已经开发了几个flask项目, 是时候总结一下了, 这里涉及到项目源码的组织和源码示例.

=========================
目录结构
=========================    
考虑到项目的扩展性, 采用 blueprint 进行组织. 假设 flaskapp 为根目录, 主要的程序放在 app 包中, 除了后台代码, 在app目录下还有templates/static/子目录. 为了重用, 最好的形式是一个建立 boilerplate 项目.
主要参考文档为:
https://github.com/mitsuhiko/flask/wiki/Large-app-how-to
http://www.realpython.com/blog/python/python-web-applications-with-flask-part-ii-app-creation
http://www.realpython.com/blog/python/rethink-flask-a-simple-todo-list-powered-by-flask-and-rethinkdb/

flaskapp
├── app
│   ├── __init__.py
│   ├── constants.py
│   ├── users[sub_app/module]
│   │   ├── constants.py
│   │   ├── decorators.py
│   │   ├── forms.py
│   │   ├── models.py
│   │   └── views.py
│   ├── tickets[sub_app/module]
│   │   ├── constants.py
│   │   ├── decorators.py
│   │   ├── forms.py
│   │   ├── models.py
│   │   └── views.py
│   ├── templates
│   │   ├── forms
│   │   │   └── macros.html
│   │   ├── base.html      
│   │   ├── index.html  
│   │   ├── base_another.html  
│   │   ├── 500.html (server error page)
│   │   ├── 404.html (not found page)
│   │   ├── method_not_allowed.html
│   │   ├── access_forbidden.html
│   │   ├── users
│   │   │   ├── profile.html  
│   │   │   ├── login.html          
│   │   │   └── register.html
│   │   └── tickets
│   │        ├── create.html          
│   │        └── close.html                                
│   └── static
│        ├── favicon.ico
│        ├── img
│        ├── js
│        │   ├── main.js #our own js code
│        │   └── vendor
│        │        ├── bootstrap.min.js
│        │        └── jquery-1.7.2.min.js
│        └── css
│             ├── layout.less
│             ├── reset.less
│             └── vendor
│                  └── bootstrap.css  
├── flaskapp.db
├── config.py
├── requirements.txt
├── runserver.py
├── shell.py     
├── tests 目录
└── docs 目录

----------------------
项目级的单元
----------------------
runserver.py 用来启动 web server,  从app包中进入flask app对象, 然后直接启动.
      
 
config.py 存储一些db的 connection 配置, 以及Flask SECRET_KEY 等等. 更多的配置项见 http://flask.pocoo.org/docs/config/
    
   
----------------------
应用级别的单元  
----------------------
flaskapp/app/__init__.py, 作为整个app的入口, 做如下工作.
    1.加载flask的config,
    2.[如使用Flask-SQLAlchemy插件]创建 SqlAlchemy 的db 实例.
    3.[如没使用Flask-SQLAlchemy插件]定义3个函数, 分别加上@app.before_request和@app.teardown_request和@app.after_request.  before_request和teardown_request函数非常适合做创建和关闭db connection工作. after_request函数不适合用来关闭db connection, 因为after_request函数在有unhandled exception发生的情况下, 会被跳过.  而teardown 函数总是能保证被调用的.
    4.注册sub app blueprint, 比如users和tickets
    5.设置root url 和favicon.ico 的路由,  
    6.创建login_manager, 比如使用flask-login插件来创建一个login_manager

----------------------
子应用级别的单元,
----------------------    

称为subapp或称为module, 目录采用复数形式
flaskapp/app/users/models.py, 和User相关的表模型
flaskapp/app/users/constants.py, 和User module相关的constant, 比如用户的激活状态, 用户的类型.
flaskapp/app/users/forms.py, 集中所有User module相关的表单类, 比如class LoginForm(Form) 和 class RegisterForm(Form) 类.
flaskapp/app/users/decorators.py, 和User module相关的一些decorator, 比如 requires_login, 供 views.py 使用.
flaskapp/app/users/views.py, 充当url路由角色(Flask是基于MVT模型, 这里的view相当于MVC模型中的Controller). 依据web请求类型和请求的url, 路由到指定的view函数, 在view函数中, 做逻辑处理, 然后, 或展现form, 或跳转到其他url.
        
 
----------------------
templates目录
----------------------
flaskapp/app/templates/base.html, 模板的模板, 根据需要, 可以设置多个base页面
flaskapp/app/templates/forms/macros.html, 定义一些宏, 供form页面调用, 用来渲染form的元素
flaskapp/app/templates/users/login.html, 在flaskapp/app/users/views.py应该有一个同名的view函数

