我有一个使用 FastAPI 的 API。在单个文件 (main.py) 中,我调用了创建 API 的函数
from fastapi import FastAPI
# ...
app = FastAPI()
Run Code Online (Sandbox Code Playgroud)
以及所有端点:
@app.post("/sum")
async def sum_two_numbers(number1: int, number2: int):
return {'result': number1 + number2}
Run Code Online (Sandbox Code Playgroud)
但随着应用程序变得越来越大,文件变得混乱且难以维护。显而易见的解决方案是将函数定义保留在单独的模块中,然后导入它们并在 main.py 中使用它们,如下所示:
from mymodules.operations import sum_two_numbers
# ...
@app.post("/sum")
sum_two_numbers(number1: int, number2: int)
Run Code Online (Sandbox Code Playgroud)
只是这样不行。我不知道我是否做错了或者无法完成,但我从 VSCode 收到此错误:
装饰器后预期的函数或类声明 | 皮兰斯
(我的程序有很多错误,我还没有看到实际的解释器投诉,但如果这很重要,我可以尝试调试它并将其发布在这里)
那么这是不可能做到的,我必须坚持使用单文件 API,还是可以做到,但我做错了?如果是第二种,正确的方法是什么?
我使用中间件来打印 HTTP 请求正文,以避免print每个函数中出现语句。但是,运行客户端代码时fastapi没有任何响应。
服务器简化为以下代码:
import typing
import uvicorn
from fastapi import FastAPI
from fastapi import Request, Body
app = FastAPI()
@app.middleware('http')
async def debug_request(request: Request, call_next):
_body = await request.body()
print(_body)
#
response = await call_next(request)
return response
@app.put("/")
def _(
_body: typing.Dict
):
# print(_body) # this statement is replaced by the middleware
return {"detail": "ok"}
if __name__ == '__main__':
uvicorn.run(app, host='localhost', port=8000)
Run Code Online (Sandbox Code Playgroud)
客户端代码如下:
import requests
_url = 'http://localhost:8000/'
_json = {
'row_id': '1'
}
resp = …Run Code Online (Sandbox Code Playgroud) 我正在使用 fastAPI python 框架构建一个简单的 POST/GET https 服务器。在客户端,我每 10 秒发送一次心跳 POST 消息,并且我希望在此期间保持连接打开。
然而,由于某种原因,我看到每次新的心跳,我的连接都会被对等点断开,所以我需要重新建立它。如果连续 2 个 keepalive 之间的空闲时间为 1 秒,则连接保持活动状态,并且可以重用。
我正在使用HTTP/1.1with Connection: keep-alive,但这完全取决于服务器保持连接活动的时间,并且我正在寻找一种方法将此超时延长到约 15 秒。有什么合适的方法吗?或者甚至只是让服务器在决定断开客户端连接时打印正确的日志消息......
PS为了启动服务器,我使用以下命令,也许需要修改?
uvicorn main:app --port 44444 --host 0.0.0.0 --reload --ssl-keyfile ./key.pem
--ssl-certfile ./certificate.pem --log-level debug
Run Code Online (Sandbox Code Playgroud) 目前,我正在学习Python和Fastapi,但我不知道打字的用途。可选的。
class Post(BaseModel):
# default value
rating: int = None
# typing.Optional
rating: Optional[int] = None
Run Code Online (Sandbox Code Playgroud)
两者都有效。我不明白有什么区别。
我有一个带有异步 sqlalchemy 的异步 FastApi 应用程序,源代码(不会提供 schemas.py,因为没有必要):
from sqlalchemy import (
Column,
String,
)
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.decl_api import DeclarativeMeta
from app.config import settings
engine = create_async_engine(settings.DATABASE_URL)
Base: DeclarativeMeta = declarative_base()
async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
class Titles(Base):
__tablename__ = "titles"
id = Column(String(100), primary_key=True)
title = Column(String(100), unique=True)
async def get_session() -> AsyncSession:
async with async_session() as session:
yield session
Run Code Online (Sandbox Code Playgroud)
import .database
from fastapi_utils.cbv import cbv
from …Run Code Online (Sandbox Code Playgroud) 是否可以在 FastAPI 中获取请求来源的 URL?
例如,如果我有一个在 处请求的端点,api.mysite.com/endpoint并且从 向该端点发出请求www.othersite.com,有没有办法可以在我的端点函数中检索字符串“www.othersite.com”?
我有一个包含学生表格的页面。我添加了一个按钮,允许您向表中添加新行。为此,我将用户重定向到带有输入表单的页面。
问题是,提交完成的表单后,用户会转到一个新的空白页面。如何传输已完成表单中的数据并将用户重定向回表格?
我刚刚开始学习Web编程,所以我决定先不使用AJAX技术来实现。
代码:
from fastapi import FastAPI, Form
from fastapi.responses import Response
import json
from jinja2 import Template
app = FastAPI()
# The page with the table
@app.get('/')
def index():
students = get_students() # Get a list of students
with open('templates/students.html', 'r', encoding='utf-8') as file:
html = file.read()
template = Template(html) # Creating a template with a table
# Loading a template
return Response(template.render(students=students), media_type='text/html')
# Page with forms for adding a new entry
@app.get('/add_student')
def add_student_page():
with open('templates/add_student.html', …Run Code Online (Sandbox Code Playgroud) error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/
Run Code Online (Sandbox Code Playgroud)
我继续下载了Microsoft C++ 构建工具
我应该安装什么?因为有一堆东西
我有以下 FastAPI 后端:
from fastapi import FastAPI
app = FastAPI
class Demo(BaseModel):
content: str = None
@app.post("/demo")
async def demoFunc(d:Demo):
return d.content
Run Code Online (Sandbox Code Playgroud)
问题是,当我向此 API 发送带有额外数据的请求时,例如:
data = {"content":"some text here"}aaaa
Run Code Online (Sandbox Code Playgroud)
或者
data = {"content":"some text here"aaaaaa}
resp = requests.post(url, json=data)
Run Code Online (Sandbox Code Playgroud)
422 unprocessable entity在以下情况下,它会抛出状态代码错误,返回字段中包含 Actual("some text here") 和 Extra("aaaaa") 数据data = {"content":"some text here"}aaaa:
{
"detail": [
{
"loc": [
"body",
47
],
"msg": "Extra data: line 4 column 2 (char 47)",
"type": "value_error.jsondecode",
"ctx": {
"msg": "Extra …Run Code Online (Sandbox Code Playgroud) 尝试使用 uvicorn 测试我的第一个 FastAPI 应用程序。
在Jupyter Notebook上编写以下代码并保存'main.py'在目录中:/home/user
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
Run Code Online (Sandbox Code Playgroud)
从我正在运行的同一目录:
$uvicorn main --reload
Run Code Online (Sandbox Code Playgroud)
它抛出以下错误:
错误:加载 ASGI 应用程序时出错。导入字符串“main”必须采用“:”格式。
fastapi ×10
python ×9
uvicorn ×3
http ×2
pydantic ×2
asgi ×1
asyncpg ×1
http-referer ×1
httprequest ×1
jinja2 ×1
json ×1
option-type ×1
python-3.x ×1
rest ×1
sqlalchemy ×1
starlette ×1
typing ×1
web ×1