python程序如何封装成接口_把你的python算法封装成HTTP接口

0ab8d35057ace48116b1d747b9988d5a.gif8b1c13c29830d6d8c7ce79d072481e0c.png3e6e4cded2d1bd40d56d64fe20f04135.png

9b3d7b7e6666e31f734cb1ab9d23c7ea.gif

python提供了很多web框架,帮助我们快速构建API,如 Flask、FastAPI、Tornado。 Flask、FastAPI如出一辙,所以这里只讲 FastAPI、Tornado,如何构建GET和POST接口。

一、安装需要的包

pip install fastapi pip install uvicorn pip install tornado

二、FastAPI的get/post接口服务

get/post接口
# -*- coding: utf-8 -*-from fastapi import FastAPIfrom pydantic import BaseModel  app = FastAPI()class Item(BaseModel):    a: int = None    b: int = None @app.get('/test/a={a}/b={b}')def calculate(a: int=None, b: int=None):    c = a + b    res = {"res":c}    return res@app.post('/test')def calculate(request_data: Item):    a = request_data.a    b = request_data.b    c = a + b    res = {"res":c}    return res  if __name__ == '__main__':    import uvicorn    uvicorn.run(app=app,                host="localhost",                port=8000,                workers=1)
将上述代码保存为get.py,存储在某一路径首先,进入python文件路径,在控制台启动服务

9ab223b518c5ab61c8d949de557306e6.png

①浏览器测试:访问 http://localhost:8000/test/a=31/b=12

5731063b8943687f55dd615fb68a6719.png

②postman测试:

bbba3e4cc61c45a29f741c9f79897f13.png

③FastAPI的交互测试: 访问 http://localhost:8000/docs

152f7258e60cfe6bf7ca4ab01901206a.png

三、Tornado的get/post接口服务

据称,Tornado比FastAPI更能承受高并发。 get/post接口
import tornado.httpserverimport tornado.ioloopimport tornado.optionsimport tornado.webfrom tornado import genfrom tornado.concurrent import run_on_executorfrom concurrent.futures import ThreadPoolExecutorimport timefrom tornado.options import define, optionsfrom tornado.platform.asyncio import to_asyncio_future,AsyncIOMainLoopfrom tornado.httpclient import AsyncHTTPClientimport asynciodefine("port", default=8000, help="just run", type=int)class MainHandler(tornado.web.RequestHandler):    def main(self,a,b):        c = float(a) + float(b)        res = {"res":c}        return res        # get接口         def get(self):        a = self.get_body_argument('a')        b = self.get_body_argument('b')        res = self.main(a,b) # 主程序计算        self.write(json.dumps(res,ensure_ascii=False))        # post接口       def post(self):        a = self.get_body_argument('a')        b = self.get_body_argument('b')        res = int(a) * int(b) #主程序计算        self.write(json.dumps(res,ensure_ascii=False))         if __name__ == "__main__":    #运行程序    application = tornado.web.Application([(r"/test", MainHandler),])    application.listen(8000,'localhost')    tornado.ioloop.IOLoop.instance().start()

get接口测试:

f994abe5489c271a72777b4cb6328af5.png

post接口测试:

0774f0a4a9eeddeda70b9bb31d0efaaa.png

你get了么?

今天也要

加油鸭!

d7b3f852f02c12651264fcb25887d05b.png

版权声明:本文为weixin_42513616原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。