我正在观看烧瓶教程,并且我完全按照步骤进行。现在我们在数据库中,我正在使用 sqlalchemy。让我感到困惑的部分是当我尝试将数据转换为表(这就是那家伙所说的)并且在输入 db.create_all() 后,终端给了我一个运行时错误。然后我看到每个人都有同样的问题,有人说在 createall 之前实现 app.app_context()push() 命令行。 然而它又给出了另一个错误,但这次它说名称“app”未定义。
# import the flask module
from flask import Flask, render_template
# we import the database tool
from flask_sqlalchemy import SQLAlchemy
# we set the class variable
app = Flask(__name__)
# we set the app in order to recognize the database and we give it a name
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///market.db'
# we create our variable where the db is gonna be stored
db = SQLAlchemy(app) # we pass our app variable as a parameter
# we create the class model
class Item(db.Model):
# parameters after specifying the type of database
# --> (data type(optional : length), nullable, unique)
# the primary key parameter is only gonna be used on the id
id = db.Column(db.Integer(), primary_key = True)
name = db.Column(db.String(length = 30), nullable = False, unique = True)
price = db.Column(db.Integer(), nullable = False)
barcode = db.Column(db.String(length = 12), nullable = False, unique = True)
description = db.Column(db.String(length = 500), nullable = False, unique = True)
# we set the route (url)
@app.route('/') # decorator
# we set the main function
def home_page():
return render_template('home.html')
@app.route('/market')
def market():
items = [
{'id': 1, 'name': 'Phone', 'barcode': '893212299897', 'price': '$500'},
{'id': 2, 'name': 'Laptop', 'barcode': '123985473165', 'price': '$900'},
{'id': 3, 'name': 'Keyboard', 'barcode': '231985128446', 'price': '$150'}
]
# primer parametro será nuestro archivo html
return render_template('market.html', item_name = 'Phones', items = items) # colocar el segundo parametro en el archivo html
为了在 python 控制台中使用您的应用程序,有必要导入它。此外,错误消息表明由于缺少句点而发生语法错误。
我建议您使用 Flask shell 而不是 python 控制台,它会在启动时初始化应用程序上下文。
flask --app market shell
无需推送,导入数据库后直接建表即可。
from market import db, Item
db.create_all()