----------------------
static目录
----------------------
flaskapp/app/static/favicon.ico, 16 × 16 pixels and in the ICO format

=========================
源码示例
=========================

------------------------------
runserver.py
------------------------------
runserver.py 用来启动 web server.

# -*- coding: utf-8 -*-
from __future__ import absolute_import from app import app app.run()

------------------------------
config.py
------------------------------
config.py 存储一些db的 connection 配置, 以及Flask SECRET_KEY 等等. 更多的配置项见 http://flask.pocoo.org/docs/config/

# -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
from datetime import timedelta
_basedir = os.path.abspath(os.path.dirname(__file__)) DEBUG = True SECRET_KEY = os.urandom(24)
PERMANENT_SESSION_LIFETIME=timedelta(seconds=24*60*60) CSRF_ENABLED = True
CSRF_SESSION_KEY = SECRET_KEY

------------------------------
app/__init__.py
------------------------------   
flaskapp/app/__init__.py, 作为整个app的入口, 做如下工作.
    1.加载flask的config,
    2.[如使用Flask-SQLAlchemy插件]创建 SqlAlchemy 的db 实例.
   
3.[如没使用Flask-SQLAlchemy插件]定义3个函数,
分别加上@app.before_request和@app.teardown_request和@app.after_request. 
before_request和teardown_request函数非常适合做创建和关闭db connection工作.
after_request函数不适合用来关闭db connection, 因为after_request函数在有unhandled
exception发生的情况下, 会被跳过.  而teardown 函数总是能保证被调用的.
    4.注册sub app blueprint, 比如users和tickets
    5.设置root url 和favicon.ico 的路由,  
    6.创建login_manager, 比如使用flask-login插件来创建一个login_manager

# -*- coding: utf-8 -*-
from __future__ import absolute_import
from flask import Flask, g, render_template, send_from_directory
import os
import os.path
_basedir = os.path.abspath(os.path.dirname(__file__))
configPy=os.path.join(os.path.join( _basedir,os.path.pardir), 'config.py') app = Flask(__name__) # create our application object app.config.from_pyfile(configPy)
#app.debug=True #change some attribute after load configuration flask_sqlalchemy_used=True # 如果使用Flask-SQLAlchemy了
db = SQLAlchemy(app) #create a db (SQLAlchemy) object from our app object login_manager = LoginManager(app) #create a LoginManager Object from our app object
#add our view as the login view to finish configuring the LoginManager
login_manager.login_view = "users.login_view" #register the users module blueprint
from app.users.views import mod as usersModule
app.register_blueprint(usersModule) #register the tickets module blueprint
from app.tickets.views import mod as ticketsModule
app.register_blueprint(ticketsModule) def connect_db(): # 如果没使用Flask-SQLAlchemy
if not flask_sqlalchemy_used:
return sqlite3.connect('/path/to/database.db')
else:
return None @app.before_request
def before_request():
"""Make sure we are connected to the database each request."""
if not flask_sqlalchemy_used:
g.db = connect_db() @app.teardown_request
def teardown_request(response):
"""Closes the database again at the end of the request."""
if not flask_sqlalchemy_used:
g.db.close()
return response #*****************
# controllers
#***************** @app.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(app.root_path, 'static'), 'ico/favicon.ico') @app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404 @app.route("/")
def index():
return render_template('index.html')

------------------------------
app/users/views.py.py
------------------------------

