时间:2021-07-01 10:21:17 帮助过:3人阅读
CSRF_ENABLED=True SECRET_KEY='you-will-never-guess' import os basedir = os.path.abspath(os.path.dirname(__file__)) SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db') SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository') SQLALCHEMY_TRACK_MODIFICATIONS=True #db文件创建在与创建脚本同一目录下 # SQLALCHEMY_DATABASE_URI是the Flask-SQLAlchemy必需的扩展。这是我们的数据库文件的路径。 # SQLALCHEMY_MIGRATE_REPO 是用来存储SQLAlchemy-migrate数据库文件的文件夹。 #SQLALCHEMY_TRACK_MODIFICATIONS 不设为True会报错(貌似段代码没有也能正常运行)
from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app=Flask(__name__) app.config.from_object('config') db=SQLAlchemy(app) from app import views,models #导入Flask-SQLAlchemy #创建了一个 db 对象,这是我们的数据库 #导入一个新的模块,叫做 models
from app import db class User(db.Model): id = db.Column(db.Integer, primary_key=True) nickname = db.Column(db.String(64), index=True, unique=True) email = db.Column(db.String(120), index=True, unique=True) posts = db.relationship('Post', backref='author', lazy='dynamic') def __repr__(self): return '<User %r>' % (self.nickname) class Post(db.Model): id = db.Column(db.Integer, primary_key = True) body = db.Column(db.String(140)) timestamp = db.Column(db.DateTime) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) def __repr__(self): return '<Post %r>' % (self.body)
from app import db db.create_all() #create_all( )是创建数据库
from app import db, models def add_com (u): db.session.add(u) db.session.commit() u = models.User(nickname='john', email='john@email.com') add_com(u) w=models.User(nickname='susan', email='susan@email.com') add_com(w) #session.add( )添加数据 #session.commit( )提交事务
import datetime from app import db, models u = models.User.query.get(1) p = models.Post(body='my first post!', timestamp=datetime.datetime.utcnow(), author=u) db.session.add(p) db.session.commit() #authou就是Post数据类里的user_id(应该是的)
from app import db, models users = models.User.query.all() print users for u in users : print u.id,u.nickname e=models.User.query.get(1) print e p=models.User.query.filter_by(nickname="john").first() print p.id print p.email d=models.User.query.filter(models.User.email.endswith('@email.com')).all() print d
from app import db, models u = models.User.query.get(1) print u posts = u.posts.all() print posts e=models.User.query.get(2) print e.posts.all()
from app import db, models users = models.User.query.all() for u in users: db.session.delete(u) posts = models.Post.query.all() for p in posts: db.session.delete(p) db.session.commit() #session.delete( )删除
flask笔记:5:数据库
标签: