python flask orm sqlalchemy 实例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python flask orm sqlalchemy 实例相关的知识,希望对你有一定的参考价值。

flask_sqlalchemy.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(name)
app.config[‘SQLALCHEMY_DATABASE_URI‘] = ‘sqlite://‘
app.config[‘SQLALCHEMY_TRACK_MODIFICATIONS‘] = True
db = SQLAlchemy(app)

定义ORM

class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
def init(self, name, email):
self.name = name
self.email = email
def repr(self):
return ‘<User %r>‘ % self.name

创建表格、插入数据

@app.before_first_request
def create_db():
#Recreate database each time for demo
#db.drop_all()
db.create_all()
admin = User(‘admin‘, ‘admin@example.com‘)
db.session.add(admin)
guestes = [User(‘guest1‘, ‘guest1@example.com‘),
User(‘guest2‘, ‘guest2@example.com‘),
User(‘guest3‘, ‘guest3@example.com‘),
User(‘guest4‘, ‘guest4@example.com‘)]
db.session.add_all(guestes)
db.session.commit()

查询

@app.route(‘/user‘)
def users():
users = User.query.all()
return "<br>".join(["{0}: {1}".format(user.name, user.email) for user in users])

查询

@app.route(‘/user/<int:id>‘)
def user(id):
user = User.query.filter_by(id=id).one()
return "{0}: {1}".format(user.name, user.email)

运行

if name == ‘main‘:
app.run(‘127.0.0.1‘, 5000)

以上是关于python flask orm sqlalchemy 实例的主要内容,如果未能解决你的问题,请参考以下文章

python flask orm sqlalchemy 实例

Flask的ORM和查询操作

SQLAlchemy-ORM

python的一些开源库

第四篇 与Flask相关的插件(flask-sessionwtformsSQLAchemy)

Flask 入门教程:第一章节路由和视图