标签: fastapi

FastAPI 以串行方式而不是并行方式运行 api 调用

我有以下代码:

import time
from fastapi import FastAPI, Request
    
app = FastAPI()
    
@app.get("/ping")
async def ping(request: Request):
        print("Hello")
        time.sleep(5)
        print("bye")
        return {"ping": "pong!"}
Run Code Online (Sandbox Code Playgroud)

如果我在本地主机上运行我的代码 - 例如http://localhost:8501/ping- 在同一浏览器窗口的不同选项卡中,我得到:

Hello
bye
Hello
bye
Run Code Online (Sandbox Code Playgroud)

代替:

Hello
Hello
bye
bye
Run Code Online (Sandbox Code Playgroud)

我已经阅读过有关使用的内容httpx,但仍然无法实现真正​​的并行化。有什么问题?

python asynchronous concurrent-processing python-asyncio fastapi

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

在返回 FastAPI + uvicorn + Docker 应用程序上托管的状态 200 之前,不断收到“307 临时重定向” - 如何返回状态 200?

编辑:

我发现了问题,但不确定为什么会发生这种情况。每当我查询:最后http://localhost:4001/hello/带有“ ”时 - 我都会得到正确的 200 状态响应。/我不懂为什么。

原帖:

每当我向我的应用程序发送查询时,我都会收到 307 重定向。如何让我的应用返回常规状态 200,而不是通过 307 重定向

这是请求输出:

abm                  | INFO:     172.18.0.1:46476 - "POST /hello HTTP/1.1" 307 Temporary Redirect
abm                  | returns the apples data. nothing special here.
abm                  | INFO:     172.18.0.1:46480 - "POST /hello/ HTTP/1.1" 200 OK
Run Code Online (Sandbox Code Playgroud)

pytest 返回:

E       assert 307 == 200
E        +  where 307 = <Response [307]>.status_code

test_main.py:24: AssertionError
Run Code Online (Sandbox Code Playgroud)

在我的根目录:/__init__.py文件:

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
# from .configs import …
Run Code Online (Sandbox Code Playgroud)

python redirect http-status-code-307 fastapi

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

如何在 FastAPI 测试之间建立和拆除数据库?

我已经按照 FastAPI文档设置了单元测试,但它只涵盖了数据库在测试中保留的情况。

如果我想在每次测试时构建和拆除数据库怎么办?(例如,下面的第二个测试将失败,因为第一个测试后数据库将不再为空)。

我目前通过在每个测试的开始和结束时调用 and (在下面的代码中注释掉)来create_all做到这一点,但这显然不理想(如果测试失败,数据库将永远不会被拆除,影响下一个测试的结果drop_all测试)。

我怎样才能正确地做到这一点?我应该围绕依赖关系创建某种 Pytest 固定装置吗override_get_db

from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

from main import app, get_db
from database import Base

SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"

