Flask SQLAlchemy

Flask SQLAlchemy

1、下載安裝python

pip3 install flask-sqlalchemy

2、導入並實例化SQLAlchemymysql

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

from .views.user import us

# !!! 注意事項
#   必須在導入藍圖以前

3、初始化redis

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

4、在配置文件寫入配置信息sql

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

5、建立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)

6、生成表(須要使用app上下文)flask

# 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()

7、基於ORM對數據庫操做session

# 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

1、下載安裝app

pip3 install flask-script

2、增長的功能 runserverui

# 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)

3、自定義命令url

# 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

1、下載安裝

pip3 install flask-migrate

2、增長的命令  

  !!!! 依賴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()
相關文章
相關標籤/搜索