标签: fastapi

Flake8 抛出 B008 fastapi 数据类型定义

我有以下代码,它POST通过 处理请求fastapi。但是,flake8不断抛出B008 Do not perform function calls in argument defaults. The call is performed only once at function definition time错误。

@app.post("/predict", status_code=200)
def predict(
    page_no: int = Form(...), dimensions: list = Form(...), image: UploadFile = File(...)
) -> Dict[str, int]:
Run Code Online (Sandbox Code Playgroud)

有没有办法修复或解决这些警告?

python typing flake8 fastapi

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

如何在带有 FastAPI 的嵌套路由器中包含路径参数?

如何将一个包含APIRouter在另一个中并指定某个路径参数是必需的前缀?

\n

对于上下文:\n假设我有组织和用户的概念。一个用户只属于一个组织。我的网络应用程序的结构如下:

\n
\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 web_app\n    \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 endpoints\n        \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 __init__.py # produces main_router by including other routers inside each other\n        \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 organization.py # contains endpoints relevant to the organization\n        \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 user.py # contains endpoints relevant to the user\n    \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 main.py # includes main_router in app\n
Run Code Online (Sandbox Code Playgroud)\n

假设我想为组织和用户实现基本的 CRUD 功能。我的端点可能看起来像这样:

\n

对于组织:

\n
GET /api/latest/org/{org_id}\nPOST /api/latest/org/{org_id}\nPUT /api/latest/org/{org_id}\nDELETE /api/latest/org/{org_id}\n
Run Code Online (Sandbox Code Playgroud)\n

对于用户:

\n
GET /api/latest/org/{org_id}/users/{user_id}\nPOST /api/latest/org/{org_id}/users/{user_id}\nPUT /api/latest/org/{org_id}/users/{user_id}\nDELETE /api/latest/org/{org_id}/users/{user_id}\n
Run Code Online (Sandbox Code Playgroud)\n

由于用户嵌套在 orgs 下,因此user.py我可以像这样编写所有端点:

\n
\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 web_app\n    \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 endpoints\n …
Run Code Online (Sandbox Code Playgroud)

python fastapi

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

url_for 在 FastAPI 中使用 HTTP 而不是 HTTPS

我有一个 html 文件,我配置了链接的 URL,如下所示。

app.mount("/static", StaticFiles(directory="static"), name="static")

{{ url_for('static', path='css/style.css') }}
Run Code Online (Sandbox Code Playgroud)

我已经使用 nginx 和 haproxy 为应用程序创建了域。

加载 html 页面时,不会加载 css 和 js 样式,因为它使用的是 http 而不是 https。

Flask url_for 在 docker 运行时生成 http 而不是 https

Jinja2 模板中 url_for 创建的 FastAPI 链接使用 HTTP 而不是 HTTPS

我使用了一些关于类似问题的链接,但没有帮助,因为它是针对 html 文件的。

当我硬编码时它起作用了。我怎样才能使这个静态。我正在使用 uvicorn fastapi。

python https jinja2 fastapi uvicorn

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

如何使用 FastAPI 和 Jinja2 模板提交 HTML 表单 <input> 值?

我在尝试将值从 HTML 表单<input>元素传递到表单的action属性并将其发送到 FastAPI 服务器时遇到以下问题。

这是 Jinja2 (HTML) 模板的加载方式:

# Test TEMPLATES
@app.get("/test",response_class=HTMLResponse)
async def read_item(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})
Run Code Online (Sandbox Code Playgroud)

我的 HTML 表单:

<form action="/disableSubCategory/{{subCatName}}">
    <label for="subCatName">SubCategory:</label><br>
    <input type="text" id="subCatName" name="subCatName" value=""><br>
    <input type="submit" value="Disable">
</form>
Run Code Online (Sandbox Code Playgroud)

我的 FastAPI 端点将在表单操作中调用:

<form action="/disableSubCategory/{{subCatName}}">
    <label for="subCatName">SubCategory:</label><br>
    <input type="text" id="subCatName" name="subCatName" value=""><br>
    <input type="submit" value="Disable">
</form>
Run Code Online (Sandbox Code Playgroud)

我得到的错误:

"GET /disableSubCategory/?subCatName=Barber HTTP/1.1" 404 Not Found
Run Code Online (Sandbox Code Playgroud)

我想要实现的是以下 FastAPI 调用:

/disableSubCategory/{subCatName} ==> "/disableSubCategory/Barber"
Run Code Online (Sandbox Code Playgroud)

谁能帮助我理解我做错了什么?

谢谢。狮子座

html python jinja2 fastapi

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

如何将FastAPI请求转发到另一台服务器?

我有一个用于测试/开发目的的 FastAPI 应用程序。我想要的是,到达我的应用程序的任何请求都会按原样自动发送到另一台服务器上的另一个应用程序,并具有完全相同的参数和相同的端点。这不是重定向,因为我仍然希望应用程序像往常一样处理请求并返回值。我只想向不同服务器上的不同版本的应用程序发起类似的请求,而不需要等待其他服务器的答复,以便其他应用程序获取该请求,就像原始请求发送给它一样。

