rest - 使用 SQLAlchemy 的 Flask REST API 中的整数范围
问题描述
我正在使用 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)
我必须执行以下逻辑:
- 设置价格值之间
0 - 100
- 设置数量值之间
0 - 100
如果成功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 之间的值,相反,您应该做的是在randrange
从 library调用的方法的帮助下使用 range 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
and 500
,我不确定你可以用这个值做什么,但我建议做布尔值。如果需要它,200
并且500
只是一个常量,您可以通过将其放入函数中轻松实现它,而不是使用返回的值来计算。那么,您将如何使用该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'))
如果它不起作用,请在下面发表评论,以便我进一步帮助您解决这个问题。祝你好运。
推荐阅读
- elasticsearch - Elastic Search Cluster Config - 在一个物理上自动发现、配置和多弹性
- nginx - NGINX - 无法设置内容类型标头
- javascript - ReactiveSearch 的 ReactiveList 不会随着 ES 的变化而更新
- multithreading - 使用多线程处理器调试单线程应用程序的性能
- html - 保持选择选择颜色并添加png作为背景
- mysql - MySQL 查询优化 - 现有查询运行速度太慢
- php - JavaScript - 检查数据 id 是否等于函数参数
- apache-zookeeper - 无法启动 bin/zkCli.sh
- python - 如何使用 jmeter 测试 django web?
- python - NiFi中的输入flowFile没有可行的替代方案