标签: fastapi

使用 Pydantic 和 FastAPI 的 PurePath 的 JSON 模式无法声明错误值

我正在尝试向我的模型添加一个path类型字段PureWindowsPath。按照此处建议实现自定义验证器后https://github.com/samuelcolvin/pydantic/issues/2089#issuecomment-890018075在尝试访问 SwaggerUI 时出现以下错误:

INFO:     127.0.0.1:7696 - "GET /api/openapi.json HTTP/1.1" 500 Internal Server Error
ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "C:\Users\xxx\.virtualenvs\server-J9mXI7Iu\lib\site-packages\uvicorn\protocols\http\httptools_impl.py", line 371, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "C:\Users\xxx\.virtualenvs\server-J9mXI7Iu\lib\site-packages\uvicorn\middleware\proxy_headers.py", line 59, in __call__
    return await self.app(scope, receive, send)
  File "C:\Users\xxx\.virtualenvs\server-J9mXI7Iu\lib\site-packages\fastapi\applications.py", line 208, in __call__
    await super().__call__(scope, receive, send)
  File "C:\Users\xxx\.virtualenvs\server-J9mXI7Iu\lib\site-packages\starlette\applications.py", line 112, in __call__
    await self.middleware_stack(scope, receive, send)
  File "C:\Users\xxx\.virtualenvs\server-J9mXI7Iu\lib\site-packages\starlette\middleware\errors.py", line 181, in __call__
    raise exc …
Run Code Online (Sandbox Code Playgroud)

python pydantic fastapi

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

FastApi:如何定义一次全局变量

我想定义一个从文本文件生成的 dict 变量一次,并用它来响应 API 请求。

该变量应该始终可用,直到服务器运行结束。

在下面的示例中:

from fastapi import FastAPI
import uvicorn

app = FastAPI()

def init_data(path):
    print("init call")
    data = {}
    data[1] = "123"
    data[2] = "abc"
    return data

data = init_data('path')

@app.get('/')
def example_method():
    # data is defined
    return {'Data': data[1]}

if __name__ == '__main__':
    uvicorn.run(f'example_trouble:app', host='localhost', port=8000)
Run Code Online (Sandbox Code Playgroud)

我会得到:

init call
init call
INFO:     Started server process [9356]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://localhost:8000 (Press CTRL+C to quit)
Run Code Online (Sandbox Code Playgroud)

向 …

python asgi fastapi

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

如何使用 Pydantic/FastAPI 正确处理 SQLAlchemy 的连接结果

我想要一些关于处理在 SQLAlchemy 中执行的连接操作的结果并使用 Pydantic(在 FastAPI 中)进行序列化的建议。

如果我没记错的话,两个表的连接结果会生成 SQLAlchemy 模型的元组列表。这是它的模拟,like_a_join是我对连接查询结果的理解。

from pydantic import BaseModel
from sqlalchemy import Column, Integer
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()


class A(BaseModel):
    a: int

    class Config:
        orm_mode = True


class B(BaseModel):
    b: int

    class Config:
        orm_mode = True


class Am(Base):
    __tablename__ = "A"
    a = Column(Integer, primary_key=True, nullable=False)


class Bm(Base):
    __tablename__ = "B"
    b = Column(Integer, primary_key=True, nullable=False)


def like_a_join():
    return [(Am(a=1), Bm(b=1))]
Run Code Online (Sandbox Code Playgroud)

