Python flask实战订餐系统微信小程序-14手写MVC框架

wechat 虚幻 559℃ 0评论

一、代码结构

一个好的框架是易扩展的。

├─.idea
├─common 公用代码
│  ├─libs 公用代码或类
│  └─models 所有数据库的Model
├─config 配置文件
├─docs 文档存放
├─jobs 定时任务
│  └─tasks 
└─web HTTP相关
    └─controllers 所有的控制层都放在这里

二、实战简单MVC框架

2.1项目框架的搭建

先删除之前的代码,创建common这个python文件夹 以及它的2个子文件夹libsmodels

20210718153114 - Python flask实战订餐系统微信小程序-14手写MVC框架

其次,创建config文件夹,在虾米那创建base_etting.pylocal_setting.py以及production_setting.py

20210718153708 - Python flask实战订餐系统微信小程序-14手写MVC框架

添加docs目录,并添加mysql.md文件用于说明数据库的使用

20210718153952 - Python flask实战订餐系统微信小程序-14手写MVC框架

创建jobs文件夹,在那创建tasks文件夹

20210718154141 - Python flask实战订餐系统微信小程序-14手写MVC框架

再创建web目录:

20210718154402 - Python flask实战订餐系统微信小程序-14手写MVC框架

创建application.py等外部文件夹:

20210718154814 - Python flask实战订餐系统微信小程序-14手写MVC框架

以上就完成了项目最基本的代码框架的搭建。

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

运行:

20210719213043 - Python flask实战订餐系统微信小程序-14手写MVC框架

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这个端口访问了:

20210719213641 - Python flask实战订餐系统微信小程序-14手写MVC框架

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

20210719215040 - Python flask实战订餐系统微信小程序-14手写MVC框架

修改环境变量:

windwos下修改

20210719215134 - Python flask实战订餐系统微信小程序-14手写MVC框架

Linux下修改:

export ops_config=local

再次运行:

20210719215308 - Python flask实战订餐系统微信小程序-14手写MVC框架

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文件

20210719220123 - Python flask实战订餐系统微信小程序-14手写MVC框架

# -*- 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 = "/" )

入喉文件引入

20210719220555 - Python flask实战订餐系统微信小程序-14手写MVC框架

访问

20210719221032 - Python flask实战订餐系统微信小程序-14手写MVC框架

转载请注明:虚坏叔叔 » Python flask实战订餐系统微信小程序-14手写MVC框架

喜欢 (3)

您必须 登录 才能发表评论!