gpt4 book ai didi

python - Flask 请求语法错误的问题

转载 作者:行者123 更新时间:2023-12-05 08:45:41 26 4
gpt4 key购买 nike

我正在测试/尝试学习 flask 和 flast_restful。我得到的这个问题是:

代码 400,消息请求语法错误('name=testitem')

ma​​in.py:

from flask import Flask,request
from flask_restful import Api, Resource, reqparse

app = Flask(__name__)
api = Api(app)

product_put_args = reqparse.RequestParser()
product_put_args.add_argument("name", type = str, help = "Name of the product")
product_put_args.add_argument("quantity", type = int, help = "Quantity of the item")

products = {}

class Product(Resource):
def get(self, barcode):
return products[barcode]

def put(self, barcode):
args = product_put_args.parse_args()
return {barcode: args}

api.add_resource(Product, "/product/<int:barcode>")

if(__name__) == "__main__":
app.run(debug = True)

还有我的测试.py

import requests

base = "http://127.0.0.1:5000/"

response = requests.put(base + "product/1", {"name": "testitem"})
print(response.json())

我已尝试对 mat 进行改革并更改两个文件以找出导致问题的原因,我觉得这很简单,但如果你能帮助我,我敢打赌这会对我和许多其他正在尝试的人有所帮助开始创建休息 API。

最佳答案

您需要将位置信息添加到 RequestParser 默认情况下它会尝试解析来自 flask.Request.valuesflask.Request.json 的值,但是在你的情况,需要从 flask.request.form 中解析这些值.下面的代码修复了你的错误

from flask import Flask,request
from flask_restful import Api, Resource, reqparse

app = Flask(__name__)
api = Api(app)

product_put_args = reqparse.RequestParser()
product_put_args.add_argument("name", type = str, help = "Name of the product", location='form')
product_put_args.add_argument("quantity", type = int, help = "Quantity of the item", location='form')

products = {}

class Product(Resource):
def get(self, barcode):
return products[barcode]

def put(self, barcode):
args = product_put_args.parse_args()
products[barcode] = args['name']
return {barcode: args}

api.add_resource(Product, "/product/<int:barcode>")

if(__name__) == "__main__":
app.run(debug = True)

关于python - Flask 请求语法错误的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71794902/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com