# -*- coding: utf-8 -*-
from __future__ import absolute_import
from flask import Blueprint, render_template, flash, redirect, session, url_for, request, g
from flask.ext.login import login_user, logout_user, login_required
from app import app, db, login_manager
from forms import LoginForm, RegistrationForm
from app.users.models import User mod = Blueprint('users', __name__) #register the users blueprint module @login_manager.user_loader
def load_user(user_id):
return User.query.get(user_id) @mod.route('/login/', methods=('GET', 'POST'))
def login_view():
form = LoginForm(request.form)
if form.validate_on_submit():
user = form.get_user()
login_user(user)
flash("Logged in successfully.")
return redirect(request.args.get("next") or url_for("index"))
return render_template('users/login.html', form=form) @mod.route('/register/', methods=('GET', 'POST'))
def register_view():
form = RegistrationForm(request.form)
if form.validate_on_submit():
user = User()
form.populate_obj(user)
db.session.add(user) #使用SqlAlchemy保存
db.session.commit()
login_user(user)
return redirect(url_for('index'))
return render_template('users/register.html', form=form) @login_required
@mod.route('/logout/')
def logout_view():
logout_user()
return redirect(url_for('index'))

macros.html, 是个jinja2的宏文件, 我们在该文件中可定义一些宏, 供form页面调用, 用来渲染form的元素. 用法是, 在我们的html文件中, 引入这个宏文件即可.
 
用法:
{% from "macros.html" import form_field %}

macros.html内容, 可以自动将form兼容 bootstrap. 内容摘自 https://gist.github.com/rawrgulmuffins/6025599

{% macro form_field(field) -%}
{% set with_label = kwargs.pop('with_label', False) %}
{% set placeholder = '' %}
{% if not with_label %}
{% set placeholder = field.label.text %}
{% endif %}
<div class="control-group {% if field.errors %}error{% endif %}">
{% if with_label %}
<label for="{{ field.id }}" class="control-label">
{{ field.label.text }}{% if field.flags.required %} *{% endif %}:
</label>
{% endif %}
<div class="controls">
{% set class_ = kwargs.pop('class_', '') %}
{% if field.flags.required %}
{% set class_ = class_ + ' required' %}
{% endif %}
{% if field.type == 'BooleanField' %}
<label class="checkbox">
{{ field(class_=class_, **kwargs) }}
{{ field.label.text|safe }}
</label>
{% else %}
{% if field.type in ('TextField', 'TextAreaField', 'PasswordField') %}
{% set class_ = class_ + ' input-xlarge' %}
{% elif field.type == 'FileField' %}
{% set class_ = class_ + ' input-file' %}
{% endif %} {% if field.type == 'SelectField' %}
{{ field(class_=class_, **kwargs) }}
{% else %}
{{ field(class_=class_, placeholder=placeholder, **kwargs) }}
{% endif %} {% endif %}
{% if field.errors %}
<span class="error help-inline">{{ field.errors|join(', ') }}</span>
{% endif %}
{% if field.description %}
<p class="help-block">{{ field.description|safe }}</p>
{% endif %}
</div>
</div>
{%- endmacro %}

