众所周知,在FreeBSD下安装有些python包会不太顺利,比如安装FastAPI
用pkg安装FastAPI
可以用pkg来安装:
pkg install py311-uvicorn py311-fastapi
但是这样安装后,运行fastapi可能会报错:
File "/usr/local/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1520, in _typed_dict_schema
td_schema = core_schema.typed_dict_schema(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: typed_dict_schema() got an unexpected keyword argument 'cls'
用pip安装FastAPI
这时候需要再用pip来安装。但是pip有些库装不上,这时候就要配合用pkg安装相关库。
先激活环境:
source py311/bin/activate.csh
然后使用pip安装:
pip install ujson orjson markupsafe pydantic_core
pip install uvloop watchfiles
pydantic-core, httptools
手工安装了pydantic_core,结果安装fastapi的时候又需要安装,仔细一看,原来自己敲成了pydantic_core ,而需要的是pydantic-core,也就是最终执行命令:
pip install ujson orjson markupsafe
pip install uvloop watchfiles
pip install pydantic-core, httptools
最终安装完成:
pip install "fastapi[all]"
Successfully installed annotated-types-0.7.0 click-8.1.7 dnspython-2.7.0 email-validator-2.2.0 fastapi-0.115.4 fastapi-cli-0.0.5 httptools-0.6.4 itsdangerous-2.2.0 jinja2-3.1.4 pydantic-2.9.2 pydantic-core-2.23.4 pydantic-extra-types-2.9.0 pydantic-settings-2.6.0 python-multipart-0.0.16 starlette-0.41.2 typer-0.12.5 typing-extensions-4.12.2 uvicorn-0.32.0 websockets-13.1
如果安装过程中有库实在装不上,就用pkg search xx来找到FreeBSD下的pkg包,用pkg install py311-xx的方式来安装一下,然后再pip安装就能装上了,比如:
pkg install py311-watchfiles
pkg install py311-uvloop
pkg install py311-uvicorn
测试
测试源代码
将下面代码写入的dependsclass.py文件:
from fastapi import Depends, FastAPI
app = FastAPI()
fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
class CommonQueryParams:
def __init__(self, q: str | None = None, skip: int = 0, limit: int = 100):
self.q = q
self.skip = skip
self.limit = limit
@app.get("/items/")
async def read_items(commons=Depends(CommonQueryParams)):
response = {}
if commons.q:
response.update({"q": commons.q})
items = fake_items_db[commons.skip : commons.skip + commons.limit]
response.update({"items": items})
return response
保存为dependsclass.py
启动服务:
uvicorn dependsclass:app --reload
curl测试:
curl 127.0.0.1:8000/items/
{"items":[{"item_name":"Foo"},{"item_name":"Bar"},{"item_name":"Baz"}]}
效果不错!
注意,FreeBSD下默认使用pf防火墙康,不要忘记打开防火墙的8000端口
调试:
启动uvicorn后报错
File "/usr/local/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 999, in match_type
return self._typed_dict_schema(obj, None)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1520, in _typed_dict_schema
td_schema = core_schema.typed_dict_schema(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: typed_dict_schema() got an unexpected keyword argument 'cls'
确认安装好fastapi,并更新该python3.11环境,再试后问题解决。