我尝试将前端安装到/with app.mount,但这会使我的所有/api路由无效。我还尝试了以下代码将文件夹安装到/static各自的路由中并index.html在以下位置提供文件/:
@app.get("/")
def index():
project_path = Path(__file__).parent.resolve()
frontend_root = project_path / "client/build"
return FileResponse(str(frontend_root) + '/index.html', media_type='text/html')
static_root = project_path / "client/build/static"
app.mount("/static", StaticFiles(directory=static_root), name="static")
Run Code Online (Sandbox Code Playgroud)
这大部分有效,但client/build文件夹中包含的文件未安装,因此无法访问。我知道 Node.js 有一种通过相对路径为前端页面提供服务的方法res.sendFile("index.html", { root: </path/to/static/folder });。FastAPI 中是否有等效的函数可以执行此操作?
我使用 FastAPi 和 Pydantic 对 POST API 的请求和响应进行建模。
我定义了三个类:
from pydantic import BaseModel, Field
from typing import List, Optional, Dict
class RolesSchema(BaseModel):
roles_id: List[str]
class HRSchema(BaseModel):
pk: int
user_id: str
worker_id: str
worker_name: str
worker_email: str
schedulable: bool
roles: RolesSchema
state: dict
class CreateHR(BaseModel):
user_id: str
worker_id: str
worker_name: str
worker_email: str
schedulable: bool
roles: RolesSchema
Run Code Online (Sandbox Code Playgroud)
我的API程序:
@router.post("/humanResource", response_model=HRSchema)
async def create_humanResource(create: CreateHR):
query = HumanResourceModel.insert().values(
user_id=create.user_id,
worker_id=create.worker_id,
worker_name=create.worker_name,
worker_email=create.worker_email,
schedulable=create.schedulable,
roles=create.roles
)
last_record_id = await database.execute(query)
return {"status": "Successfully …Run Code Online (Sandbox Code Playgroud) 我有一个用例,我想在构建模型的类中创建一些值。但是,当我在调用 API 时将类返回到 FastAPI 以便转换为 JSON 时,构造函数会再次运行,并且我可以获得与原始实例不同的值。
这是一个人为的例子来说明:
class SomeModel(BaseModel):
public_value: str
secret_value: Optional[str]
def __init__(self, **data):
super().__init__(**data)
# this could also be done with default_factory
self.secret_value = randint(1, 5)
def some_function() -> SomeModel:
something = SomeModel(public_value="hello")
print(something)
return something
@app.get("/test", response_model=SomeModel)
async def exec_test():
something = some_function()
print(something)
return something
Run Code Online (Sandbox Code Playgroud)
控制台输出为:
public_value='hello' secret_value=1
public_value='hello' secret_value=1
Run Code Online (Sandbox Code Playgroud)
但 Web API 中的 JSON 是:
{
"public_value": "hello",
"secret_value": 2
}
Run Code Online (Sandbox Code Playgroud)
当我单步执行代码时,我可以看到__init__被调用两次。
首先是在建设上something = SomeModel(public_value="hello")。
其次,令我意想不到的是,在调用的 API 处理程序exec_test …
我试图在该对象的 JSON 架构中允许 null:
from pydantic import BaseModel
from typing import Optional
class NextSong(BaseModel):
song_title: Optional[str] = ...
Run Code Online (Sandbox Code Playgroud)
但结果的模式如下:
{
"title": "NextSong",
"type": "object",
"properties": {
"song_title": {
"title": "Song Title",
"type": "string"
}
},
"required": ["song_title"]
}
Run Code Online (Sandbox Code Playgroud)
生成的架构不允许 Song_title 的值为 null,这不符合预期,但我不确定如何指定允许 null,但该字段仍然是必需的。
在 FastAPI 应用程序中创建模型时,我正在努力获取创建 UUID 字段的语法。我正在使用SQLModel。
基本上,我的 models.py 文件如下所示:
from datetime import datetime
from typing import Optional
import uuid
from sqlalchemy import Column, DateTime
from sqlalchemy.dialects import postgresql as psql
from sqlmodel import SQLModel, Field
class ModelBase(SQLModel):
"""
Base class for database models.
"""
id: Optional[int] = Field(default=None, primary_key=True)
created_at: datetime = Field(sa_column=Column(DateTime(timezone=True), default=datetime.utcnow))
updated_at: datetime = Field(sa_column=Column(DateTime(timezone=True),
onupdate=datetime.utcnow, default=datetime.utcnow))
class UUIDModelBase(ModelBase, table=True):
"""
Base class for UUID-based models.
"""
uuid: uuid.UUID = Field(sa_column=Column(psql.UUID(as_uuid=True)), default=uuid.uuid4)
Run Code Online (Sandbox Code Playgroud)
上述错误与
AttributeError: 'FieldInfo' object …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 session 在 fastapi 中的视图函数之间传递变量。但是,我没有找到任何专门说明会话对象的文档。我看到的所有地方都使用cookie。有什么方法可以将下面的flask代码转换为fastapi吗?我想让会话实现尽可能简单。
from flask import Flask, session, render_template, request, redirect, url_for
app=Flask(__name__)
app.secret_key='asdsdfsdfs13sdf_df%&'
@app.route('/a')
def a():
session['my_var'] = '1234'
return redirect(url_for('b'))
@app.route('/b')
def b():
my_var = session.get('my_var', None)
return my_var
if __name__=='__main__':
app.run(host='0.0.0.0', port=5000, debug = True)
Run Code Online (Sandbox Code Playgroud) 我有一个 FastAPI 应用程序,我希望将默认日志写入 STDOUT,并使用 JSON 格式的以下数据:
应用程序日志应如下所示:
{
"XYZ": {
"log": {
"level": "info",
"type": "app",
"timestamp": "2022-01-16T08:30:08.181Z",
"file": "api/predictor/predict.py",
"line": 34,
"threadId": 435454,
"message": "API Server started on port 8080 (development)"
}
}
}
Run Code Online (Sandbox Code Playgroud)
访问日志应如下所示:
{
"XYZ": {
"log": {
"level": "info",
"type": "access",
"timestamp": "2022-01-16T08:30:08.181Z",
"message": "GET /app/health 200 6ms"
},
"req": {
"url": "/app/health",
"headers": {
"host": "localhost:8080",
"user-agent": "curl/7.68.0",
"accept": "*/*"
},
"method": "GET",
"httpVersion": "1.1",
"originalUrl": "/app/health",
"query": {}
},
"res": {
"statusCode": 200,
"body": …Run Code Online (Sandbox Code Playgroud) 我有一个连接到 MongoDB 的多语言 FastAPI。我在 MongoDB 中的文档以两种可用语言复制,并以这种方式构建(简化示例):
\n\n{\n "_id": xxxxxxx,\n "en": { \n "title": "Drinking Water Composition",\n "description": "Drinking water composition expressed in... with pesticides.",\n "category": "Water", \n "tags": ["water","pesticides"] \n },\n "fr": { \n "title": "Composition de l\'eau de boisson",\n "description": "Composition de l\'eau de boisson exprim\xc3\xa9e en... pr\xc3\xa9sence de pesticides....",\n "category": "Eau", \n "tags": ["eau","pesticides"] \n }, \n}\n\nRun Code Online (Sandbox Code Playgroud)\n因此,我实现了两个模型DatasetFR和,每个模型都对每种语言中的特定外部模型 ( )DatasetEN进行引用。Enumcategorytags
class DatasetFR(BaseModel):\n title:str\n description: str\n category: CategoryFR\n tags: …Run Code Online (Sandbox Code Playgroud) 当我使用 docker-compose 安装 fastapi 项目时,我得到了AssertionError: jinja2 must be installed to use Jinja2Templates
但是当我使用 env 安装它时,它将运行良好。
我的操作系统:
Ubuntu18.04STL
我的要求.txt:
fastapi~=0.68.2
starlette==0.14.2
pydantic~=1.8.1
uvicorn~=0.12.3
SQLAlchemy~=1.4.23
# WSGI
Werkzeug==1.0.1
pyjwt~=1.7.0
# async-exit-stack~=1.0.1
# async-generator~=1.10
jinja2~=2.11.2
# assert aiofiles is not None, "'aiofiles' must be installed to use FileResponse"
aiofiles~=0.6.0
python-multipart~=0.0.5
requests~=2.25.0
pyyaml~=5.3.1
# html-builder==0.0.6
loguru~=0.5.3
apscheduler==3.7.0
pytest~=6.1.2
html2text==2020.1.16
mkdocs==1.2.1
Run Code Online (Sandbox Code Playgroud)
Dockerfile
FROM python:3.8
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
WORKDIR /server
COPY requirements.txt /server/
RUN pip install -r requirements.txt
COPY . /server/
Run Code Online (Sandbox Code Playgroud)
docker-compose.yml …
我有以下代码片段:
from passlib.context import CryptContext
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
pwd_context.hash(password)
Run Code Online (Sandbox Code Playgroud)
这里描述的是。
我不明白的是,如果它始终返回相同的散列密码而不考虑另一个 Secret_key 例如散列密码值,这怎么可能是安全的?
fastapi ×10
python ×7
pydantic ×4
docker ×1
gunicorn ×1
logging ×1
mongodb ×1
passlib ×1
postgresql ×1
python-3.x ×1
reactjs ×1
sqlalchemy ×1
sqlmodel ×1
uvicorn ×1