python flask web開(kāi)發(fā)實(shí)戰(zhàn) DB flask-sqlalchemy

連接方式

MySQL mysql://username:password@hostname/database
Postgres postgresql://username:password@hostname/database
SQLite(Unix) sqlite:////absolute/path/to/database
SQLite(Windows) sqlite:///c:/absolute/path/to/database

1、配置連接DB
from flask.ext.sqlalchemy import SQLAlchemy
basedir = os.path.abspath(os.path.dirname(file))
app = Flask(name)
app.config['SQLALCHEMY_DATABASE_URI'] =
'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
db = SQLAlchemy(app)

2、配置模型 db.Model db.Column
class Role(db.Model):
tablename = 'roles'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
def repr(self):
return '<Role %r>' % self.name
class User(db.Model):
tablename = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), unique=True, index=True)
def repr(self):
return '<User %r>' % self.username


在hello.py中配置導(dǎo)入數(shù)據(jù)庫(kù)

from flask.ext.script import Shell
def make_shell_context():
return dict(app=app, db=db, User=User, Role=Role)
manager.add_command("shell", Shell(make_context=make_shell_context))
3、常用列
db.Integer
SmallInteger
BigInteger
Float
Numeric
String
Text
Unicode
UnicodeText
Boolean
Date
Time
DateTime
Interval 時(shí)間間隔
Enum
PickleType
LargeBinary 二進(jìn)制文件


primary_key
unique
index
nullable
default
4、外鍵引用
class Role(db.Model):
# ...
users = db.relationship('User', backref='role', lazy='dynamic')
class User(db.Model):
# ...
role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))

relationship中的參數(shù):

backref 在關(guān)系的另一個(gè)模型中添加反向關(guān)系
lazy select,immediate,joined,subquery,noload,dynamic
uselist 是否使用列表
order_by
secondary
secondaryjoin
5、DB操作
db.create_all()
drop_all()

添加

db.session.add()


image.png

修改也是add

image.png

刪除delete

image.png

查詢

Role.query.all()
User.query.filter_by(role=user_role).all()
user_role = Role.query.filter_by(name='User').first()

filter()
filter_by()
limit()
offset()
order_by()
group_by()


all() 以列表形式返回查詢的所有結(jié)果
first() 返回查詢的第一個(gè)結(jié)果,如果沒(méi)有結(jié)果,則返回None
first_or_404() 返回查詢的第一個(gè)結(jié)果,如果沒(méi)有結(jié)果,則終止請(qǐng)求,返回404 錯(cuò)誤響應(yīng)
get() 返回指定主鍵對(duì)應(yīng)的行,如果沒(méi)有對(duì)應(yīng)的行,則返回None
get_or_404() 返回指定主鍵對(duì)應(yīng)的行,如果沒(méi)找到指定的主鍵,則終止請(qǐng)求,返回404 錯(cuò)誤響應(yīng)
count() 返回查詢結(jié)果的數(shù)量
paginate() 返回一個(gè)Paginate 對(duì)象,它包含指定范圍內(nèi)的結(jié)果
6、


image.png

7、數(shù)據(jù)庫(kù)操作


image.png

image.png

數(shù)據(jù)庫(kù)遷移 flask-migrate

1、
from flask.ext.migrate import Migrate, MigrateCommand

...

migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)
2|
python hello.py db init
python hello.py db migrate -m "initial migration"
python hello.py db upgrade

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容