鱼书项目模块化总结 (3)

view.__init__.py

#view.__init__.py from .main import main from .user import user from .posts import posts BluePrint = [ (main,''), (user,''), (posts,'') ] #封装注册蓝本的函数 def config_blueprint(app): #循环注册蓝本 for blueprint,prefix in BluePrint: app.register_blueprint(blueprint,url_prefix=prefix)

方案二

fisher.py

from app import create_app app = create_app() if __name__ == '__main__': from werkzeug.contrib.fixers import ProxyFix app.wsgi_app = ProxyFix(app.wsgi_app) app.run()

app.__init__.py

#app.__init__.py '''创建flask核心对象''' from flask import Flask from app.models.base import db from flask_login import LoginManager from flask_mail import Mail from app.libs.limiter import Limiter login_manager = LoginManager() mail = Mail() limiter = Limiter() def create_app(): ''' 系统配置与蓝图需要绑定app :return: ''' app = Flask(__name__) app.config.from_object('app.secure') app.config.from_object('app.setting') register_blueprint(app) db.init_app(app) login_manager.init_app(app) login_manager.login_view = 'web.login' login_manager.login_message = '请先登录或者注册' mail.init_app(app) with app.app_context(): db.create_all() return app #注册蓝本 def register_blueprint(app): from app.web.book import web app.register_blueprint(web)

view.__init__.py

#view.__init__.py from flask import Blueprint,render_template '''蓝图 blueprint ''' web = Blueprint('web',__name__) #__name__代表蓝图所在模块 @web.app_errorhandler(404) def not_found(e): ''' AOP: 处理所有的404请求 ''' return render_template('404.html'),404 @web.app_errorhandler(500) def internal_server_error(e): ''' AOP: 处理所有的500请求 ''' return render_template('500.html'),500 #在此处导入代表先初始化在导入应用 #防止循环调用的问题 from app.web import book from app.web import auth from app.web import drift from app.web import gift from app.web import main from app.web import wish 5 生产开发环境下的settings配置

settings配置

1 根据不同等级,配置系统设置

2 配置数据库的连接

3 配置不同环境下的生产

方案一

import os base_path = os.path.abspath(os.path.dirname(__file__)) #配置所有环境的基类 class Config: SECRET_KEY = 'secret_key' SQLALCHEMY_COMMIT_ON_TEARDOWN = True SQLALCHEMY_TRACK_MODIFICATIONS = False MAIL_SERVER = os.environ.get('MAIL_SERVER', 'smtp.163.com') MAIL_USERNAME = os.environ.get('MAIL_USERNAME', 'xxx@163.com') MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD', 'xxx') #配置上传文件 MAX_CONTENT_LENGTH = 1024*1024*64 UPLOADED_PHOTOS_DEST = os.path.join(base_path,'static/upload') PAGE_NUM = 3 #测试 class TestingConfig(Config): SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:xxx@127.0.0.1:3306/blog' #开发 class DevelopmentConfig(Config): SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:xxx@127.0.0.1:3306/blog' # SQLALCHEMY_DATABASE_URI = 'sqlite:///'+ os.path.join(base_path,'develop.sqlite') #生产 class ProductionConfig(Config): SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:xxx@127.0.0.1:3306/blog' #设置字典 config = { 'development':DevelopmentConfig, 'production':ProductionConfig, 'test':TestingConfig, 'default':DevelopmentConfig }

方案二

settings.py

''' 配置文件: 生产环境与开发环境相同的配置,setting可以上传git ''' PER_PAGE = 15 BEANS_UPLOAD_ONE_BOOK = 0.5 RECENT_BOOK_COUNT = 20

secure.py

''' 配置文件:保存单独的加密信息,secure不要上传git ''' DEBUG = True # 单数据库 SQLALCHEMY_DATABASE_URI = 'mysql+cymysql://root:xxx@xxx:3306/fisher' SECRET_KEY = '\SAAFsdfsdf:sdadzxcsd,./.dasdafasd' #Email相关配置 MAIL_SERVER = 'smtp.163.com' MAIL_PORT = 465 MAIL_USE_SSL = True MAIL_USE_TSL = False MAIL_USERNAME = 'xxx@163.com' MAIL_PASSWORD = 'xxx' 6 分页展示 def calulate_start(self,page): return (page-1)* current_app.config.get('PER_PAGE') 7 模型基类的设计

模型类的设置

1 创建基类继承db.Model

2 db实例化通过继承添加容错自动提交数据库功能

3 封装了快速设置属性功能

base.py

from flask_sqlalchemy import SQLAlchemy as _SQLAlchemy, BaseQuery from sqlalchemy import Column, Integer, SmallInteger from contextlib import contextmanager from datetime import datetime class SQLAlchemy(_SQLAlchemy): ''' 封装了数据库的自动提交回滚 ''' @contextmanager def auto_commit(self): try: yield self.session.commit() except Exception as e: self.session.rollback() raise e class Query(BaseQuery): ''' 自定义基类(继承,初始化),重写filter_by方法 ''' def filter_by(self, **kwargs): if 'status' not in kwargs.keys(): kwargs['status'] = 1 return super(Query, self).filter_by(**kwargs) db = SQLAlchemy(query_class=Query) class Base(db.Model): ''' 该模型表不想在数据库创建,添加__abstract__ = True不会创建该表 ''' __abstract__ = True '''类变量在类开始的时候就已经确定了''' create_time = Column('create_time', Integer) status = Column(SmallInteger, default=1) def __init__(self): '''实例变量保证创建时间的准确性''' self.create_time = int(datetime.now().timestamp()) def delete(self): self.status = 0 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

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyjsdx.html