标签: fastapi

FastAPI - 如何在使用 UploadFile 时读取 json 文件

from typing import List, Optional

from fastapi import FastAPI, File, UploadFile
from fastapi.responses import HTMLResponse
from pydantic import BaseModel

app = FastAPI(debug=True)
@app.post("/uploadfiles/")
def create_upload_files(upload_file: UploadFile = File(...)):
     json_data =  ??  upload_file ?? 
     result = model().calculate(json_data)
     return { "estimation": result}


@app.get("/")
async def main():
    content = """
<body>
<form action="/uploadfiles/" enctype="multipart/form-data" method="post">
<input name="upload_file" type="file" multiple>
<input type="submit">
</form>
</body>
    """
    return HTMLResponse(content=content)
Run Code Online (Sandbox Code Playgroud)

我有上面的 FastAPI 应用程序。我需要上传一个json文件。因此 upload_file 是一个 json 文件。model() 实例还使用一个计算方法,该方法将 json 数据作为输入。我在努力解决如何将 upload_file 从 Fast_API 解码为字典格式的问题。

我尝试了 upload_file.read() 但这返回一个字节数组 …

python api fastapi

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

使用 Pydantic 嵌套模型从 FastAPI 获取 JSON

以下代码接收一些已 POST 到 FastAPI 服务器的 JSON。FastAPI 使其可以作为 Pydantic 模型在函数中使用。我的示例代码通过写入文件来处理它。我不喜欢的(这似乎是使用 Pydantic List 的副作用)是我必须循环回来才能获得一些可用的 JSON。

我怎样才能在不循环的情况下做到这一点?

我觉得这一定是可能的,因为return images它确实有效。

from typing import List

from fastapi import FastAPI
from pydantic import BaseModel
import json

app = FastAPI()

class Image(BaseModel):
    url: str
    name: str

@app.post("/images/multiple/")
async def create_multiple_images(images: List[Image]):
  #return images             # returns json string
  #print(images)             # prints an Image object
  #print(images.json())      # AttributeError: 'list' object has no attribute 'json'
  #print(json.dumps(images)) # TypeError: Object of type Image is not JSON serializable
  img_data = …
Run Code Online (Sandbox Code Playgroud)

python json python-3.8 pydantic fastapi

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

在 FastAPI / Uvicorn 中接受 gzipped body

我正在将FastAPIUvicorn一起使用来实现 u-service,它接受请求正文中的 json 有效负载。由于请求正文可能非常大,我希望服务接受 gzip 压缩。我该如何做到这一点?

到目前为止,如下:

  • 添加了GZip 中间件,但它对响应进行编码,而不是解码请求
  • 在我的请求中添加了“内容编码:gzip”

失败并响应:

状态:400 错误请求
{“detail”:“解析正文时出错”}

python fastapi uvicorn

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

在 aiohttp 或 httpx 中,我需要在应用程序关闭时关闭会话/客户端吗

我正在使用httpx库,但我认为aiohttp的原理是相同的。如果我在应用程序的整个生命周期中为多个请求创建并重用 AsyncClient,我是否需要在应用程序关闭事件时调用aclose()(或者如果使用 Client)?close或者这些联系会自行消失。

如果我在 Docker 容器中运行应用程序会怎样?这也会是一个因素吗?

我不明白 AsyncClient 或 Client (或 aoihttp 中的 ClientSession)对象下面发生了什么。

感谢帮助。

python httprequest aiohttp fastapi httpx

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

Force encode/databases to use asyncpg instead of psycopg2

Recently, I am trying to use encode/databases packages with my postgres db. I have done all correctly. But when I go to run it with uvicorn, I see that it shows me that psycopg2 is not installed. I do not wan to use psycopg2. So, I restated all and run databases[postgresql] instead of databases only. I also installed asyncpg. But I am still seeing the same err. I was also doing everything in a virtual environment. My code is …

python database postgresql asyncpg fastapi

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

如何在FastAPI中接收图像和json数据?

我通过以下方式将图像和 json 数据发送到我的 API:

import requests
filename = "test_image.jpeg"
files = {'my_file': (filename, open(filename, 'rb'))}
json={'first': "Hello", 'second': "World"}

response = requests.post('http://127.0.0.1:8000/file', files=files, params=json)
Run Code Online (Sandbox Code Playgroud)

如何通过FastAPI在服务器端同时接收图像和json数据?

我的代码如下所示:

@app.post('/file')
def _file_upload(my_file: UploadFile = File(...), params: str = Form(...)):

    image_bytes = my_file.file.read()
    decoded = cv2.imdecode(np.frombuffer(image_bytes, np.uint8), -1)
    pg_image = cv2.resize(decoded, (220, 220))
    return {"file_size": params}
Run Code Online (Sandbox Code Playgroud)

但是,这给了我以下错误:

<Response [422]>
{'detail': [{'loc': ['body', 'params'], 'msg': 'field required', 'type': 'value_error.missing'}]}
Run Code Online (Sandbox Code Playgroud)

