Flask代码结构总结

来源:互联网 发布:包天下网络怎么赚钱 编辑:程序博客网 时间:2024/05/29 18:04

1.     代码结构

1.1 最简单的(没有数据库)

`-- app

   |-- static        #用来放CSS,js之类的文件

`-- templates     #用来放HTML格式的文件,可以在里面再创建子文件夹

run.py          #程序主入口,视图函数都写在这里

 备注:

Flask默认使用static目录存放静态资源,这是可以更改的,请在:

app = Flask(__name__)

中为Flask多加几个参数值,如:

app=Flask(__name__,static_url_path="/Users/test")

此时查看

>>> app.static_url_path
'/Users/test'

这些参数请参考__doc__

from flask import Flaskprint Flask.__doc__

1.2 稍复杂点的(没有数据库)

|-- app

|  |-- __init__.py    #将app这个文件夹模块化

|  |-- static

|  `-- templates

`-- run.py             #程序主入口

 

1.3 大型项目(用到了blueprint,有数据库)

|-- app

|  |-- __init__.py

 

|  |-- auth     #蓝图名为auth

|  |   |-- __init__.py   #模块化

|  |   |-- forms.py    #定义页面展示的表格,在views.py里import进去,在对应的视图函数里创建实例,传给html,进行前端展示

|  |   |-- views.py    #视图函数app.route()

 

|  |-- main    #蓝图名为main

|  |   |-- __init__.py

|   |   |-- errors.py    #如404这样的错误视图函数,在该模块的__init里面导入

|  |   |-- forms.py

|  |   |-- views.py

|  |-- models.py    #定义数据库的每个table格式、关系

|  |-- static

|  |   `-- styles.css

|  `-- templates

|      |-- _macros.html

|      |-- auth     #蓝图auth对应的相关html文件

|      |   |-- forgetPwd.html

|      |   |-- login.html

|      |-- base.html

|      |-- index.html

|-- config.py    #配置文件

|-- data.sqlite   #数据库文件

|-- migrations     #数据库迁移自动生成

|  |-- README

|  |-- alembic.ini

|  |-- env.py

|  |-- script.py.mako

|  `-- versions

|-- run.py     #程序主入口

`-- test       #用于测试

   `-- test_user_model.py

 

2.     蓝图blueprint

官方文档:http://docs.jinkan.org/docs/flask/blueprints.html

使用目的:将代码拆分模块化,便于多人合作coding。

如上1.3的代码结构,将代码拆成了auth和main。auth模块主要负责用户登陆登出等权限问题,main模块负责index等主要页面功能。

蓝图用法(auth模块举例):

app/auth/__init__.py

from flask import Blueprint    #导入Blueprint

auth=Blueprint('auth',__name__)    #创建蓝图

 

app/__init__.py

from .auth import auth    #从auth模块导入auth

app.register_blueprint(auth,url_prefix='/auth')    #注册蓝图,并注明该蓝图前缀

 

app/auth/views.py    #模块auth中的视图函数

from . import auth

@auth.route('/login',methods=['GET','POST'])   #使用蓝图,auth前缀,各模块之间相互独立

def login():

   form=LoginForm()