先创建数据库依赖文件如 flask-sqlalchemy.py
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy()
然后,创建数据库表单,database.py
from database_extention import db class User(db.Model): id = db.Column( db.Integer, primary_key=True) name = db.Column( db.String( 50 ), unique = True ) email = db.Column( db.String( 120 ), unique = True ) password = db.Column( db.String( 120 ) )
__tablename__ = 'users' def __init__( self, name, email, password ): self.name = name self.email = email self.password = password def __repr( self ): return '<User %r>' % (self.name)
最后,在应用中引用数据库:
from flask import Flask, session, g, render_template from database_extention import db from database import User app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db.init_app( app )
db.create_all(app =app) @app.route('/') def show_home(): return "ok" @app.route('/add') def add_user(): user = User('liuchao', 'liuchao@hotmail.com', 'liu') db.session.add(user) db.session.commit() return 'save ok' @app.route('/showrecord') def show_record(): users = User.query.all() records = [ dict( username=user.name, email=user.email ) for user in users ] return render_template('showrecord.html', records = records ) if __name__ == "__main__": app.run(debug=True)
需要注意的是,直接return records会导致TypeError: 'list' object is not callable错误。需要render_template模板来处理。