Flask SQLAlchemy

Flask SQLAlchemy

一、下载安装

pip3 install flask-sqlalchemy

二、导入并实例化SQLAlchemy

# 在跟项目同名的文件夹下的 init.py中
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

from .views.user import us

# !!! 注意事项
#   必须在导入蓝图之前

三、初始化

def create_app():
    app = Flask(__name__)
    app.config.from_object("settings.BaseConfig")

    app.register_blueprint(us)
    # Flask-Session 第一步实例化session
    Session(app)
    # 初始化db
    db.init_app(app)
    return app

四、在配置文件写入配置信息

class BaseConfig(object):
    # Flask-Session  第二步
    # SESSION_TYPE = 'redis'
    # SESSION_REDIS = Redis(host='192.168.0.94', port='6379')

    SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:root1234@127.0.0.1:3306/code_record?charset=utf8"
    SQLALCHEMY_POOL_SIZE = 10
    SQLALCHEMY_MAX_OVERFLOW = 5

    # SQLALCHEMY_TRACK_MODIFICATIONS = False
    pass

五、创建model

# by gaoxin
from sqlalchemy import Column, Integer, String
from flask_demo import db


class Users(db.Model):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String(32), index=True, nullable=False)

六、生成表(需要使用app上下文)

# by gaoxin
from flask_demo import db, create_app
from flask_demo.models import *
# 一定要导入models 否则找不到表创建不出来 app = create_app() app_ctx = app.app_context() with app_ctx: db.create_all() # db.drop_all()

七、基于ORM对数据库操作

# by gaoxin
from flask import Blueprint
from flask_demo import db
from flask_demo.models import Users

us = Blueprint("us", __name__)


@us.route("/index")
def index():
    # db.session.add(Users(name="gaoxin"))
    # db.session.commit()
    # db.session.remove()
    ret = db.session.query(Users).all()
    print(ret)
    db.session.remove()
    return "Index"

 Flask-Script

一、下载安装

pip3 install flask-script

二、增加的功能 runserver

# by gaoxin

from flask_demo import create_app
from flask_script import Manager

app = create_app()
manager = Manager(app)

if __name__ == '__main__':
    # app.run()
    manager.run()
# 启动命令变成
# python3 manager.py runserver -h 127.0.0.1 -p 8000
# Running on http://127.0.0.1:8000/ (Press CTRL+C to quit)

三、自定义命令

# by gaoxin

from flask_demo import create_app
from flask_script import Manager

app = create_app()
manager = Manager(app)


# 位置传参
@manager.command
def custom(arg):
    """
    自定义命令
    python manage.py custom 123
    :param arg:
    :return:
    """
    print(arg)
    
    
# 关键字传参
@manager.option('-n', '--name', dest='name')
@manager.option('-u', '--url', dest='url')
def cmd(name, url):
    """
    自定义命令
    执行: python manage.py  cmd -n wupeiqi -u http://www.oldboyedu.com
    :param name:
    :param url:
    :return:
    """
    print(name, url)


if __name__ == '__main__':
    # app.run()
    manager.run()

 Flask-migrate

一、下载安装

pip3 install flask-migrate

二、增加的命令  

  !!!! 依赖flask-script  !!!!

# by gaoxin

from flask_demo import create_app, db
from flask_demo.models import *
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand

app = create_app()
manager = Manager(app)
Migrate(app, db)

"""
# 数据库迁移命名
# 依赖 flask-script
python manage.py db init # 初始化
python manage.py db migrate # makemigrations
python manage.py db upgrade # migrate
"""
manager.add_command("db", MigrateCommand)

if __name__ == '__main__':
    # app.run()
    manager.run()

posted on 2018-11-19 10:39  cai128118*  阅读(149)  评论(0编辑  收藏  举报

导航