flask创建步骤

1.在__init__.py中创建db对象

from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

2.同样的在__init__.py中create_app函数中让app传入到db中

def create_app():
    app = Flask(__name__)
    app.config.from_object('settings.DevelopmentConfig')

    app.register_blueprint(ac)
    app.register_blueprint(hm)

    db.init_app(app)
    Auth(app)
    
    return app

3.写配置文件,在settings中将连接字符串定义在配置文件中

class BaseConfig(object):
    # SESSION_TYPE = 'redis'  # session类型为redis
    # SESSION_KEY_PREFIX = 'session:'  # 保存到session中的值的前缀
    # SESSION_PERMANENT = True  # 如果设置为False,则关闭浏览器session就失效。
    # SESSION_USE_SIGNER = False  # 是否对发送到浏览器上 session:cookie值进行加密

    SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:[email protected]:3306/s8day130db?charset=utf8"
    SQLALCHEMY_POOL_SIZE = 5
    SQLALCHEMY_POOL_TIMEOUT = 30
    SQLALCHEMY_POOL_RECYCLE = -1

    # 追踪对象的修改并且发送信号
    SQLALCHEMY_TRACK_MODIFICATIONS = False

    SECRET_KEY = "11111jfadfqaee"

class ProductionConfig(BaseConfig):
    pass

4.定义models.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, UniqueConstraint, Index,DateTime,ForeignKey
from demo import db

class Users(db.Model):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True,autoincrement=True)
    name = Column(String(32),nullable=False,unique=True)
    pwd = Column(String(32),nullable=False)

5.穿件数据库表,编写离线脚本:drop_create_table.py

from demoimport db
from demoimport create_app
from demoimport models

app = create_app()
with app.app_context():
    db.drop_all()
    db.create_all()
    # data = db.session.query(models.Users).all()
    # print(data)

6.在视图函数中使用sqlalchemy操作数据库

from demo import models
from demoimport db
ac = blueprints.Blueprint('ac',__name__)

@ac.route('/login',methods=['GET','POST'])
def login():
	data = db.session.query(models.Users).all()
	db.session.commit()
	return "login"

你可能感兴趣的:(flask,python,后端)