我在FastAPI和Flask中编写了具有相同功能的相同 API 应用程序。但是,当返回 JSON 时,两个框架之间的数据格式不同。两者都使用相同的json库,甚至相同的代码:
import json
from google.cloud import bigquery
bigquery_client = bigquery.Client()
@router.get('/report')
async def report(request: Request):
response = get_clicks_impression(bigquery_client, source_id)
return response
def get_user(client, source_id):
try:
query = """ SELECT * FROM ....."""
job_config = bigquery.QueryJobConfig(
query_parameters=[
bigquery.ScalarQueryParameter("source_id", "STRING", source_id),
]
)
query_job = client.query(query, job_config=job_config) # Wait for the job to complete.
result = []
for row in query_job:
result.append(dict(row))
json_obj = json.dumps(result, indent=4, sort_keys=True, default=str)
except Exception as e:
return …Run Code Online (Sandbox Code Playgroud) 我有这个模型:
class Text(BaseModel):
id: str
text: str = None
class TextsRequest(BaseModel):
data: list[Text]
n_processes: Union[int, None]
Run Code Online (Sandbox Code Playgroud)
所以我希望能够接受如下请求:
{"data": ["id": "1", "text": "The text 1"], "n_processes": 8}
Run Code Online (Sandbox Code Playgroud)
和
{"data": ["id": "1", "text": "The text 1"]}.
Run Code Online (Sandbox Code Playgroud)
现在在第二种情况下我得到
{'data': [{'id': '1', 'text': 'The text 1'}], 'n_processes': None}
Run Code Online (Sandbox Code Playgroud)
使用此代码:
app = FastAPI()
@app.post("/make_post/", response_model_exclude_none=True)
async def create_graph(request: TextsRequest):
input_data = jsonable_encoder(request)
Run Code Online (Sandbox Code Playgroud)
n_processes那么这里我该如何排除呢?
使用 ORM,我想要执行一个 POST 请求,让某些字段具有null值,该值将在数据库中转换为那里指定的默认值。
问题是 OpenAPI (Swagger) docs忽略了默认值None,并且默认情况下仍然提示 a UUID。
from fastapi import FastAPI
from pydantic import BaseModel
from typing import Optional
from uuid import UUID
import uvicorn
class Table(BaseModel):
# ID: Optional[UUID] # the docs show a example UUID, ok
ID: Optional[UUID] = None # the docs still shows a uuid, when it should show a null or valid None value.
app = FastAPI()
@app.post("/table/", response_model=Table)
def create_table(table: Table):
# here we call …Run Code Online (Sandbox Code Playgroud)