为什么我在记录日志时 FastAPI 不创建日志文件
这是我使用的代码
from fastapi.logger import logger as fastapi_logger
from logging.handlers import RotatingFileHandler
import logging
formatter = logging.Formatter(
"[%(asctime)s.%(msecs)03d] %(levelname)s [%(thread)d] - %(message)s", "%Y-%m-%d %H:%M:%S")
handler = RotatingFileHandler('logfile.log', backupCount=0)
logging.getLogger("fastapi")
fastapi_logger.addHandler(handler)
handler.setFormatter(formatter)
fastapi_logger.info('****************** Starting Server *****************')
Run Code Online (Sandbox Code Playgroud)
与 Flask 不同,文件“logfie.log”不会自动生成。还有其他配置吗?
我有一个简单的FastAPI应用程序,我正在尝试为其创建测试pytest。
我的目标是测试应用程序在出现不同错误时的行为方式。
\n\n我的应用程序中有一个简单的健康检查路线:
\n\nfrom fastapi import APIRouter\n\nrouter = APIRouter()\n\n\n@router.get("/health")\nasync def health():\n return "It\'s working \xe2\x9c\xa8"\nRun Code Online (Sandbox Code Playgroud)\n\n现在在我的 pytest 模块中,我正在尝试修补上述函数,以便它引发不同的错误。\n我正在使用,unittest.mock但我得到了非常奇怪的行为。
import pytest\nfrom unittest import mock\n\nfrom fastapi import HTTPException\nfrom starlette.testclient import TestClient\n\nimport app.api.health\nfrom app.main import app # this is my application (FastAPI instance) with the `router` attached\n\n\n@pytest.fixture()\ndef client():\n with TestClient(app) as test_client:\n yield test_client\n\n\ndef test_simple(client):\n def mock_health_function():\n raise HTTPException(status_code=400, detail=\'gibberish\')\n\n with mock.patch(\'app.api.health.health\', mock_health_function):\n response = client.get(HEALTHCHECK_PATH)\n\n with pytest.raises(HTTPException): # this check passes …Run Code Online (Sandbox Code Playgroud) 我已关注有关 Oauth2 的文档,但它没有描述添加客户端 id 和密钥的过程
https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/
这是做什么的
class UserInDB(User):
hashed_password: str
Run Code Online (Sandbox Code Playgroud)
从原来的例子
我尝试创建 Foo 的子级,每个子级都应该有自己的 uuid。在真实的代码中,不会创建 Foo 的实例,只会创建它的子实例。子项稍后将保存在数据库中,uuid 用于从数据库中检索正确的对象。
在第一个代码片段中,我尝试使用 init 方法,这会导致 AttributeError。我还尝试使用类方法,这会导致丢失子对象中的所有字段。
如果我的第二个片段每个孩子都会获得相同的 uuid,这对我来说很有意义,因为它作为默认值传递。
我可以将 uuid 创建放入子级中,尽管在使用继承时这感觉不对。
有没有更好的方法为每个孩子创建一个uuid?
# foo_init_.py
class Foo(BaseModel):
def __init__(self):
self.id_ = uuid4()
# >>> AttributeError: __fields_set__
# foo_classmethod.py
class Foo(BaseModel):
@classmethod
def __init__(cls):
cls.id_ = uuid4()
# >>> Bar loses id_ fields
Run Code Online (Sandbox Code Playgroud)
from uuid import uuid4, UUID
from pydantic import BaseModel
class Foo(BaseModel):
id_: UUID = uuid4()
class Bar(Foo):
pass
class Spam(Foo):
pass
if __name__ == '__main__':
b1 = Bar()
print(b1.id_) # >>> 73860f46-5606-4912-95d3-4abaa6e1fd2c
b2 = …Run Code Online (Sandbox Code Playgroud) 我是在 DRF 的背景下问这个问题的,但这也可以概括。我们正在维护一个 API 服务,为超过 1K 的实时请求提供服务。在当前场景中,我们正在实时计算 API 调用,即我们正在针对每个 API 调用的用户更新 API 调用计数的数据库列。
但有没有有效的方法呢?例如,在其他地方记录 API 调用,然后在几分钟后更新数据库?或者说我们现在正在做的事情可以吗?大规模 API 服务可以处理多大程度的问题?网上没有针对此问题的具体内容。
我是使用 fastapi 的新手。我在 docker 容器中有一个 main.py。当我使用连接到 fastapi 时
\nuvicorn main:app \xe2\x80\x94-reload \nRun Code Online (Sandbox Code Playgroud)\n来自我的容器。系统提示我连接到http://127.0.0.1:8000。将地址复制到 Firefox 时出现错误:
\n unable to connect. \nRun Code Online (Sandbox Code Playgroud)\n如何连接到 fastapi 服务器?
\nPS 我正在工作的 git 分支是由另一位同事开发的,所以我几乎不知道 fastapi 是如何在 docker 内设置的
\n返回 RedirectResponse 对象后,我遇到了奇怪的重定向行为
事件.py
router = APIRouter()
@router.post('/create', response_model=EventBase)
async def event_create(
request: Request,
user_id: str = Depends(get_current_user),
service: EventsService = Depends(),
form: EventForm = Depends(EventForm.as_form)
):
event = await service.post(
...
)
redirect_url = request.url_for('get_event', **{'pk': event['id']})
return RedirectResponse(redirect_url)
@router.get('/{pk}', response_model=EventSingle)
async def get_event(
request: Request,
pk: int,
service: EventsService = Depends()
):
....some logic....
return templates.TemplateResponse(
'event.html',
context=
{
...
}
)
Run Code Online (Sandbox Code Playgroud)
路由器.py
api_router = APIRouter()
...
api_router.include_router(events.router, prefix="/event")
Run Code Online (Sandbox Code Playgroud)
这段代码返回结果
127.0.0.1:37772 - "POST /event/22 HTTP/1.1" 405 Method Not …Run Code Online (Sandbox Code Playgroud) 我最近使用 FastAPI 框架创建了一个 python API,并使其在我的 AWS ECS 服务中运行良好。我已经设置了 /health 端点以供 ALB 进行运行状况检查。我的 ECS 容器的入口点是这个命令
ENTRYPOINT ["app/start.sh"]
Run Code Online (Sandbox Code Playgroud)
这就是我的 start.sh 中的内容
uvicorn main:app --host 0.0.0.0
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是,当 ALB 命中 /health 端点时,我的 ECS 日志中充满了 200 OK。非常令人沮丧的是,我几乎找不到我的 API 日志,而 Cloudwatch 中充满了 /health 端点日志。有没有办法可以避免健康端点日志?
@app.get("/health", response_class=PlainTextResponse)
def healthcheck():
return "200"
Run Code Online (Sandbox Code Playgroud) 这是我的 FastAPImain.py文件。
from fastapi import FastAPI
from project.config.settings import base as settings
app = FastAPI(docs_url=f"{settings.URL_ROOT}/{settings.DOCS_URL}", redoc_url=None)
app.openapi_version = "3.0.0"
# some functions here
Run Code Online (Sandbox Code Playgroud)
我将这个项目部署到服务器上。但是当我转到服务器中的文档地址时,1.2.3.4/url_root/docs_url它向我显示以下消息:
Unable to render this definition
The provided definition does not specify a valid version field.
Please indicate a valid Swagger or OpenAPI version field.
Supported version fields are swagger: "2.0" and those that match openapi: 3.0.n (for example, openapi: 3.0.0).
Run Code Online (Sandbox Code Playgroud)
有什么问题以及如何解决?
更新:
FastAPI 落后于 Nginx。我的所有端点都工作正常,但我看不到文档。
我收到此错误,模型在我运行uvicorn main:app --reload时成功迁移,但是当我尝试转到 127.0.0.1:8000/docs 时出现此错误。我正在为数据库使用 Postgresql
TypeError: Object of type 'ModelMetaclass' is not JSON serializable
Run Code Online (Sandbox Code Playgroud)
这是我的文件结构
backend/main.py
backend/pydantic_models.py
backend/requirements.txt
backend/sql
backend/sql/crud.py
backend/sql/database.py
backend/sql/sql_models.py
backend/sql/__init__.py
Run Code Online (Sandbox Code Playgroud)
我跟着教程https://fastapi.tiangolo.com/tutorial/sql-databases/ 这里是代码。 主文件
from typing import List
from fastapi import FastAPI, Depends, HTTPException, status
from sqlalchemy.orm import Session
from sql import crud, database, sql_models
from pydantic_models import User, Todo, UserCreation, TodoCreation
sql_models.Base.metadata.create_all(bind=database.engine)
app = FastAPI()
def get_db():
db = database.SessionLocal()
try:
yield db
finally:
db.close()
@app.post("/users/", response_model=User)
def create_user(user=User, db: Session = Depends(get_db)): …Run Code Online (Sandbox Code Playgroud) fastapi ×10
python ×7
starlette ×2
amazon-ecs ×1
connection ×1
oauth-2.0 ×1
openapi ×1
pydantic ×1
pytest ×1
python-3.7 ×1
python-3.x ×1
rest ×1
swagger ×1