标签: fastapi

覆盖 FastAPI 中 jsonable_encoder 的默认编码器

我有使用Fast API 的代码,看起来像这样:

class EnumTestT(Enum):
    test_t_value = 0

object = { 
    test: test_t_value
}

enum_mapping = {
    test_t_value: "Test"
}

def enum_encoder(val: EnumTestT) -> str:
    return enum_mapping[val]

custom_encoder = {
    EnumTestT: enum_encoder
}

@app.get("/test")
async def test_get():
    return jsonable_encoder(object, custom_encoder=custom_encoder)
Run Code Online (Sandbox Code Playgroud)

问题是jsonable_encoder在默认编码器之后应用自定义编码器。有什么方法可以在默认编码器之前应用它们。因为对于Enum任何派生类,报告的是枚举值而不是映射值。

python fastapi

9
推荐指数
2
解决办法
2万
查看次数

FastAPI 应用程序在本地运行,但不在 Docker 容器中运行

我有一个 FastAPI 应用程序,在本地运行时按预期工作,但是,当我尝试在 Docker 容器中运行时,出现“内部服务器错误”。这是我的应用程序的代码:

from fastapi import FastAPI
from pydantic import BaseModel
import pandas as pd
from fbprophet import Prophet

class Data(BaseModel):
    length: int
    ds: list
    y: list
    model: str
    changepoint: float = 0.5
    daily: bool = False
    weekly: bool = False
    annual: bool = False
    upper: float = None
    lower: float = 0.0
    national_holidays: str = None

app = FastAPI()

@app.post("/predict/")
async def create_item(data: Data):

    # Create df from base model
    df = pd.DataFrame(list(zip(data.ds, data.y)), columns =['ds', 'y']) …
Run Code Online (Sandbox Code Playgroud)

python docker facebook-prophet fastapi

9
推荐指数
3
解决办法
1万
查看次数

pydantic 模型中的对象属性列表

我使用 Fast API 创建 Web 服务。

有以下 sqlAlchemy 模型:

class User(Base):
    __tablename__ = 'user'
    account_name = Column(String, primary_key=True, index=True, unique=True)
    email = Column(String, unique=True, index=True, nullable=False)
    roles = relationship("UserRole", back_populates="users", lazy=False, uselist=True)


class UserRole(Base):
    __tablename__ = 'user_role'
    __table_args__ = (UniqueConstraint('role_name', 'user_name', name='user_role_uc'),)
    role_name = Column(String, ForeignKey('role.name'), primary_key=True)
    user_name = Column(String, ForeignKey('user.account_name'), primary_key=True)
    users = relationship("User", back_populates="roles")
Run Code Online (Sandbox Code Playgroud)

Pydantic 架构如下:

class UserRole(BaseModel):
    role_name: str

    class Config:
        orm_mode = True


class UserBase(BaseModel):
    account_name: str
    email: EmailStr
    roles: List[UserRole] = []

    class Config:
        orm_mode …
Run Code Online (Sandbox Code Playgroud)

python sqlalchemy pydantic fastapi

9
推荐指数
1
解决办法
2万
查看次数

单独文件中的 FastAPI / Pydantic 循环引用

我很想在 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 文档生成,我需要将其结合起来 - 我认为。

python circular-dependency pydantic fastapi

9
推荐指数
3
解决办法
1769
查看次数

如何在 FastAPI 中保存 UploadFile

我通过 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)

python temporary-files python-asyncio fastapi

9
推荐指数
2
解决办法
9251
查看次数

FastAPI:从视图名称(路由名称)中检索 URL

假设我有以下观点,

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以类似的方式?

python python-3.x fastapi

9
推荐指数
2
解决办法
5233
查看次数

FastAPI - 带有 Pydantic 列表字段的 GET 请求

GET我是 FastAPI 的新手(从 Flask 迁移),我正在尝试为我的路线创建一个 Pydantic 模型:

from fastapi import APIRouter,Depends
from pydantic import BaseModel
from typing import Optional,List

