作者:sasame | 来源:互联网 | 2023-09-04 10:25
FastAPI
FastAPI框架,高性能,易学,快速编码,可投入生产
FastAPI是一种现代,快速(高性能)的Web框架,用于基于标准Python类型提示使用Python 3.6+构建API。
文档:https : //fastapi.tiangolo.com
源代码:https : //github.com/tiangolo/fastapi
Hello World
集各大框架于一身,站在巨人肩膀上的FastAPI环境搭建起来还是比较简单的。
短短几行代码就可以完成接口开发,与接口文档的开发。
from fastapi import FastAPIapp = FastAPI()@app.get("/")
def read_root():return {"Hello": "World"}@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):return {"item_id": item_id, "q": q}if __name__ == '__main__':import uvicornuvicorn.run(app, host="0.0.0.0", port=8000, workers=4)
API
http://127.0.0.1:8000/
交互式API文档
http://127.0.0.1:8000/docs
Windows可能的报错
报错提示1
Traceback (most recent call last):File "D:/coding/vn-var-test/test/main.py", line 19, in <module>uvicorn.run(app, host&#61;&#39;127.0.0.1&#39;, port&#61;8000, workers&#61;3)File "D:\Python\Python37\lib\site-packages\uvicorn\main.py", line 272, in runsocket &#61; config.bind_socket()File "D:\Python\Python37\lib\site-packages\uvicorn\config.py", line 216, in bind_socketsock.bind((self.host, self.port))
OSError: [WinError 10013] 以一种访问权限不允许的方式做了一个访问套接字的尝试。
报错提示2
由于添加了异常值处理中间件&#xff0c;报错信息看起来是序列化的问题&#xff0c;和报错提示1的问题一样
Traceback (most recent call last):File "D:/coding/ivc/app.py", line 53, in <module>uvicorn.run(app, host&#61;"127.0.0.1", port&#61;8000, workers&#61;4)File "D:\Python\Python37\lib\site-packages\uvicorn\main.py", line 274, in runsupervisor.run(server.run, sockets&#61;[socket])File "D:\Python\Python37\lib\site-packages\uvicorn\supervisors\multiprocess.py", line 33, in runprocess.start()File "D:\Python\Python37\lib\multiprocessing\process.py", line 112, in startself._popen &#61; self._Popen(self)File "D:\Python\Python37\lib\multiprocessing\context.py", line 223, in _Popenreturn _default_context.get_context().Process._Popen(process_obj)File "D:\Python\Python37\lib\multiprocessing\context.py", line 322, in _Popenreturn Popen(process_obj)File "D:\Python\Python37\lib\multiprocessing\popen_spawn_win32.py", line 65, in __init__reduction.dump(process_obj, to_child)File "D:\Python\Python37\lib\multiprocessing\reduction.py", line 60, in dumpForkingPickler(file, protocol).dump(obj)
AttributeError: Can&#39;t pickle local object &#39;FastAPI.setup.<locals>.openapi&#39;
解决方式
uvicorn.run(app, host&#61;"0.0.0.0", port&#61;8000, workers&#61;4)uvicorn.run(app, host&#61;"0.0.0.0", port&#61;8000)