flask 项目的开发经验总结的更多相关文章

  1. Python框架 Flask 项目实战教程

    本文目的是为了完成一个项目用到的flask基本知识,例子会逐渐加深.最好对着源码,一步一步走.下载源码,运行pip install -r requirements.txt 建立环境python db_ ...

  2. 通过VM虚拟机安装Ubuntu server部署flask项目

    1. VM安装Ubuntu server 14.04,系统安装完成后,首先安装pip工具方便之后的包安装,此处需先使用 apt-get install update,apt-get install u ...

  3. flask项目开发中,遇到http 413错误

    在flask项目中,上传文件时后台报http 413 Request Entity Too Large 请求体太大错误! 解决的2种方法: 1.在flask配置中设置 MAX_CONTENT_LENG ...

  4. flask项目部署到阿里云 ubuntu16.04

    title: flask项目部署到阿里云 ubuntu16.04 date: 2018.3.6 项目地址: 我的博客 部署思路参考: Flask Web开发>的个人部署版本,包含学习笔记. 开始 ...

  5. 部署Flask项目到腾讯云服务器CentOS7

    部署Flask项目到腾讯云服务器CentOS7 安装git yum install git 安装依赖包 支持SSL传输协议 解压功能 C语言解析XML文档的 安装gdbm数据库 实现自动补全功能 sq ...

  6. pycharm创建Flask项目,jinja自动补全,flask智能提示

    pycharm创建Flask项目,jinja自动补全,flask智能提示 之前一直都是用在idea里创建空项目然后导入,之后就没有各种的智能提示,在选择文类,选择模板之类的地方就会很麻烦. 步骤1:用 ...

  7. flask 项目基本框架的搭建

    综合案例:学生成绩管理项目搭建 一 新建项目目录students,并创建虚拟环境 mkvirtualenv students 二 安装开发中使用的依赖模块 pip install flask==0.1 ...

  8. windows环境隐藏命令行窗口运行Flask项目

    Linux下可以使用nohub来使Flask项目在后台运行,而windows环境下没有nohub命令,如何让Flask项目在windows中在后台运行而不显示命令行窗口呢? 1.写一个.bat脚本来启 ...

  9. nginx + gunicorn + flask项目发布

    程序安装(linux mint) gunicorn安装:pip install gunicorn nginx安装:sudo apt-get install nginx 配置 nginx默认配置信息在/ ...

随机推荐

  1. Jenkins实现生产环境部署文件的回滚操作(Windows)

    由于dotnet项目的生产环境环境部署工具比较少,所以我使用jenkins作为生产环境的自动化部署工具. 既然有回滚操作,那么就会有部署操作:要实现回滚,先要实现部署的操作,我在jenkins搭建了一 ...

  2. PHP解释器引擎执行流程 - [ PHP内核学习 ]

    catalogue . SAPI接口 . PHP CLI模式解释执行脚本流程 . PHP Zend Complile/Execute函数接口化(Hook Call架构基础) 1. SAPI接口 PHP ...

  3. 使用 BASH 作为 CGI 进行 HTTP 文件上传

    憋半天憋出这么点代码来,暂时凑合可以用...需要手动删除文件末尾的分隔符,还有一个windows 换行: #!/bin/bash newline="" while true; do ...

  4. sed命令给文本文件的每行的行首或者行尾添加文字

    在每行的头添加字符,比如"HEAD",命令如下: sed 's/^/HEAD&/g' test.file 在每行的行尾添加字符,比如“TAIL”,命令如下: sed 's/ ...

  5. type parameters of <T>T cannot be determined; no unique maximal instance exists for type variable T with upper bounds int,java.lang.Object

    今天在进行代码检查的时候出现下面的异常: type parameters of <T>T cannot be determined; no unique maximal instance ...

  6. 【Alpha阶段】第三次Scrum例会

    会议信息 时间:2016.10.19 21:00 时长:0.5h 地点:大运村1号公寓5楼楼道 类型:日常Scrum会议 个人任务报告 姓名 今日已完成Issue 明日计划Issue 今日已做事务 工 ...

  7. 《JavaScript权威指南》学习笔记 第六天 开始学习DOM了。

    昨天学习了window对象的一些方法.window对象主要是针对当前视窗的操作.window对象提供了一些列API来帮助我们了解当前窗口的信息.例如history对象可以让我们获取浏览历史.nvaig ...

  8. PHP常用函数备用

    刚学习php的时候,我也为记忆php函数苦恼不已.认为干嘛记忆这么枯燥无味的东西呢?用的时候查一下手册不就行了吗?但是当时因为身在辅导机构,还是记忆了一大堆自己并不感兴趣的函数. 由此就想起来,小的时 ...

  9. Hibernate Hql 总结

    1.from子句 Hibernate中最简单的查询语句的形式如下: from eg.Cat该子句简单的返回eg.Cat类的所有实例. 通常我们不需要使用类的全限定名, 因为 auto-import(自 ...

  10. 在Android上实现使用Facebook登录(基于Facebook SDK 3.5)

    准备工作: 1.       Facebook帐号,国内开发者需要一个vpn帐号(网页可以浏览,手机可以访问) 2.       使用Facebook的SDK做应用需要一个Key Hashes值. 2 ...