engine = create_engine(
    SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# Base.metadata.create_all(bind=engine)

def override_get_db():
    try:
        db = TestingSessionLocal()
        yield db
    finally:
        db.close()

app.dependency_overrides[get_db] = override_get_db

client = TestClient(app)

def test_get_todos():
    # Base.metadata.create_all(bind=engine)

    # …
Run Code Online (Sandbox Code Playgroud)

python unit-testing fastapi

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

如何在 fastAPI 中返回图像?

使用 python 模块fastAPI,我不知道如何返回图像。在烧瓶中,我会做这样的事情:

@app.route("/vector_image", methods=["POST"])
def image_endpoint():
    # img = ... # Create the image here
    return Response(img, mimetype="image/png")
Run Code Online (Sandbox Code Playgroud)

这个模块中对应的调用是什么?

python api fastapi

37
推荐指数
7
解决办法
3万
查看次数

加载index.html的最小fastapi示例

在我的项目文件夹中,我有一个基本index.html文件加上静态文件(js、css)以及我的main.py

from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi import Request

app = FastAPI()

templates = Jinja2Templates(directory="/")
app.mount("/", StaticFiles(directory="/"))

@app.get("/")
def serve_home(request: Request):
    return templates.TemplateResponse("index.html", context= {"request": request}) 
Run Code Online (Sandbox Code Playgroud)

我怎样才能让fastapi在这里工作?我只想index.html在本地主机上提供我的静态文件。没有staticortemplates文件夹有问题吗?

fastapi

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

是否可以更改 pydantic 中的输出别名?

设置:

# Pydantic Models

class TMDB_Category(BaseModel):
    name: str = Field(alias="strCategory")
    description: str = Field(alias="strCategoryDescription")


class TMDB_GetCategoriesResponse(BaseModel):
    categories: list[TMDB_Category]


@router.get(path="category", response_model=TMDB_GetCategoriesResponse)
async def get_all_categories():
    async with httpx.AsyncClient() as client:
        response = await client.get(Endpoint.GET_CATEGORIES)
        return TMDB_GetCategoriesResponse.parse_obj(response.json())
Run Code Online (Sandbox Code Playgroud)

问题:
创建响应时使用别名,我想避免它。我只需要这个别名来正确映射传入数据,但在返回响应时,我想使用实际的字段名称。

实际响应:

{
  "categories": [
    {
      "strCategory": "Beef",
      "strCategoryDescription": "Beef is ..."
    },
    {
      "strCategory": "Chicken",
      "strCategoryDescription": "Chicken is ..."
    }
}
Run Code Online (Sandbox Code Playgroud)

预期回应:

{
  "categories": [
    {
      "name": "Beef",
      "description": "Beef is ..."
    },
    {
      "name": "Chicken",
      "description": "Chicken is ..."
    }
}
Run Code Online (Sandbox Code Playgroud)

python json json-deserialization pydantic fastapi

34
推荐指数
3
解决办法
6万
查看次数

FastAPI - GET 请求导致类型错误(值不是有效的字典)

这是我的数据库架构。

\n

在此输入图像描述

\n

我这样定义我的架构:

\n

从 pydantic 导入 BaseModel

\n
class Userattribute(BaseModel):\n    name: str\n    value: str\n    user_id: str\n    id: str\n
Run Code Online (Sandbox Code Playgroud)\n

这是我的模型:

\n
class Userattribute(Base):\n    __tablename__ = "user_attribute"\n\n    name = Column(String)\n    value = Column(String)\n    user_id = Column(String)\n    id = Column(String, primary_key=True, index=True)\n
Run Code Online (Sandbox Code Playgroud)\n

在 crud.py 中我定义了一个get_attributes方法。

\n
def get_attributes(db: Session, skip: int = 0, limit: int = 100):\n    return db.query(models.Userattribute).offset(skip).limit(limit).all()\n
Run Code Online (Sandbox Code Playgroud)\n

这是我的GET终点:

\n
@app.get("/attributes/", response_model=List[schemas.Userattribute])\ndef read_attributes(skip: int = 0, limit: int = 100, db: Session = …
Run Code Online (Sandbox Code Playgroud)

python get pydantic fastapi

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

FastAPI 抛出错误(错误加载 ASGI 应用程序。无法导入模块“api”)

我尝试使用 uvicorn 网络服务器运行 FastAPI,但它引发了错误。

我运行这个命令,

uvicorn api:app --reload --host 0.0.0.0

但是终端有错误。

Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
Started reloader process [23445]
Error loading ASGI app. Could not import module "api".
Stopping reloader process [23445]
Run Code Online (Sandbox Code Playgroud)

我真的很感激任何建议或建议

python fastapi uvicorn

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

如何从后端 API 获取标头或特定标头?

我想使用 fastAPI 从函数内的 API 中检索特定标头,但我找不到解决方案。

在烧瓶中很简单:request.headers['your-header-name']

为什么 fastAPI 做这么简单的事情却这么复杂?

有人知道检索标头的解决方案吗?谢谢 :)

装饰者:

def token_required(f):
    @wraps(f)
    def decorator(*args, **kwargs):
        CONFIG = settings.read_config()
        token = None
        headers = Request.headers
        if "Authorization" in headers:
            auth_header = Request.headers
            token = auth_header
        elif not token:
            return {"Error": "Token is missing or incorrect header name"}, 401

        try:
            public_key = CONFIG["APPLICATION"]["PUBLIC_KEY"]
            claim = jwt.decode(token, public_key)
            claim.validate()
        except UnicodeDecodeError as err:
            return {"Error": f"An error occurred -> {err} check your token"}, 401

        return f(*args, **kwargs)

    return decorator …
Run Code Online (Sandbox Code Playgroud)

python fastapi

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

如何使用 Pycharm 运行 fast-api 服务器?

我有一个简单的 API 函数,如下所示,

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def read_root():
    return {"Hello": "World"}
Run Code Online (Sandbox Code Playgroud)

我正在使用uvicorn命令启动服务器,

uvicorn main:app
Run Code Online (Sandbox Code Playgroud)

由于我们没有直接调用任何 python 文件,因此无法uvicorn从 Pycharm调用命令。

那么,如何使用 Pycharm 运行 fast-api 服务器?

python pycharm fastapi

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