python flask框架学习(四):数据库配置,flask_sqlalchemy使用


project/app/config/secure.py 数据库URI连接配置

DB_HOST = '127.0.0.1'
DB_PORT = '3306'
DB_DATABASE = 'flask_demo'
DB_USERNAME = 'root'
DB_PASSWORD = 'root'

SQLALCHEMY_DATABASE_URI = f'mysql+mysqlconnector://{DB_USERNAME}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_DATABASE}'
SQLALCHEMY_TRACK_MODIFICATIONS = False
# SQLALCHEMY_ECHO = True
SECRET_KEY = '\x00\x8b\x15\x10R\xc5t &\x13\xad"\xff\xe2\xb0&\xbeK\xfb\x99\xfc\xba\x17}'
# import os
# os.urandom(24) #随机码

project/app/models/base.py 使用flask_sqlalchemy ORM操作数据库,创建db对象

from datetime import datetime
from sqlalchemy import Column, Integer, SmallInteger
from flask_sqlalchemy import SQLAlchemy as _SQLAlchemy, BaseQuery
from contextlib import contextmanager


# 增加自动提交事务
class SQLAlchemy(_SQLAlchemy):
    @contextmanager
    def auto_commit(self):
        try:
            yield
            self.session.commit()
        except Exception as e:
            db.session.rollback()
            raise e

# 重写filter_by函数
class Query(BaseQuery):
    def filter_by(self, **kwargs):
        if 'status' not in kwargs.keys():
            kwargs['status'] = 1
        return super().filter_by(**kwargs)

db = SQLAlchemy(query_class=Query)

class Base(db.Model):
    __abstract__ = True
    create_time = Column('create_time', Integer)
    status = Column(SmallInteger, default=1)

    def __init__(self):
        self.create_time = int(datetime.now().timestamp())

    def set_attrs(self, attrs_dict):
        for key, value in attrs_dict.items():
            if hasattr(self, key) and key != 'id':
                setattr(self, key, value)

    @property
    def create_datetime(self):
        if self.create_time:
            return datetime.fromtimestamp(self.create_time)
        else:
            return None


project/app/app.py 在app上下文中初始化数据库

from flask import Flask

# from app.api.v1 import register_blueprint
from app.models.base import db

def create_app():
    app = Flask(__name__)
    # app.config.from_object('app.config.setting')
    app.config.from_object('app.config.secure')
    db.init_app(app) #注册数据库
    with app.app_context():
        db.create_all()
    # register_blueprint(app)
    return app

project/app/models/user.py 创建一个user数据表

from werkzeug.security import generate_password_hash, check_password_hash
from app.models.base import Base, db


class User(Base):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(24), unique=True, nullable=False)
    nickname = db.Column(db.String(24), unique=True)
    auth = db.Column(db.SmallInteger, default=1)
    _password = db.Column('password', db.String(100))

    @property
    def password(self):
        return self._password

    @password.setter
    def password(self, raw_password):
        self._password = generate_password_hash(raw_password)

    def check_password(self, raw_password):
        return check_password_hash(self._password, raw_password)

    @staticmethod
    def register_by_email(nickname, account, secret):
        with db.auto_commit():
            user = User()
            user.nickname = nickname
            user.email = account
            user.password = secret
            db.session.add(user)

project/main.py 入口文件

from app.app import create_app

app = create_app()

if __name__ == '__main__':
    app.run(debug=True, port=5050)

你可能感兴趣的:(python flask框架学习(四):数据库配置,flask_sqlalchemy使用)