Flask REST 中的整数范围 API 使用 SQLAlchemy

Integer range in Flask REST API using SQLAlchemy

我正在使用 Flask、SQLAlchemy 和 Marshmallow 创建 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)

我必须执行以下逻辑:

  1. 设置价格值介于0 - 100
  2. 之间
  3. 设置数量值介于 0 - 100
  4. 之间

如果成功return 200,如果有任何错误return 500

我无法通过 db.Integer([0, 100]) 在给定范围内设置整数值,因为它给我错误:

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 之间的值的方法的代码存在问题,相反,您应该做的是在名为 [ 的方法的帮助下使用范围=14=] 来自图书馆 random。恕我直言,我其实并不知道你想要完成什么,如果我错了,请在评论中纠正我,我会纠正我的 post.

我建议您不要在模型 class 中设置价格和数量,而是在完全不同的函数中使用您的模型 class 在您的模型中创建元素数据库。例如:

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的作用是选择变量range1range2之间的范围。至于返回 200500,我不确定你可以用这个值做什么,但我建议做布尔值。如果需要,200500 只是一个常量,您可以通过将其放在函数中而不是使用返回值来计算事物来轻松实现它。那么,您将如何使用 ProductRange 函数?只需按照下面的代码即可。

from random import randrange

class Product(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    product_name = db.Column(db.String) # Ignore this line, this just for the /addpost route to get the method POST
    price = db.Column(db.Integer)
    qty = db.Column(db.Integer)

def ProductRange(range1, range2):
    return randrange(range1, range2)

# This route is just an example of how you would use the function ProductRange
@app.route('/addpost', methods=['POST'])
def addpost():
    product_name = request.form['product_name']
    price = ProductRange(1,100)
    qty = ProductRange(1,100)
    post = Product[product_name=product_name, price=price, qty=qty]

    db.session.add(post)
    db.session.commit()

    return redirect(url_for('index'))

如果还是不行,请在下方留言,帮我进一步解答你的这个问题。祝你好运。

因为你已经安装了 marshmallow,安装 marmallow-sqlalchemy 并使用 SQLAlchemyAutoSchema 功能,这将允许你直接引用模型并在成功加载 json object 在请求正文中发送,另外您可以在模式 class 中定义自己的约束。棉花糖会议。看起来像:

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, validate=[Range(max=100, 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"
    ]
}