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&
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cocktail_py

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值