flask web開發:主程式從單檔案到多檔案的轉化——第三步

flask web開發:主程式從單檔案到多檔案的轉化——第三步
第三步:這一步主要是將程式不同功能的程式碼進行拆分,本例將拆分出檢視物件、錯誤檢視物件、郵件物件、資料庫模型物件、表單物件和建立app的物件。
這裡分別對應檔案為:
物件
檔案
檢視
views.py
錯誤檢視
errors.py
郵件
emails.py
資料庫模型
models.py
表單
forms.py
建立app
__init__.py

切割如此多的檔案出來,就得保證多個檔案之間的聯絡必須緊密,我們將會一步步實現分割:

1,分割表單
forms.py檔案內容:
from flask.ext.wtf import Form
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
class NameForm(Form):
name = StringField('What is your name?', validators=[DataRequired()])
submit = SubmitField('Submit')
此時__init__.py檔案內容應為:

from flask import Flask, render_template,session,redirect,url_for
from flask.ext.bootstrap import Bootstrap
from flask.ext.mail import Mail,Message
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from config import config
from .forms import NameForm
bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()
class Role(db.Model):
__tablename__ = 'roles'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
users = db.relationship('User', backref='role', lazy='dynamic')
def __repr__(self):
return '<Role %r>' % self.name
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), unique=True, index=True)
role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
def __repr__(self):
return '<User %r>' % self.username
def send_email(app,to, subject, template, **kwargs):
msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX']   ' '   subject,
sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to])
msg.body = render_template(template   '.txt', **kwargs)
msg.html = render_template(template   '.html', **kwargs)
mail.send(msg)
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bootstrap.init_app(app)
mail.init_app(app)
moment.init_app(app)
db.init_app(app)
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@app.errorhandler(500)
def internal_server_error(e):
return render_template('500.html'), 500
@app.route('/', methods=['GET', 'POST'])
def index():
form = NameForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.name.data).first()
if user is None:
user = User(username=form.name.data)
db.session.add(user)
session['known'] = False
if app.config['FLASKY_ADMIN']:
send_email(app,app.config['FLASKY_ADMIN'], 'New User',
'mail/new_user', user=user)
else:
session['known'] = True
session['name'] = form.name.data
return redirect(url_for('index'))
return render_template('index.html', form=form, name=session.get('name'),
known=session.get('known', False))
return app
執行程式,結果正常執行。

2,分割資料庫模型
models.py檔案內容:
from app import db
class Role(db.Model):
__tablename__ = 'roles'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
users = db.relationship('User', backref='role', lazy='dynamic')
def __repr__(self):
return '<Role %r>' % self.name
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), unique=True, index=True)
role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
def __repr__(self):
return '<User %r>' % self.username

此時__init__.py檔案內容應為:
from flask import Flask, render_template,session,redirect,url_for
from flask.ext.bootstrap import Bootstrap
from flask.ext.mail import Mail,Message
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from config import config
from .forms import NameForm
bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()
from .models import User,Role  #這裡放在db生成之後,是因為mudules檔案需要反過來匯入本檔案,這麼做避免了死迴圈
def send_email(app,to, subject, template, **kwargs):
msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX']   ' '   subject,
sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to])
msg.body = render_template(template   '.txt', **kwargs)
msg.html = render_template(template   '.html', **kwargs)
mail.send(msg)
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bootstrap.init_app(app)
mail.init_app(app)
moment.init_app(app)
db.init_app(app)
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@app.errorhandler(500)
def internal_server_error(e):
return render_template('500.html'), 500
@app.route('/', methods=['GET', 'POST'])
def index():
form = NameForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.name.data).first()
if user is None:
user = User(username=form.name.data)
db.session.add(user)
session['known'] = False
if app.config['FLASKY_ADMIN']:
send_email(app,app.config['FLASKY_ADMIN'], 'New User',
'mail/new_user', user=user)
else:
session['known'] = True
session['name'] = form.name.data
return redirect(url_for('index'))
return render_template('index.html', form=form, name=session.get('name'),
known=session.get('known', False))
return app
執行程式,結果正常執行。

3,分割郵件
emails.py檔案內容:
from flask import render_template
from flask.ext.mail import Message
from . import mail
def send_email(app,to, subject, template, **kwargs):
msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX']   ' '   subject,
sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to])
msg.body = render_template(template   '.txt', **kwargs)
msg.html = render_template(template   '.html', **kwargs)
mail.send(msg)
此時__init__.py檔案內容:
from flask import Flask, render_template,session,redirect,url_for
from flask.ext.bootstrap import Bootstrap
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from config import config
from .forms import NameForm
bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()
from .models import User,Role
from .emails import send_email #這裡放在mail生成之後,是因為emails檔案需要反過來匯入本檔案,這麼做避免了死迴圈
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bootstrap.init_app(app)
mail.init_app(app)
moment.init_app(app)
db.init_app(app)
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@app.errorhandler(500)
def internal_server_error(e):
return render_template('500.html'), 500
@app.route('/', methods=['GET', 'POST'])
def index():
form = NameForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.name.data).first()
if user is None:
user = User(username=form.name.data)
db.session.add(user)
session['known'] = False
if app.config['FLASKY_ADMIN']:
send_email(app,app.config['FLASKY_ADMIN'], 'New User',
'mail/new_user', user=user)
else:
session['known'] = True
session['name'] = form.name.data
return redirect(url_for('index'))
return render_template('index.html', form=form, name=session.get('name'),
known=session.get('known', False))
return app
執行程式,結果正常執行。

4,分割檢視
views.py檔案內容:
from datetime import datetime
from flask import render_template, session, redirect, url_for
from forms import NameForm
from . import db
from models import User
from .emails import send_email
def  view(app):
@app.route('/', methods=['GET', 'POST'])
def index():
form = NameForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.name.data).first()
if user is None:
user = User(username=form.name.data)
db.session.add(user)
session['known'] = False
if app.config['FLASKY_ADMIN']:
send_email(app,app.config['FLASKY_ADMIN'], 'New User',
'mail/new_user', user=user)
else:
session['known'] = True
session['name'] = form.name.data
return redirect(url_for('.index'))
return render_template('index.html',form=form, name=session.get('name'),
known=session.get('known', False),current_time=datetime.utcnow())
return app
此時__init__.py檔案內容:
from flask import Flask, render_template,session,redirect,url_for
from flask.ext.bootstrap import Bootstrap
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from config import config
from .forms import NameForm
bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()
from .models import User,Role
from .views import view
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bootstrap.init_app(app)
mail.init_app(app)
moment.init_app(app)
db.init_app(app)
app = view(app)
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@app.errorhandler(500)
def internal_server_error(e):
return render_template('500.html'), 500
return app
執行結果正常。

5,分割錯誤檢視
errors.py檔案內容:
from flask import render_template
def  error(app):
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@app.errorhandler(500)
def internal_server_error(e):
return render_template('500.html'), 500
return app
此時__init__.py檔案內容:
from flask import Flask, render_template,session,redirect,url_for
from flask.ext.bootstrap import Bootstrap
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from config import config
from .forms import NameForm
bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()
from .models import User,Role
from .views import view
from .errors import error
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bootstrap.init_app(app)
mail.init_app(app)
moment.init_app(app)
db.init_app(app)
app = view(app)
app = error(app)
return app
分割到此結束,現在進行一次測試:
執行:$ python manage.py  runserver –host 0.0.0.0 -r -d
瀏覽器輸入URL後顯示:
輸入三牛,提交後顯示:
以及收到郵件:
顯然是成功了!