社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
一、安装需要的包
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文件路径,在控制台启动服务
①浏览器测试:访问
http://localhost:8000/test/a=31/b=12
②postman测试:
③FastAPI的交互测试:
访问
http://localhost:8000/docs
三、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接口测试:
post接口测试:
你get了么?今天也要
加油鸭!
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!