小编Moh*_*dar的帖子

如何使用FastAPI返回JSON格式的数据?

我在FastAPIFlask中编写了具有相同功能的相同 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)

python serialization json fastapi

12
推荐指数
1
解决办法
2万
查看次数

标签 统计

fastapi ×1

json ×1

python ×1

serialization ×1