1.flask-sqlalchemy使用
1.使用原生sqlalchemy写接口:只要一访问根目录,就会添加这本书
from flask import Flask
from settings import session
from models import Book
app = Flask(__name__)
@app.route('/')
def index():
'''数据暂时写死,后期可以动态添加'''
session.add(Book(name='三国演义'))
session.commit()
session.close()
return '增加成功'
if __name__ == '__main__':
app.run()
models.py:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
Base = declarative_base()
class Book(Base):
__tablename__ = 'books'
id = Column(Integer,primary_key=True)
name = Column(String(32))
sqlalchemy11.py:
from flask import Flask
from settings import session
from models import Book
app = Flask(__name__)
@app.route('/')
def index():
session.add(Book(name='三国演义'))
session.commit()
session.close()
return '增加成功'
if __name__ == '__main__':
app.run()
2.使用flask_sqlalchemy继承到flask,这种方法可以将session封装到db对象中,这样db对象中的session和全局的session不会产生错乱:
managepy
from flask_sqlalchemy import SQLAlchemy
from flask import Flask
app = Flask(__name__)
app.config.from_pyfile('settings.py')
# 1.实例化得到对象
db = SQLAlchemy()
# 2.将db注册到app中
db.init_app(app)
@app.route('/')
def index():
from models import Book
# 3.视图函数中使用session
db.session.add(Book(name='红楼梦'))
db.session.commit()
return '增加成功'
if __name__ == '__main__':
app.run()
models.py:
from sqlalchemy.ext.declarative import declarative_base
from manage import db
Base = declarative_base()
'''需要继承db.Model'''
class Book(db.Model):
__tablename__ = 'books'
'''字段类型也需要从db对象中点'''
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(32))
settings.py
SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:123456@127.0.0.1:3306/aaa?charset=utf8"
SQLALCHEMY_POOL_SIZE = 5
SQLALCHEMY_POOL_TIMEOUT = 30
SQLALCHEMY_POOL_RECYCLE = -1
# 追踪对象的修改并且发送信号
SQLALCHEMY_TRACK_MODIFICATIONS = False
flask-migrate使用
原生的sqlalchemy不支持修改表。flask-migrate可以实现类似于django的数据库迁移命令:
django中的两步命令:
python manage.py makemigrations # 记录数据库变化
python manage.py migrate # 真正将数据同步到数据库
通过flask-migrate我们在flask中也可以实现类似于django中的两步操作
标签:__,sqlalchemy,flask,app,db,session,使用,import From: https://www.cnblogs.com/ERROR404Notfound/p/17307382.html