如果出现 HTTPException,如何使用 FastAPI 重定向请求?
在 Flask 中我们可以这样实现:
@app.errorhandler(404)
def handle_404(e):
if request.path.startswith('/api'):
return render_template('my_api_404.html'), 404
else:
return redirect(url_for('index'))
Run Code Online (Sandbox Code Playgroud)
或者在 Django 中我们可以使用 django.shortcuts:
from django.shortcuts import redirect
def view_404(request, exception=None):
return redirect('/')
Run Code Online (Sandbox Code Playgroud)
我们如何使用 FastAPI 来实现这一目标?
我目前有名为 jwt 的 JWT 依赖项,它确保它在到达端点之前通过 JWT 身份验证阶段,如下所示:
sample_endpoint.py:
from fastapi import APIRouter, Depends, Request
from JWTBearer import JWTBearer
from jwt import jwks
router = APIRouter()
jwt = JWTBearer(jwks)
@router.get("/test_jwt", dependencies=[Depends(jwt)])
async def test_endpoint(request: Request):
return True
Run Code Online (Sandbox Code Playgroud)
以下是使用 JWT 对用户进行身份验证的 JWT 依赖项(来源:https ://medium.com/datadriveninvestor/jwt-authentication-with-fastapi-and-aws-cognito-1333f7f2729e ):
JWTBearer.py
from typing import Dict, Optional, List
from fastapi import HTTPException
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from jose import jwt, jwk, JWTError
from jose.utils import base64url_decode
from pydantic import BaseModel
from starlette.requests import Request …Run Code Online (Sandbox Code Playgroud) 我正在尝试运行一项使用简单变压器 Roberta 模型进行分类的服务。测试时,推理脚本/函数本身按预期工作。当我将其包含在快速 API 中时,它会关闭服务器。
\nuvicorn==0.11.8\nfastapi==0.61.1\nsimpletransformers==0.51.6\ncmd : uvicorn --host 0.0.0.0 --port 5000 src.main:app\nRun Code Online (Sandbox Code Playgroud)\n@app.get("/article_classify")\ndef classification(text:str):\n """function to classify article using a deep learning model.\n Returns:\n [type]: [description]\n """\n\n _,_,result = inference(text)\n return result\nRun Code Online (Sandbox Code Playgroud)\n错误 :
\nINFO: Started server process [8262]\nINFO: Waiting for application startup.\nINFO: Application startup complete.\nINFO: Uvicorn running on http://0.0.0.0:5000 (Press CTRL+C to quit)\nINFO: 127.0.0.1:36454 - "GET / HTTP/1.1" 200 OK\nINFO: 127.0.0.1:36454 - "GET /favicon.ico HTTP/1.1" 404 Not Found\nINFO: 127.0.0.1:36454 - "GET /docs HTTP/1.1" …Run Code Online (Sandbox Code Playgroud) python multilabel-classification fastapi uvicorn simpletransformers
我python manage.py在 Flask 应用程序中使用 shell 来使用 IPython shell 从 shell 访问我的应用程序。fastApi 中有类似的东西吗?
在带有restframework的Django中,你可以这样做:
class Item(models.Model):
id = models.IntegerField()
name = models.CharField(max_length=32)
another_attribute = models.CharField(max_length=32)
...
(more attributes)
...
yet_another_attribute = models.CharField(max_length=32)
class ItemViewSet(viewsets.ReadOnlyModelViewSet):
permission_classes = [IsAuthenticated]
serializer_class = ItemSerializer
filterset_fields = '__all__' # <- this enables filtering on all fields
queryset = Item.objects.all()
Run Code Online (Sandbox Code Playgroud)
如果我想允许过滤,filterset_fields = '__all__'将允许我做类似的事情api/item/?(attribute)=(value)并允许我过滤任何属性
我正在阅读本教程(https://fastapi.tiangolo.com/tutorial/sql-databases/#crud-utils),看起来涉及很多手动过滤:
from fastapi_sqlalchemy import db
class Item(BaseModel):
id: int
name: str
another_attribute: str
...
(more attributes)
...
yet_another_attribute: str
# is it necessary to manually include all the fields I …Run Code Online (Sandbox Code Playgroud) 我开始开发的 FastAPI 应用程序使用了多个服务,我只想在应用程序启动时初始化一次这些服务,然后在不同的地方使用该对象的方法。
它可以是云服务或任何其他重型服务。
可能的方法是使用Lazy loading和 with来实现Singlenton pattern,但我正在寻找更好的 FastAPI 方法。
另一种可能的方法是使用Depends类并缓存它,但它的使用仅对路由方法有意义,而对从路由方法调用的其他常规方法则无效。
例子:
async def common_parameters(q: Optional[str] = None, skip: int = 0, limit: int = 100):
return {"q": q, "skip": skip, "limit": limit}
async def non_route_function(commons: dict = Depends(common_parameters)):
print(commons) # returns `Depends(common_parameters)`
@router.get('/test')
async def test_endpoint(commons: dict = Depends(common_parameters)):
print(commons) # returns correct dict
await non_route_function()
return {'success': True}
Run Code Online (Sandbox Code Playgroud)
还可以使用@app.on_event("startup")事件来初始化重类,但不知道如何使这个初始化的对象可以从每个地方访问,而不使用singleton.
另一种丑陋的方法是将初始化的对象保存到 @app( 中,然后从请求中获取此应用程序,但随后您必须传递request到每个非路由函数中。
我描述的所有方法要么是丑陋的、不方便的、非Pythonic的,要么是更糟糕的实践,我们这里也没有像flask中那样的线程局部变量和代理对象,那么对于我描述的此类问题的最佳方法是什么多于?
谢谢!
是否可以在请求正文(或响应)的架构中指定列表的长度?支持使用查询函数验证 url 中传递的字符串的长度,但我没有看到任何列表。可能的用例是发送固定大小的浮点数列表以馈送到 ML 模型。
我想用 FastAPI 和 Jinja 作为模板构建一个购物车,
所以我需要在会话中保存每个匿名用户的数据。
Django和flask都有内置的session功能,我们可以很容易地做到这一点。
其中一种解决方案可以使用 SQLAlchemy 会话,但 SQLAlchemy 会话不支持匿名用户,我们必须为每个会话单独创建令牌。那么我们应该使用存储的令牌来保存每个数据。
还有其他类似Django和Flask内置功能的方式吗?
我的 FastAPI 应用程序似乎将很多事情记录两次。
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [21360] using statreload
INFO: Started server process [21362]
INFO:uvicorn.error:Started server process [21362]
INFO: Waiting for application startup.
INFO:uvicorn.error:Waiting for application startup.
INFO: Application startup complete.
INFO:uvicorn.error:Application startup complete.
^CINFO: Shutting down
INFO:uvicorn.error:Shutting down
INFO: Waiting for application shutdown.
INFO:uvicorn.error:Waiting for application shutdown.
INFO: Application shutdown complete.
INFO:uvicorn.error:Application shutdown complete.
INFO: Finished server process [21362]
INFO:uvicorn.error:Finished server process [21362]
INFO: Stopping reloader process [21360]
Run Code Online (Sandbox Code Playgroud)
这包括引发的任何异常,您将获得整个堆栈跟踪两次。我看到一些答案建议删除 …