当我输入一个int(产品名称的字符串与价格和数量中的int相同)的int时,我需要能够显示我的消息。运行代码时,我收到此错误:
"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}