最近比较忙
快速玩Flask框架,为微博做些准备
part 1 python程序
from flask importFlask, render_template, session, redirect, url_for, flash
from flask_bootstrap importBootstrap
from flask_moment importMoment
from datetime import datetime
from flask_wtf importForm
from wtforms importStringField,SubmitField
from wtforms.validators importRequired
from flask_sqlalchemy importSQLAlchemy
from flask_script importManager
import os
basedir = os.path.abspath(os.path.dirname(__file__))
app =Flask(__name__)
#wtf表单验证
app.config['SECRET_KEY']='hard to guess string'
#数据库URL
app.config['SQLALCHEMY_DATABASE_URI']= \
'sqlite:///'+ os.path.join(basedir,'data.sqlite')
#每次请求结束后自动提交数据变动
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN']=True
bootstrap =Bootstrap(app)
moment =Moment(app)
db =SQLAlchemy(app)
manager =Manager(app)
#wtf表单类
classNameForm(Form):
name =StringField('What is your name?', validators=[Required()])
submit =SubmitField('Submit')
#数据库中的table类
classRole(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
classUser(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
#主页
@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 isNone:
user =User(username=form.name.data)
db.session.add(user)
session['known']=False
else:
session['known']=True
session['name']= form.name.data
form.name.data =''
return redirect(url_for('index'))
return render_template('user.html', form=form, name=session.get('name'), known=session.get('known',False),
current_time=datetime.utcnow())
#404页
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'),404
#500页
@app.errorhandler(500)
def internal_server_error(e):
return render_template('500.html'),500
#manager.run() 用于是服务器在命令行运行
if __name__ =='__main__':
app.run(debug=True)
# manager.run()
part 2 基模板
主页面:
<!-- 基于bootstrap/base.html的基模板 默认有导航栏 page——content可重写-->
{% extends "bootstrap/base.html" %}
<!-- 导入moment.js -->
{% block scripts %}
{{ super() }}
{{ moment.include_moment() }}
{% endblock %}
{% block title %}Flasky{% endblock %}
{% block head %}
{{ super() }}
<linkrel="shortcut icon"href="{{ url_for('static', filename = 'favicon.ico') }}"
type="image/x-icon">
<linkrel="icon"href="{{ url_for('static', filename = 'favicon.ico') }}"
type="image/x-icon">
{% endblock %}
{% block navbar %}
<divclass="navbar navbar-inverse"role="navigation">
<divclass="container">
<divclass="navbar-header">
<buttontype="button"class="navbar-toggle"
data-toggle="collapse"data-target=".navbar-collapse">
<spanclass="sr-only">Toggle navigation</span>
<spanclass="icon-bar"></span>
<spanclass="icon-bar"></span>
<spanclass="icon-bar"></span>
</button>
<aclass="navbar-brand"href="/">Flasky</a>
</div>
<divclass="navbar-collapse collapse">
<ulclass="nav navbar-nav">
<li><ahref="/">Home</a></li>
</ul>
</div>
</div>
</div>
{% endblock %}
{% block content %}
<!-- 弹出警告信息-->
<divclass="container">
{% for message in get_flashed_messages() %}
<divclass="alert alert-warning">
<buttontype="button"class="close"data-dismiss="alert">×</button>
{{ message }}
</div>
{% endfor %}
{% block page_content %}{% endblock %}
</div>
{% endblock %}
自定义错误页面:
<!DOCTYPE html>
{% extends "base.html" %}
{% block title %}Flasky - Page Not Found{% endblock %}
{% block page_content %}
<divclass="page-header">
<h1>Not Found</h1>
</div>
{% endblock %}
作者:苏徽.W
出处:http://www.cnblogs.com/perfe/
本文版权归作者和博客园共有,欢迎转载,希望大家能够多多评论交流哦。