python - Flask 错误:“无法解码 JSON 对象”由于意外类型
问题描述
当我输入一个整数时,我需要能够显示我的消息,其中产品名称的字符串与价格和数量的整数相同。当我运行我的代码时,我收到此错误:
"message": "Failed to decode JSON object: Expecting value: line 3
如何确保在意外输入 int 时,我的代码不会引发此错误?
这是我的代码:
来自视图的代码
from flask_restplus import Resource, reqparse, Namespace, fields
from .models import Products
product = Products()
create_product = product_api.model("Create product", {"product_name": fields.String, "quantity": fields.Integer,
"product_price": fields.Integer})
@product_api.expect(create_product)
def post(self):
parser = reqparse.RequestParser()
parser.add_argument("product_name", help="product name should be provided", required=True,
location=["json"])
parser.add_argument("quantity", help="quantity should be provided", required=True,
location=["json"])
parser.add_argument("product_price", help="price should be provided", required=True,
location=["json"])
arguments = parser.parse_args()
if arguments["product_name"] == int:
return {"txt": "please enter a string"}
response = product.create_product(product_name=arguments["product_name"], quantity=arguments["quantity"],
product_price=arguments["product_price"])
return response, 201
模型代码
from werkzeug.security import generate_password_hash, check_password_hash
class Products:
"""Functionality of products"""
products = {}
def create_product(self, product_name, quantity, product_price):
if product_name == "":
return {"txt": "product name must be provided"}
if product_price == "":
return {"txt": "price value must be provided"}
new_id = len(self.products) + 1
self.products[new_id] = {"product_name": product_name, "quantity": quantity,
"product_price": product_price, }
res = self.products[new_id]
return {"msg": "Product added successfully", "data": res}
解决方案
推荐阅读
- file - 从 Jenkins Groovy 脚本控制台编写文件
- sql - 通过c#代码检索存储在sql表中的Json值的最佳实践
- algorithm - 量子计算中Shor算法的电路实现一题
- python - 合并 pandas 中列名不同且长度不同的两个数据框
- autohotkey - 在单独的线程中运行脚本文件中的每个热键(每个热键的最大线程数 = 1)
- sql - 在sql中具有不同的最大值
- python - docker 内的 Conda 更改了我兼容的 pip 轮平台标签
- debugging - 如何突出显示两个文件之间的行?
- linux - AH00544: httpd: 错误的组名 nogroup
- mongodb - MongoDB聚合中的嵌套分组