run.py
#导入falskapp实例,调用run方法来启动服务器
from app import flaskapp
flaskapp.run(debug=True)
views.py
#view是来响应来网页的浏览器的请求处理器。在flask视图是编写成python函数的,每一个函数可以映射一个或多个URL。
from app import flaskapp
from flask import render_template,flash,redirect
from .forms import LoginForm
#render_template 调用了 Jinja2 模板引擎,Jinja2 模板引擎是 Flask 框架的一部分
@flaskapp.route(‘/‘) #route装饰器
@flaskapp.route(‘/index‘)
def index():
user={‘nickname‘:‘Miguel‘}
posts=[{
‘author‘:{‘nickname‘:‘John‘}
‘body‘:‘Beautyful day in Portland‘
},
{ ‘author‘:{‘nickname‘:‘Susan‘}
‘body‘:‘The Avengers movie was so cool!‘
}
]
return render_template("index.html",
title=‘Home‘,
user=user)
#渲染表单的函数
@flaskapp.route(‘/login‘,methods=[‘GET‘,‘POST‘])
def login():
form=LoginForm()
if form.validate_on_submit():
flash(‘Login requested for OpenID="‘+ from.opendid.data+‘",remember_me=‘+str(form.remember_me.data))
return redirect(‘/index‘)
return render_template(‘login.html‘,
title=‘Sign In‘,
form=form)
config.py
#CSRF_ENABLED 配置是为了激活 跨站点请求伪造 保护。
#SECRET_KEY:CSRF_ENABLED激活后,建立一个加密的令牌,用于验证表单。
CRSF_ENABLED=True
SECRET_KEY=‘you-will-never-guess‘
OPENID_PROVIDERS=[{‘name‘:‘Google‘,‘url‘:‘https://www.google.com/account/o8/id‘},
{‘name‘:‘Yahoo‘,‘url‘:‘https://me.yahoo.com‘},
{‘name‘:‘AOL‘,‘url‘:‘https://www.google.com/account/o8/id‘},
{‘name‘:‘Google‘,‘url‘:‘https://www.google.com/account/o8/id‘}]
__init__.py
from flask import Flask
flaskapp =Flask(__name__)
#读取配置
flaskapp.config.from_object(‘config‘)
from app import views
form.py
from flask.ext.wtf import From
from wtforms import StringField,BooleanField
from wtforms.validators import DataRequired
class LoginForm(From):
openid=StringField(‘opendid‘,validators=[DataRequired()])
remember_me=BooleanField(‘remember_me‘,defult=False)
index.thml
{% extends "base.html" %}
{% block content%}
<h1> Hello,{{user.nickname}}!</h1>
{% for post in posts%}
<p>{{post.author.nickname}} says: <b>{{post,body}}</b></p>
{% endfor %}
{% endblock %}
base.html
<html>
<head>
<%if title %>
<title>{{title}} - falskblog</title>
<%else %>
<title>Welcome to flaskblog</title>
<%end if %>
</head>
<body>
<div>Microblog: <a herf="/index" >Home</a></div>
<hr>
{% with messages=get_flashed_messages %}
{% if messages % }
<ul>
{%for message in messages %}
<li>{{message}}</li>
{% endfor %}
</ul>
{% endif %}
{% end with %}
{ block content %}
{% endblock %}
</body>
</html>
login.html
<!-- extend from base layout -->
{% extends "base.html " %}
{% block content%}
<h1>Sign In</h1>
<form action="" method="post" name="login">
{{form.hidden_tag()}}
<p>
Please enter your OpenID:</br>
{{form.openid(size=80)}}<br>
{for error in form.openid.errors %}
<span style="color:red;">[{{error}}]</span>
{% endfor %}
</p>
<p>{{form.remember_me}} Remember Me</p>
<p>i<input="submit" value="Sign In"></p>
</form>