问题描述
我正在使用Flask,sqlAlchemy和棉花糖创建REST API。我在app.py
中将产品模型定义为:
from flask import Flask,request,jsonify
from flask_sqlalchemy import sqlAlchemy
from flask_marshmallow import Marshmallow
import os
# Initialize App
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
# Database Setup
app.config['sqlALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir,'db.sqlite')
app.config['sqlALCHEMY_TRACK_MODIFICATIONS'] = False
# Init db
db = sqlAlchemy(app)
# Init marshmallow
ma = Marshmallow(app)
# Product Class/Model
class Product(db.Model):
id = db.Column(db.Integer,primary_key=True)
price = db.Column(db.Integer)
qty = db.Column(db.Integer)
def __init__(self,price,qty):
self.price = price
self.qty = qty
# Product Schema
class ProductSchema(ma.Schema):
class Meta:
fields = ('id','price','qty')
# Init Schema
product_schema = ProductSchema()
products_schema = ProductSchema(many=True)
# Create Product
@app.route('/product',methods=['POST'])
def add_product():
price = request.json['price']
qty = request.json['qty']
new_product = Product(price,qty)
db.session.add(new_product)
db.session.commit()
return product_schema.jsonify(new_product)
# Run the Server
if __name__ == '__main__':
app.run(debug=True)
我必须执行以下逻辑:
- 在
0 - 100
之间设置价格值 - 在
0 - 100
之间设置数量值
如果成功return 200
,如果有任何问题return 500
。
我无法在db.Integer([0,100])
的给定范围内设置Integer值,因为它给了我错误:
TypeError: Integer() takes no arguments
如何实现以上逻辑?
解决方法
编辑:我误解了这个问题,并做了一个新功能。
def ExpectedRange(var1):
return 200 if var1 in range(0,100) else 500
# Create Product
@app.route('/product',methods=['POST'])
def add_product():
price = request.json['price']
qty = request.json['qty']
if ExpectedRange(price) and ExpectedRange(qty) == 200:
new_product = Product(price,qty)
db.session.add(new_product)
db.session.commit()
return product_schema.jsonify(new_product)
#else:
# Show error. I recommend you using the method 'flash' in flask.
我认为通过使用db.Integer([0,100])
作为查找0到100之间的值的方法,您的代码存在问题,相反,您应该做的是在名为{{1 }}来自库randrange
。出于所有应有的尊重,我实际上不知道您要完成的工作,如果我错了,请在评论中更正我,我将更正我的帖子。
我建议您不要在模型类中设置价格和数量,而要在完全不同的函数中使用模型类在数据库中创建元素。例如:
random
函数from random import randrange
class Product(db.Model):
id = db.Column(db.Integer,primary_key=True)
price = db.Column(db.Integer)
qty = db.Column(db.Integer)
def ProductRange(range1,range2):
return randrange(range1,range2)
print(ProductRange(1,100))
的作用是选择变量ProductRange
和range1
之间的范围。至于返回range2
和200
,我不确定该值可以使用什么,但是我建议使用布尔值。如果需要,500
和200
只是一个常数,您可以通过将其放入函数中而不是使用返回值来计算事物来轻松实现它。那么,您将如何使用500
函数?只需遵循以下代码即可。
ProductRange
如果它不起作用,请在下面对我进行评论,以帮助您进一步解决您的问题。祝你好运。
,因为您已经安装了棉花糖,所以请安装marmallow-sqlalchemy并使用SQLAlchemyAutoSchema功能,该功能将允许您直接引用模型并在成功加载请求正文中发送的json对象后创建实例,此外您还可以定义模式类中自己的约束。棉花糖会议看起来像:
from marshmallow import ValidationError,fields
from marshmallow.validate import Range
from marshmallow_sqlalchemy import SQLAlchemyAutoSchema
ma = Marshmallow(app)
# to return marshmallow parsing error
@app.errorhandler(ValidationError)
def handle_marshmallow_validation(err):
print(err)
return jsonify(err.messages),400
# Product Schema
class ProductSchema(ma.SQLAlchemyAutoSchema):
id = fields.Integer(required=False)
price = fields.Integer(required=True,validate=[Range(max=100,error="Value must be 100 or less")])
qty = fields.Integer(required=True,error="Value must be 100 or less")])
class Meta:
model = Product
load_instance = True
现在资源将如下所示:
# Create Product
@app.route('/product',methods=['POST'])
def add_product():
# here we can check the payload validity,parse it and transform it directly to instance
product_json = request.get_json()
new_product = product_schema.load(product_json)
db.session.add(new_product)
db.session.commit()
return product_schema.dump(new_product)
现在,如果您发送的值超出了范围,您将收到这样的响应
{
"price": [
"Value must be 100 or less"
],"qty": [
"Value must be 100 or less"
]
}