router = APIRouter()

class SortModel(BaseModel):
    field:    Optional[str]
    directions: List[str]

@router.get("/pydanticmodel")
def get_sort(criteria: SortModel = Depends(SortModel)):
    pass #my code for handling this route.....
Run Code Online (Sandbox Code Playgroud)

当我跑步时 curl -X GET http://localhost:XXXX/pydanticmodel?directions=up&directions=asc&field=id 我得到422 Unprocessable Entity: {"detail":[{"loc":["body"],"msg":"field required","type":"value_error.missing"}]}

但如果我正在改变directions:List[str]->directions: str我正在200 OK接受directions="asc". str对于查询参数有效而List[str]无效的原因是什么?我究竟做错了什么?

谢谢。

python pydantic fastapi

9
推荐指数
2
解决办法
8652
查看次数

fastapi - 可选的 OAuth2 身份验证

我需要创建一个具有路由的 API,该路由能够识别当前用户是否是请求中指示的用户(而且任何身份验证都不应有效)

对于其他路径,我遵循https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt/,一切都可以与带有 JWT 令牌的 Bearer 一起使用,如下所示

user: User = Depends(get_current_active_user)
Run Code Online (Sandbox Code Playgroud)

修改我尝试过的文档提供的方法

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth")

async def get_user_or_none(db: Session = Depends(get_db), token: str = Depends(oauth2_scheme)):
    """
    Return the current active user if is present (using the token Bearer) or None
    """
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            return None
    except JWTError:
        return None
    
    # check user in db
    user = crud.get_user(db, username)
    if user is None:
        return None
    return user …
Run Code Online (Sandbox Code Playgroud)

python fastapi

9
推荐指数
1
解决办法
4688
查看次数

如何设置 FastAPI 版本以允许 HTTP 在接受标头中指定版本?

我正在开发一个需要对 FastAPI 端点进行版本控制的项目。我们希望通过 HTTP 接受标头对端点进行版本控制,例如:

headers={'Accept': 'application/json;version=1.0.1'}, 
headers={'Accept': 'application/json;version=1.0.2'}
Run Code Online (Sandbox Code Playgroud)

像这样设置 api 版本似乎不起作用:

headers={'Accept': 'application/json;version=1.0.1'}, 
headers={'Accept': 'application/json;version=1.0.2'}
Run Code Online (Sandbox Code Playgroud)

有谁知道我还需要做什么?

http api-versioning fastapi

9
推荐指数
1
解决办法
1万
查看次数

如何在 fastapi 中将 httpx AsyncClient 与 pytest 结合使用?

我已经尝试了所有我能找到的东西,但我无法让异步测试工作。

我开始RuntimeError: This event loop is already running运行TestClient(根据文档,这是有意义的),但我开始httpx.ConnectError: [Errno 8] nodename nor servname provided, or not known使用httpx AsyncClient.

我有一个简单的测试:

@pytest.fixture(scope="module")
async def async_client() -> Generator:
    async with AsyncClient(app=app, base_url='http://0.0.0.0') as client:
        yield client

@pytest.mark.asyncio@mock.patch('apps.core.views.requests.get', new=mocked_get_request)
async def test_get_non_json_response(async_client: AsyncClient):
    response = await async_client.get("/mymedia")
    assertEqual(response.json()['error']['message']['message'], 'Not json')
Run Code Online (Sandbox Code Playgroud)

哪里 /media:

@app.get('/mymedia')
async def my_media(request: Request, cache: RedisCacheBackend = Depends(redis_cache)):
    return await my_media_ep(request, cache=cache)
Run Code Online (Sandbox Code Playgroud)

my_media_ep是一个包含多个异步 api 调用的长函数。

我也按照异步测试文档中的建议进行了尝试,但得到了相同的错误。

有什么建议或例子吗?

python unit-testing pytest pytest-asyncio fastapi

9
推荐指数
0
解决办法
3114
查看次数