我很想在 FastAPI 中使用类似于以下内容的架构:
from __future__ import annotations
from typing import List
from pydantic import BaseModel
class Project(BaseModel):
members: List[User]
class User(BaseModel):
projects: List[Project]
Project.update_forward_refs()
Run Code Online (Sandbox Code Playgroud)
但为了保持我的项目结构干净,我会关闭。喜欢在单独的文件中定义这些。我怎么能在不创建循环引用的情况下做到这一点?
使用上面的代码,FastAPI 中的模式生成工作正常,我只是不知道如何将它分成单独的文件。在后面的步骤中,我将不再使用属性,而是使用@propertys 在它们的子类中为这些对象定义 getter。但是对于 OpenAPI 文档生成,我需要将其结合起来 - 我认为。
我通过 POST 接受该文件。本地保存时,可以使用file.read()读取内容,但是显示通过file.name不正确(16)的名称。当我尝试按此名称查找它时,出现错误。可能是什么问题?
我的代码:
@router.post(
path="/po/{id_po}/upload",
response_model=schema.ContentUploadedResponse,
)
async def upload_file(
id_po: int,
background_tasks: BackgroundTasks,
uploaded_file: UploadFile = File(...)):
"""pass"""
uploaded_file.file.rollover()
uploaded_file.file.flush()
#shutil.copy(uploaded_file.file.name, f'/home/fyzzy/Desktop/api/{uploaded_file.filename}')
background_tasks.add_task(s3_upload, uploaded_file=fp)
return schema.ContentUploadedResponse()
Run Code Online (Sandbox Code Playgroud) 假设我有以下观点,
from fastapi import FastAPI
app = FastAPI()
@app.get('/hello/')
def hello_world():
return {"msg": "Hello World"}
@app.get('/hello/{number}/')
def hello_world_number(number: int):
return {"msg": "Hello World Number", "number": number}
Run Code Online (Sandbox Code Playgroud)
我一直在 Flask 和 Django 中使用这些函数
所以,我怎样才能获得/建立的网址,hello_world并hello_world_number以类似的方式?
我们已经使用 FastAPI 创建了一个服务。当我们的服务启动时,它会创建一些 Python 对象,然后端点使用这些对象来存储或检索数据。
生产中的 FastAPI 从多个工人开始。我们的问题是每个工人创建自己的对象而不是共享一个。
下面的脚本显示了我们正在做的(简化的)示例,尽管在我们的例子中 Meta() 的使用要复杂得多。
from fastapi import FastAPI, status
class Meta:
def __init__(self):
self.count = 0
app = FastAPI()
meta = Meta()
# increases the count variable in the meta object by 1
@app.get("/increment")
async def increment():
meta.count += 1
return status.HTTP_200_OK
# returns a json containing the current count from the meta object
@app.get("/report")
async def report():
return {'count':meta.count}
# resets the count in the meta object to 0
@app.get("/reset") …Run Code Online (Sandbox Code Playgroud) 部署使用 Uvicorn 和Tiangolo 的 Gunicorn+Uvicorn dockerized 的FastAPI 应用程序有什么区别?为什么我的结果表明,仅使用 Uvicorn 进行部署时我会得到比 Gunicorn+Uvicorn 更好的结果?
当我在 Tiangolo 的文档中搜索时,它说:
您可以使用 Gunicorn 来管理 Uvicorn 并运行多个这些并发进程。这样,您可以获得最佳的并发性和并行性。
由此,我可以假设使用这个 Gunicorn 会得到更好的结果吗?
这是我使用 JMeter 进行的测试。我将脚本部署到 Google Cloud Run,结果如下:
使用 Python 和 Uvicorn:
使用 Tiangolo 的 Gunicorn+Uvicorn:
这是我的 Python Dockerfile (Uvicorn):
FROM python:3.8-slim-buster
RUN apt-get update --fix-missing
RUN DEBIAN_FRONTEND=noninteractive apt-get install -y libgl1-mesa-dev python3-pip git
RUN mkdir /usr/src/app
WORKDIR /usr/src/app
COPY ./requirements.txt /usr/src/app/requirements.txt
RUN pip3 install -U setuptools
RUN pip3 install --upgrade pip
RUN pip3 install -r ./requirements.txt …Run Code Online (Sandbox Code Playgroud) 我有一个用 Uvicorn + FastAPI 编写的应用程序。我正在使用 PyTest 测试响应时间。
参考如何在使用 PyTest 进行测试时在后台启动 Uvicorn + FastAPI,我编写了测试。然而,当工人> = 2时,我在完成测试后发现应用程序进程处于活动状态。
我想在测试结束时干净地终止应用程序进程。
你有什么主意吗?
详情如下。
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def hello_world():
return "hello world"
Run Code Online (Sandbox Code Playgroud)
from multiprocessing import Process
import pytest
import requests
import time
import uvicorn
HOST = "127.0.0.1"
PORT = 8765
WORKERS = 1
def run_server(host: str, port: …Run Code Online (Sandbox Code Playgroud)注意:这个问题与这里的问题不同,因为我需要它与 Swagger 一起工作。
给定一个 FastAPIGET端点,我希望允许任意一组 URL 参数,同时保持 Swagger 支持。
我的用例是我想要支持一组类似于 JSON API 的查询参数,如下所示:
/api/books/?include=author&sort=name,zip&sort[author]=-lname&fields=name,phone,street
Run Code Online (Sandbox Code Playgroud)
使用方括号使我无法使用传统的类来对查询参数进行建模,因此我直接使用该Request对象。但是,我想使用 Swagger 来测试端点。我找不到提供任意 URL 参数的方法。我很高兴将它们作为单个字符串输入。
人们可能会这样想:
def books(**params):
....
Run Code Online (Sandbox Code Playgroud)
这给出了一个curl语句:
api/books?params=sort%5Bone%5D%3Dtwo'
Run Code Online (Sandbox Code Playgroud)
我真正想要的是:
api/books?sort&one%5D%3Dtwo'
Run Code Online (Sandbox Code Playgroud) 我有一个连接到 MongoDB 的多语言 FastAPI。我在 MongoDB 中的文档以两种可用语言复制,并以这种方式构建(简化示例):
\n\n{\n "_id": xxxxxxx,\n "en": { \n "title": "Drinking Water Composition",\n "description": "Drinking water composition expressed in... with pesticides.",\n "category": "Water", \n "tags": ["water","pesticides"] \n },\n "fr": { \n "title": "Composition de l\'eau de boisson",\n "description": "Composition de l\'eau de boisson exprim\xc3\xa9e en... pr\xc3\xa9sence de pesticides....",\n "category": "Eau", \n "tags": ["eau","pesticides"] \n }, \n}\n\nRun Code Online (Sandbox Code Playgroud)\n因此,我实现了两个模型DatasetFR和,每个模型都对每种语言中的特定外部模型 ( )DatasetEN进行引用。Enumcategorytags
class DatasetFR(BaseModel):\n title:str\n description: str\n category: CategoryFR\n tags: …Run Code Online (Sandbox Code Playgroud) 当我使用 docker-compose 安装 fastapi 项目时,我得到了AssertionError: jinja2 must be installed to use Jinja2Templates
但是当我使用 env 安装它时,它将运行良好。
我的操作系统:
Ubuntu18.04STL
我的要求.txt:
fastapi~=0.68.2
starlette==0.14.2
pydantic~=1.8.1
uvicorn~=0.12.3
SQLAlchemy~=1.4.23
# WSGI
Werkzeug==1.0.1
pyjwt~=1.7.0
# async-exit-stack~=1.0.1
# async-generator~=1.10
jinja2~=2.11.2
# assert aiofiles is not None, "'aiofiles' must be installed to use FileResponse"
aiofiles~=0.6.0
python-multipart~=0.0.5
requests~=2.25.0
pyyaml~=5.3.1
# html-builder==0.0.6
loguru~=0.5.3
apscheduler==3.7.0
pytest~=6.1.2
html2text==2020.1.16
mkdocs==1.2.1
Run Code Online (Sandbox Code Playgroud)
Dockerfile
FROM python:3.8
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
WORKDIR /server
COPY requirements.txt /server/
RUN pip install -r requirements.txt
COPY . /server/
Run Code Online (Sandbox Code Playgroud)
docker-compose.yml …
我有以下代码片段:
from passlib.context import CryptContext
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
pwd_context.hash(password)
Run Code Online (Sandbox Code Playgroud)
这里描述的是。
我不明白的是,如果它始终返回相同的散列密码而不考虑另一个 Secret_key 例如散列密码值,这怎么可能是安全的?