我在这里做错了什么吗?

python api fastapi

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

如何使用 fastapi 日志记录捕获 X-Forwarded-For?

我在这样的函数中运行 FastApi 和 guvicorn:

if __name__ == "__main__":

    uvicorn.run(
        app="app.main:app",
        host="HOSTIP",
        port=8000,
        reload=True,
        # log_config=None,
        log_config=log_config,
        log_level="info"
    )
Run Code Online (Sandbox Code Playgroud)

这就是我的 log_config 的样子:

log_config = {
    "version": 1,
    "disable_existing_loggers": True,
    "formatters": {
        "default": {
            "()": "uvicorn.logging.DefaultFormatter",
            "fmt": "%(asctime)s::%(levelname)s::%(name)s::%(filename)s::%(funcName)s - %(message)s",
            "use_colors": None,
        },
        "access": {
            "()": "uvicorn.logging.AccessFormatter",
            "fmt": '%(asctime)s::%(levelprefix)s %(client_addr)s - "%(request_line)s" %(status_code)s',
        },
    },
    "handlers":
    {
        "default":
        {
            "formatter": "default",
            # "class": 'logging.NullHandler',
            "class": 'logging.FileHandler',
            "filename": CONFIG[SECTION]["default"]
        },
        "error":
        {
            "formatter": "default",
            # "class": 'logging.NullHandler',
            "class": 'logging.FileHandler',
            "filename": CONFIG[SECTION]["error"]
        },
        "access": …
Run Code Online (Sandbox Code Playgroud)

haproxy python-3.x fastapi uvicorn

2
推荐指数
2
解决办法
6527
查看次数

在 Flask 中执行 request.json() 的等效 FastAPI 方法是什么?

在Flask中,来自客户端的请求可以如下处理。

对于 JSON 数据:

payload = request.get_json()

对于令牌参数:

token = request.headers.get('Authorization')

对于参数:

id = request.args.get('url', None)

FastAPI 做同样事情的方法是什么?

python json starlette fastapi

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

如何在 Docker 上运行时重定向 FastAPI 文档

我需要将“ /swagger-ui.html ”重定向到文档页面。

我试过:

app = FastAPI()

@app.get("/swagger-ui.html")
async def docs_redirect():
    response = RedirectResponse(url='/docs')
    return response
Run Code Online (Sandbox Code Playgroud)

app = FastAPI(docs_url="/swagger-ui.html")

@app.get("/")
async def docs_redirect():
    response = RedirectResponse(url='/swagger-ui.html')
    return response
Run Code Online (Sandbox Code Playgroud)

但是,直接运行项目(使用 uvicorn 命令)我可以工作,但是当我将其放在 Docker 容器上时,它会在浏览器上输出此消息,询问位置,但没有任何内容可以作为输入:

无法推断基本 URL。当使用动态 Servlet 注册或 API 位于 API 网关后面时,这种情况很常见。基本 url 是提供所有 swagger 资源的根。例如,如果 api 在http://example.org/api/v2/api-docs上可用,则基本 URL 为http://example.org/api/。请手动输入位置:

这是我的 dockerfile:

FROM python:3.8
USER root
RUN mkdir -p /usr/local/backend
WORKDIR /usr/local/backend
EXPOSE 8080
ARG BUILD_ENV=dev 
ENV BUILD_ENV=$BUILD_ENV
COPY . /usr/local/backend
RUN pip install -r requirements.txt …
Run Code Online (Sandbox Code Playgroud)

python backend docker dockerfile fastapi

2
推荐指数
2
解决办法
5871
查看次数

测试期间模拟环境变量

我有一个非常简单的 fastapi 应用程序,我想测试它,代码dummy_api.py如下:

import os
from fastapi import FastAPI


app = FastAPI()


@app.get(os.getenv("ENDPOINT", "/get"))
def func():
    return {
        "message": "Endpoint working !!!"
    }
Run Code Online (Sandbox Code Playgroud)

当我想测试这个时,我使用以下文件:

from fastapi.testclient import TestClient
import dummy_api


def test_dummy_api():
    client = TestClient(dummy_api.app)
    response = client.get("/get")
    assert response.status_code == 200


def test_dummy_api_with_envar(monkeypatch):
    monkeypatch.setenv("ENDPOINT", "dummy")
    client = TestClient(dummy_api.app)
    response = client.get("/dummy")
    assert response.status_code == 200
Run Code Online (Sandbox Code Playgroud)

但是,我无法模拟环境变量部分,因为其中一个测试因404.

pytest -s -v
================================================================= test session starts ==================================================================
platform linux -- Python 3.8.5, pytest-6.2.2, py-1.9.0, pluggy-0.13.1 -- /home/subhayan/anaconda3/envs/fastapi/bin/python
cachedir: …
Run Code Online (Sandbox Code Playgroud)

python mocking pytest fastapi pytest-mock

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