FastAPI 解决 "There was an error parsing the body"

在使用flask处理一些接口高并发的问题时候,发现响应没那么快,之后在网上了解到了FastAPI这个框架.在使用flask的post请求的原接口切换到fastapi接口的时候遇到"There was an error parsing the body"问题,有以下两种处理方案

pip install uvicorn
pip install fastapi
pip install python-multipart
1.更改原接口
# Read the body of the request as JSON

# session.post(url, data=data)
session.post(url, json=data)
# -*- coding: utf-8 -*-
# @Time    : 2020/4/30 9:45
# @Author  :

import json
from fastapi import FastAPI
from pydantic import BaseModel
from starlette.requests import Request
from starlette.responses import Response
from decimal import Decimal
from datetime import datetime, date

app = FastAPI()

class Item(BaseModel):
    proxy: str
    # description: str = None
    # price: float
    # tax: float = None
    
@app.post("/home/ip-proxy")
async def web_api(item: Item):
    return item
2.保留原接口 using request directly
@app.post("/home/ip-proxy")
async def web_api(request: Request):
    data = await request.form()
    data_json = dict(data)
    return Response(content=json.dumps(data_json, cls=DateEncoder),
                    media_type='application/json')


class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime("%Y-%m-%d")
        elif isinstance(obj, Decimal):
            return float(obj)
        else:
            return json.JSONEncoder.default(self, obj)
3.运行
# 前台运行
uvicorn 文件名:app --reload --host 0.0.0.0 --port 11111

# 后台运行
nohup uvicorn 文件名:app --reload --host 0.0.0.0 --port 11111> /var/log/文件名.log 2>&1&

你可能感兴趣的:(个人学习记录)