标签: fastapi

在 FastAPI 中等待 request.json() 永远挂起

我将此处给出的异常处理(https://github.com/tiangolo/fastapi/discussions/6678)添加到我的代码中,但我想打印完整的请求正文以查看完整的内容。但是,当我等待时,request.json()它永远不会终止。request.json()返回一个协程,因此我需要等待协程完成才能打印结果。如果向端点发送了无效请求,如何打印请求内容?

来自 github 的代码示例,我在错误处理程序和一个简单的端点中进行了 2 处更改。

import logging
from fastapi import FastAPI, Request, status
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel

app = FastAPI()


@app.exception_handler(RequestValidationError)
async def validation_exception_handler(
    request: Request, exc: RequestValidationError
) -> JSONResponse:
    exc_str = f"{exc}".replace("\n", " ").replace("   ", " ")
    logging.error(f"{request}: {exc_str}")
    body = await request.json()  # This line was added by me and never completes
    logging.error(body)  # This line was added by me
    content = …
Run Code Online (Sandbox Code Playgroud)

python freeze exceptionhandler starlette fastapi

4
推荐指数
1
解决办法
586
查看次数

PyInstaller 和 FastAPI(超过最大递归深度)

我有一个使用fastapi作为 Web 界面的 python 服务。我需要制作一个可执行文件,因此我正在使用PyInstaller。

我不断收到以下错误:

File "..../miniconda3/lib/python3.7/site-packages/PyInstaller/lib/modulegraph/modulegraph.py", line 2912, in _load_package
    self._load_module(fqname, fp, buf, stuff)
File "..../miniconda3/lib/python3.7/site-packages/PyInstaller/lib/modulegraph/modulegraph.py", line 2093, in _load_module
    m = self._load_package(fqname, pathname, packagepath)

RecursionError: maximum recursion depth exceeded while calling a Python object
Run Code Online (Sandbox Code Playgroud)

我添加import sys; sys.setrecursionlimit(50000)到原始 python 文件以及规范中,但仍然遇到相同的问题。

有趣的是,如果我不使用fastapi(例如它与 Flask 一起使用),我就不会收到该错误。看起来 PyInstaller 对 fastapi 有一些问题。

有人知道如何解决这个问题吗?

这是我的主要 python 函数中的代码:

from fastapi import FastAPI
import uvicorn
app = FastAPI()

if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", workers=1, port=5000)
Run Code Online (Sandbox Code Playgroud)

python pyinstaller fastapi

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

Python3.8 - FastAPI 和无服务器 (AWS Lambda) - 无法处理发送到 api 端点的文件

几个月来,我一直通过 AWS Lambda 函数将 FastAPI 与 Serverless 结合使用,并且效果很好。

我正在创建一个新的 api 端点,它需要发送一个文件。

在我的本地机器上使用时它可以完美运行,但是当我部署到 AWS Lambda 时,当我尝试使用与本地工作完全相同的文件调用我的端点时出现以下错误。我目前正在通过 swagger UI 进行此测试,除了运行代码的“机器”之外,我的无服务器或本地机器之间没有任何变化。

你知道发生了什么吗?

Python 3.8 FastAPI 0.54.1

我的代码:

from fastapi import FastAPI, File, UploadFile
import pandas as pd

app = FastAPI()

@app.post('/process_data_import_quote_file')
def process_data_import_quote_file(file: UploadFile = File(...)): # same error if I put bytes instead of UploadFile
    file = file.file.read()
    print(f"file {file}")
    quote_number = pd.read_excel(file, sheet_name='Data').iloc[:, 0].dropna()
Run Code Online (Sandbox Code Playgroud)

它在最后一行失败

我尝试打印文件,当我将打印的数据与我在本地读取的数据进行比较时,它是不同的。我发誓这是我在 2 上使用的同一个文件,所以我不知道有什么可以解释的?这是一个非常基本的excel文件,没有什么特别之处。

[ERROR] 2020-05-07T14:25:17.878Z    25ff37a5-e313-4db5-8763-1227e8244457    Exception in ASGI application

Traceback (most recent call last):
  File …
Run Code Online (Sandbox Code Playgroud)

python amazon-web-services aws-lambda serverless fastapi

3
推荐指数
1
解决办法
2133
查看次数

如何使用邮递员将文件发送到fastapi端点

我遇到了使用邮递员测试 api 的困难。通过 swagger 文件上传功能正常工作,我在硬盘上得到了一个保存的文件。我想了解如何用邮递员做到这一点。我使用标准方式来处理我在使用 django、flask 时使用的文件。

Body -> form-data: key=file, value=image.jpeg
Run Code Online (Sandbox Code Playgroud)

但是使用fastapi,我收到一个错误

127.0.0.1:54294 - "POST /uploadfile/ HTTP/1.1" 422 Unprocessable Entity
Run Code Online (Sandbox Code Playgroud)

主文件

@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
    img = await file.read()
    if file.content_type not in ['image/jpeg', 'image/png']:
        raise HTTPException(status_code=406, detail="Please upload only .jpeg files")
    async with aiofiles.open(f"{file.filename}", "wb") as f:
        await f.write(img)
    return {"filename": file.filename}
Run Code Online (Sandbox Code Playgroud)

我也试过了body -> binary: image.jpeg。但得到了相同的结果

邮递员查询

python postman fastapi

3
推荐指数
1
解决办法
4804
查看次数

如何修复 Apache WSGI 上的 FastAPI 应用程序错误?

我正在尝试在运行 Apache 的服务器上运行 FastAPI 应用程序。

我已经相应地配置了 Apache 虚拟主机文件

<VirtualHost *:80>
        ServerAdmin admin@example.com
        ServerName fastapi.example.com
        ServerAlias fastapi.example.com
        DocumentRoot /var/www/fastapi
        ErrorLog ${APACHE_LOG_DIR}/fastapi_error.log
        CustomLog ${APACHE_LOG_DIR}/fastapi_access.log combined
        WSGIScriptAlias / /var/www/fastapi/main.wsgi
        <Directory "/var/www/fastapi">
                AllowOverride All
        </Directory>
</VirtualHost>
Run Code Online (Sandbox Code Playgroud)

并创建了 main.wsgi 和 main.py 文件。

主文件

#! /usr/bin/python3.7

import logging
import sys
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0, '/var/www/fastapi/')
from main import app as application
application.secret_key = 'alibaba'
Run Code Online (Sandbox Code Playgroud)