我怎样才能做到这一点?以下是我用于处理请求的示例代码:

@app.post("/my_endpoint/some_parameters")
def process_request(
    params: MyParamsClass,
    pwd: str = Depends(authenticate),
):
    # send the same request to http://my_other_url/my_endpoint/
    return_value = process_the_request(params)
    return return_value.as_json()
Run Code Online (Sandbox Code Playgroud)

python rest request forward fastapi

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

如何从同一本地网络上的不同机器/IP 访问 FastAPI 后端?

FastAPI 后端和 Next.js 前端都在localost. 在同一台计算机上,前端可以fetch毫无问题地进行 API 调用。然而,在同一网络上的另一台计算机上,例如,在 上192.168.x.x,前端运行,但其 API 调用不再工作。

我尝试使用代理作为 next.js 但仍然不起作用。

前端:


export default function People({setPerson}:PeopleProps)  {
 const fetcher = async (url:string) => await axios.get(url).then((res) => res.data);
 const { data, error, isLoading } = useSWR(`${process.env.NEXT_PUBLIC_API}/people`, fetcher);
  if (error) return <div>"Failed to load..."</div>;
  return (
      <>
        {isLoading? "Loading..." :data.map((person: Person) =>
        <div key={person.id}> {person.name} </div>)}
     </> 
  )
 }
Run Code Online (Sandbox Code Playgroud)

Next.js 应用程序env.local在启动时加载该文件,其中包含: NEXT_PUBLIC_API=http://locahost:20002

后端:

rom typing import List
from fastapi import …
Run Code Online (Sandbox Code Playgroud)

python ip localhost next.js fastapi

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

在 FastAPI 中返回 StreamingResponse 时出现“AttributeError:encode”

我正在使用 Python 3.10 和 FastAPI0.92.0编写服务器发送事件 (SSE) 流 api。Python 代码如下所示:

from fastapi import APIRouter, FastAPI, Header

from src.chat.completions import chat_stream
from fastapi.responses import StreamingResponse

router = APIRouter()

@router.get("/v1/completions",response_class=StreamingResponse)
def stream_chat(q: str, authorization: str = Header(None)):
    auth_mode, auth_token = authorization.split(' ')
    if auth_token is None:
        return "Authorization token is missing"
    answer = chat_stream(q, auth_token)
    return StreamingResponse(answer, media_type="text/event-stream")
Run Code Online (Sandbox Code Playgroud)

这是chat_stream函数:

import openai

def chat_stream(question: str, key: str):
    openai.api_key = key
    # create a completion
    completion = openai.Completion.create(model="text-davinci-003",
                                          prompt=question,
                                          stream=True)
    return …
Run Code Online (Sandbox Code Playgroud)

streaming python-3.x server-sent-events fastapi openai-api

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

如何使用 FastAPI 在查询参数名称中允许使用连字符 (-)?

我有一个简单的应用程序如下:

from typing import Annotated

import uvicorn
from fastapi import FastAPI, Query, Depends
from pydantic import BaseModel

app = FastAPI()


class Input(BaseModel):
    a: Annotated[str, Query(..., alias="your_name")]


@app.get("/")
def test(inp: Annotated[Input, Depends()]):
    return f"Hello {inp.a}"


def main():
    uvicorn.run("run:app", host="0.0.0.0", reload=True, port=8001)


if __name__ == "__main__":
    main()
Run Code Online (Sandbox Code Playgroud)

curl "http://127.0.0.1:8001/?your_name=amin"返回“你好阿明”


我现在将别名从 更改your_name为your-name。

from typing import Annotated

import uvicorn
from fastapi import FastAPI, Query, Depends
from pydantic import BaseModel

app = FastAPI()


class Input(BaseModel):
    a: Annotated[str, Query(..., alias="your-name")] …
Run Code Online (Sandbox Code Playgroud)

python query-string pydantic fastapi

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

将 sqlalchemy 响应转换为 pydantic 对象

如何在FastAPI中将字符串转换为模型类型?如果我有学生模型并且想要将字符串学生转换为类型模型。如何转换呢?

engine = create_engine(SQLALCHAMY_DATABASE_URL,pool_pre_ping=True,pool_recycle=3600)
meta = MetaData()
con = engine.connect()
SessionLocal = sessionmaker(bind=engine, autocommit=False, autoflush=False)
Base = declarative_base()

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


def convert_model(student,db:Session = Depends(database.get_db)):
   Q=student.all()



convert_model(student,db)
Run Code Online (Sandbox Code Playgroud)

它给出了错误str object has no attribute all()

python sqlalchemy pydantic fastapi

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

如何修复 Pydantic 关于使用 model.dict() 方法的弃用警告?

.dict()当我在 FastAPI 中的 Pydantic 模型上使用方法时,它会给我一个弃用警告。我pydantic通过命令行升级,但仍然显示相同的错误。我也更新了 VScode,但同样的问题。

python deprecation-warning visual-studio-code pydantic fastapi

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