文章目录
显示
一、代码结构
一个好的框架是易扩展的。
├─.idea
├─common 公用代码
│ ├─libs 公用代码或类
│ └─models 所有数据库的Model
├─config 配置文件
├─docs 文档存放
├─jobs 定时任务
│ └─tasks
└─web HTTP相关
└─controllers 所有的控制层都放在这里
二、实战简单MVC框架
2.1项目框架的搭建
先删除之前的代码,创建common
这个python文件夹
以及它的2个子文件夹libs
和models
。
其次,创建config
文件夹,在虾米那创建base_etting.py
和local_setting.py
以及production_setting.py
添加docs
目录,并添加mysql.md
文件用于说明数据库的使用
创建jobs
文件夹,在那创建tasks
文件夹
再创建web
目录:
创建application.py
等外部文件夹:
以上就完成了项目最基本的代码框架的搭建。
2.2 app封装
2.2.1简单封装
首先再application
里面进行app封装:
# -*- coding: utf-8 -*-
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
class Application( Flask ):
def __init__(self,import_name):
super( Application,self ).__init__( import_name )
self.config.from_pyfile( 'config/base_setting.py' )
db.init_app( self )
db = SQLAlchemy()
app = Application( __name__ )
manager.py
添加:
# -*- coding: utf-8 -*-
from application import app
def main():
app.run(host='0.0.0.0', debug=True)
# manager.run( )
if __name__ == '__main__':
try:
import sys
sys.exit( main() )
except Exception as e:
import traceback
traceback.print_exc( )
2.2.2添加配置
base_setting.py
添加配置文件,去除代码警告
SQLALCHEMY_DATABASE_URI = 'mysql://root:123456@127.0.0.1/mysql?charset=utf8mb4'
SQLALCHEMY_TRACK_MODIFICATIONS = False
2.2.3安装flask-script扩展
为管理manager入口,我们需要引入flask_script库,它为flask框架提供了扩展的能力
https://flask-script.readthedocs.io/en/latest/
pip install Flask-Script
2.2.4调用flask-script自定义启动参数
因为flask-script有一些特性可供我们扩展、它可以自定义命令。
application.py
# -*- coding: utf-8 -*-
from flask import Flask
from flask_script import Manager
from flask_sqlalchemy import SQLAlchemy
class Application( Flask ):
def __init__(self,import_name):
super( Application,self ).__init__( import_name )
self.config.from_pyfile( 'config/base_setting.py' )
db.init_app( self )
db = SQLAlchemy()
app = Application( __name__ )
# app包装
manager = Manager( app )
manager.py
# -*- coding: utf-8 -*-
from application import app,manager
from flask_script import Server
##web server
manager.add_command( "runserver", Server( host='0.0.0.0',port=5000,use_debugger = True ,use_reloader = True) )
def main():
manager.run( )
# app.run(host='0.0.0.0', debug=True)
if __name__ == '__main__':
try:
import sys
sys.exit( main() )
except Exception as e:
import traceback
traceback.print_exc( )
运行:
2.2.5端口配置化
base_setting.py
添加配置文件
SQLALCHEMY_DATABASE_URI = 'mysql://root:123456@127.0.0.1/mysql?charset=utf8mb4'
SQLALCHEMY_TRACK_MODIFICATIONS = False
SERVER_PORT = 8999
manager.pu
# -*- coding: utf-8 -*-
from application import app,manager
from flask_script import Server
##web server
manager.add_command( "runserver", Server( host='0.0.0.0',port=app.config['SERVER_PORT'],use_debugger = True ,use_reloader = True) )
这样 既可以通过8999这个端口访问了:
2.2.6加载不同环境的配置实现
application.py添加如下语句
# -*- coding: utf-8 -*-
from flask import Flask
from flask_script import Manager
from flask_sqlalchemy import SQLAlchemy
import os
class Application( Flask ):
def __init__(self,import_name):
super( Application,self ).__init__( import_name )
self.config.from_pyfile( 'config/base_setting.py' )
if "ops_config" in os.environ:
self.config.from_pyfile( 'config/%s_setting.py'%os.environ['ops_config'] )
将SERVER_PORT = 9000这个设置从base_setting.py
拷贝到local_setting.py
修改环境变量:
windwos下修改
Linux下修改:
export ops_config=local
再次运行:
2.2.7配置统一规划
base_setting.py
# -*- coding: utf-8 -*-
SERVER_PORT = 8999
DEBUG = False
SQLALCHEMY_ECHO = False
local_setting.py
# -*- coding: utf-8 -*-
SQLALCHEMY_DATABASE_URI = 'mysql://root:123456@127.0.0.1/mysql?charset=utf8mb4'
SQLALCHEMY_TRACK_MODIFICATIONS = False
DEBUG = True
SQLALCHEMY_ECHO = True
SQLALCHEMY_ENCODING = "utf8mb4"
2.2.8入口页面的添加
web创建controllers
层,然后创建index.py文件
# -*- coding: utf-8 -*-
from flask import Blueprint
route_index = Blueprint( 'index_page',__name__ )
@route_index.route("/")
def index():
return "Hello World"
www.py
添加Blueprnit
# -*- coding: utf-8 -*-
from application import app
from web.controllers.index import route_index
app.register_blueprint( route_index,url_prefix = "/" )
入喉文件引入
访问