主文件

from typing import Optional
from fastapi import FastAPI
app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

@app.get("/items/{item_id}")
def read_item(item_id: int, q: Optional[str] …
Run Code Online (Sandbox Code Playgroud)

mod-wsgi apache2 fastapi

3
推荐指数
1
解决办法
1165
查看次数

用 Python 异步写入 CSV 文件

我正在编写一个具有以下功能的 CSV 文件:

import csv
import os
import aiofiles


async def write_extract_file(output_filename: str, csv_list: list):
    """
    Write the extracted content into the file
    """
    try:
        async with aiofiles.open(output_filename, "w+") as csv_file:
            writer = csv.DictWriter(csv_file, fieldnames=columns.keys())
            writer.writeheader()
            writer.writerows(csv_list)
    except FileNotFoundError:
        print("Output file not present", output_filename)
        print("Current dir: ", os.getcwd())
        raise FileNotFoundError
Run Code Online (Sandbox Code Playgroud)

但是,由于没有 await 允许 overwriterows方法,因此没有将行写入 CSV 文件。
如何解决这个问题?有没有可用的解决方法?
谢谢你。
整个代码可以在这里找到。

python csv async-await python-asyncio fastapi

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

FastAPI 请求中的不可哈希类型

我正在使用 fastapi 编写 post-api。所需的请求格式为:

{
   "leadid":LD123,
   "parties":[
      {
         "uid":123123,
         "cust_name":"JOhn Doe",
      }, ...]}
Run Code Online (Sandbox Code Playgroud)

python中的fastapi代码是:

class Customer(BaseModel):
    UID: str
    CustName: str

class PackageIn(BaseModel): 
    lead_id: str
    parties: Set[Customer]
    # threshold: Optional[int] = 85

app = FastAPI()

@app.post('/')
async def nm_v2(package:PackageIn):
    return {"resp":"Response"}
Run Code Online (Sandbox Code Playgroud)

当我访问 SwaggerUI 提交响应时,错误是"422 Error: Unprocessable Entity"。此外,SwaggerUI 文档指出

{
  "detail": [
    {
      "loc": [
        "body"
      ],
      "msg": "unhashable type: 'Customer'",
      "type": "type_error"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我不知道如何为请求有效负载创建这个 dict() 结构而不创建一个名为 Customer 的单独的基于 pydantic 的类。请告诉我如何纠正错误。

python pydantic fastapi

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

如何在 Google Colab 中运行 FastAPI / Uvicorn?

我正在尝试使用 FastAPI / Uvicorn 在 Google Colab 上运行“本地”网络应用程序,就像我见过的一些 Flask 应用程序示例代码一样,但无法使其工作。有没有人能够做到这一点?欣赏它。

成功安装 FastAPI & Uvicorn

!pip install FastAPI -q
!pip install uvicorn -q
Run Code Online (Sandbox Code Playgroud)

示例应用程序

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def root():
    return {"message": "Hello World"}
Run Code Online (Sandbox Code Playgroud)

运行尝试

#attempt 1
if __name__ == "__main__":
    uvicorn.run("/content/fastapi_002:app", host="127.0.0.1", port=5000, log_level="info")
Run Code Online (Sandbox Code Playgroud)

#attempt 2
#uvicorn main:app --reload
!uvicorn "/content/fastapi_001.ipynb:app" --reload
Run Code Online (Sandbox Code Playgroud)

python google-colaboratory fastapi uvicorn

3
推荐指数
1
解决办法
1448
查看次数

我无法在 FastAPI 中读取上传的 csv 文件

我正在尝试遍历 csv 文件。但是,接收到的文件很难阅读。我搜索了这个,我找不到明确的解决方案!

@app.get("/uploadsequence/")
async def upload_sequence_form():
    return HTMLResponse("""
            <!DOCTYPE html>
            <html>
                <head>
                    <title>sequence upload</title>
                </head>
                <body>
                    <h1>upload sequence .CSV file</h1>
                    <form method='post' action='/uploadsequence/' enctype='multipart/form-data'>
                        Upload a csv file: <input type='file' name='csv_file'>
                        <input type='submit' value='Upload'>
                    </form>
                </body>
            </html>
            """)

@app.post("/uploadsequence/")
async def upload_sequence(csv_file: UploadFile = File(...), db = Depends(get_db)):
        csv_file_encoded = TextIOWrapper(csv_file.file, encoding='utf-8')
        csv_reader = csv.DictReader(csv_file_encoded)
        for row in csv_reader:
            if row["Well Type"] in ["RIG MAINTENANCE","RIG MOVE","RIG COMMISSIONING","ABANDONMENT","LEARNINGCURVE"]:
                crud.insert_sequence_record(db=db, row=row,is_drilling=False)
            else:
                crud.insert_sequence_record(db=db, row=row,is_drilling=True)
Run Code Online (Sandbox Code Playgroud)

它给了我这个错误: csv_file_encoded = TextIOWrapper(csv_file.file, encoding='utf-8') AttributeError: 'SpooledTemporaryFile' …

python csv fastapi

3
推荐指数
1
解决办法
1031
查看次数

何时/何地在 FastAPI 中使用正文/路径/查询/字段?

我正在关注FastAPI的教程,到目前为止,我对 FastAPI 中何时/何地使用 Body/Path/Query/Field 有疑问?因为它们似乎都以相同的方式工作,所以本教程对它们的区别使用了模糊的解释,还是我遗漏了什么?

奖金问题:*真的有用吗?我在教程的示例代码中设置/省略了它,但我没有看到区别。

validation metadata fastapi

3
推荐指数
1
解决办法
1496
查看次数