虽然可以将模型对象传递给 Pydantic 以进行from_orm简单查询(例如在 FastAPI Postgres 饼干切割机上完成,但对我来说,如何最好地处理连接/元组情况并不明显。 …

python sqlalchemy pydantic fastapi

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

带有 FastAPI 的异步 SqlAlchemy:为所有请求获取单个会话

我最近将使用 FastApi 编码的 REST API 迁移到新的 SQLAlchemy 1.4+ 异步版本。我的应用程序编译正确,数据库似乎设置得很好。当我尝试执行多个请求时,会出现问题,出现错误,似乎表明同一会话正在用于我的所有请求。我把错误信息放在最后

这是我的代码,我基于 SQLAlchemy 异步文档和此示例

应用程序引擎初始化

from typing import AsyncIterator
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

from .notification import Notification
from .devices import Device



from sqlalchemy import MetaData
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy import create_engine

from app.core.config import Config
from app.core.constants import logger
import asyncio

engine = create_async_engine(Config.RDS_DB_URL)
metadata = MetaData(engine)

#if not engine.dialect.has_table(engine, C.NOTIFICATIONS):
#Base.metadata.create_all(engine)

async def init_connection():
    async with engine.begin() as conn:
        await …
Run Code Online (Sandbox Code Playgroud)

python sqlalchemy python-asyncio asyncpg fastapi

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

如何在 FastAPI RealWorld 示例应用程序中应用事务逻辑?

我正在使用nsidnev/fastapi-realworld-example-app

我需要将事务逻辑应用到这个项目中。

在一个 API 中,我从存储库调用许多方法,并在许多表中执行更新、插入和删除操作。如果这些操作出现异常,我该如何回滚更改?(或者如果一切正确则提交。)

python asyncpg fastapi

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

fromtyping_extensions import ParamSpec ImportError:无法从“typing_extensions”导入名称“ParamSpec”

我正在研究 FastAPI 并发生了这个错误。

from fastapi import FastAPI
import uvicorn
app = FastAPI()

@app.get("/ping")
async def ping():
    return "Hello, I am alive"

if __name__ == "__main__":
    uvicorn.run(app, host='localhost', port=8000)
Run Code Online (Sandbox Code Playgroud)
Traceback (most recent call last):
  File "D:/own_thesis/training/for_api.py", line 2, in <module>
    from fastapi import FastAPI
  File "C:\Users\USER\AppData\Local\Programs\Python\Python37\lib\site-packages\fastapi\__init__.py", line 7, in <module>
    from .applications import FastAPI as FastAPI
  File "C:\Users\USER\AppData\Local\Programs\Python\Python37\lib\site-packages\fastapi\applications.py", line 15, in <module>
    from fastapi import routing
  File "C:\Users\USER\AppData\Local\Programs\Python\Python37\lib\site-packages\fastapi\routing.py", line 22, in <module>
    from fastapi.datastructures import Default, DefaultPlaceholder
  File "C:\Users\USER\AppData\Local\Programs\Python\Python37\lib\site-packages\fastapi\datastructures.py", line 3, …
Run Code Online (Sandbox Code Playgroud)

fastapi

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

FastAPI、robots.txt 和 noindex

FastAPI 是否需要 robots.txt 和标签 noindex?我正在创建不应该由匿名调用的业务 api 应用程序。所以我想知道我是否必须准备robots.txt和标签noindex以避免任何爬虫的操作。

我制作了 robots.txt 路由器,如下所示:

@router.get('/robots.txt')
def robots():
    data = """
    User-agent: *
    Disallow: /
    """
    return Response(content=data, media_type='text/plain')
Run Code Online (Sandbox Code Playgroud)

我需要再做一次改变吗?

robots.txt noindex fastapi

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

如何使用 FastAPI 从 HTTP 请求中获取 cookie?

当有人点击 API 时是否可以获取 cookie?我需要读取每个请求的cookie。

@app.get("/")
async def root(text: str, sessionKey: str = Header(None)):
    print(sessionKey)
    return {"message": text+" returned"}

if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=5001 ,reload=True)
Run Code Online (Sandbox Code Playgroud)

python cookies http starlette fastapi

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

FastAPI - 带有模块化导入的“TypeError: issubclass() arg 1 必须是一个类”

当使用 FastAPI 和 SQLModel 进行模块化导入时,如果打开 /docs,我会收到以下错误:

类型错误:issubclass() arg 1 必须是一个类

  • Python 3.10.6
  • pydantic 1.10.2
  • 快速API 0.85.2
  • sqlmodel 0.0.8
  • macOS 12.6

这是一个可重现的示例。

用户.py

from typing import List, TYPE_CHECKING, Optional
from sqlmodel import SQLModel, Field

if TYPE_CHECKING:
    from item import Item

class User(SQLModel):
    id: int = Field(default=None, primary_key=True)
    age: Optional[int]
    bought_items: List["Item"] = []
Run Code Online (Sandbox Code Playgroud)

项目.py

from sqlmodel import SQLModel, Field

class Item(SQLModel):
    id: int = Field(default=None, primary_key=True)
    price: float
    name: str
Run Code Online (Sandbox Code Playgroud)

主要.py

from fastapi import FastAPI

from user import User

app = …
Run Code Online (Sandbox Code Playgroud)

python sqlalchemy pydantic fastapi sqlmodel

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

JWT 集不包含任何可用的密钥

在使用 fastapi 的 okta 应用程序设置 Auth0 身份验证时,我们收到以下错误,

jwt.exceptions.PyJWKSetError: The JWK Set did not contain any usable keys
Run Code Online (Sandbox Code Playgroud)

我们遵循以下链接中详细说明的指南来使用 auth0 实施快速 api 授权。

https://auth0.com/blog/build-and-secure-fastapi-server-with-auth0/

以下代码用于验证创建的令牌。给定的错误出现在验证函数的第一个 try 块中。

class VerifyToken():
"""Does all the token verification using PyJWT"""
def __init__(self, token):
    self.token = token
    self.config = set_up()
    print(self.config)
    # This gets the JWKS from a given URL and does processing so you can
    # use any of the keys available
    jwks_url = f'https://{self.config["DOMAIN"]}/.well-known/jwks.json'
    self.jwks_client = jwt.PyJWKClient(jwks_url)
def verify(self):
    # This gets the 'kid' …
Run Code Online (Sandbox Code Playgroud)

okta auth0 fastapi

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