一 flask介绍 三

13 About Responses

view function会自动转换返回对象类型为response
1 如果返回值为string,那么返回值作为参数创建一个response
2 如果返回值为tuple,例如 (response, status, headers) or (response, headers)

make_response()会创建一个response

14 Sessions

除了request可以store information,其包括由一个请求到下一个。另外一个是object session。
app.secret_key = b'_5#y2L"F4Q8z\n\xec][/'

@app.route('/')
def index():
if 'username' in session:
return 'logined in as %s' % escape(session['username'])
return 'you are not logged in'

@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
session['username'] = request.form['username']
return redirect(url_for('index'))
else:
return '''
<form method="post">
<p><input type=text name=username>
<p><input type=submit value=Login>
</form>
'''
@app.route('/logout')
def logout():
if session['username']: #direct run session exception,KeyError: 'username'
#if not exist,return None,which not need if aboved
session.pop('username',None)
return redirect(url_for('index'))

概念:
序列是Python的基本数据结构,每个元素指定一个数字,或者说index,从0开始。
可以对序列index, 切片,加,乘,迭代 for x in (1,2,3),检查成员3 in (1,2,3)。
常见的序列有list,tuple。 list实现了stack,queue操作。tuple没有stack操作。
dictionary实现了stack操作。

note:
sessions保存的信息,在server重启后,browser连接server,sessions的信息还是存在的。

15 Message Flashing

通过flash函数,user在view中flash message
通过 get_flashed_messages()函数,user在template中获取messages。
这样用户就能获取更多的信息feedback。

flash('logined successfully!')

{% with messages = get_flashed_messages() %}
{% if messages %}
<li>{{messages}}</li>
{% endif%}
{% endwith%}

输出:
['logined successfully!']

案例
return render_template('index.html',user=escape(session['username']))
return render_template('index.html',user='')
报错:
return render_template('index.html',user='')
^ SyntaxError: invalid syntax
原因:
return render_template('index.html',user=escape(session['username'])) 少一个括号
分析方法:
找一个对的,粘贴到txt中对比分析。

16 Logging

使用logger来记录

例如:
app.logger.debug('A value for debugging')
app.logger.warning('A warning occurred (%d apples)', 42)
app.logger.error('An error occurred')

17 Hooking in WSGI Middlewares

18 Using Flask Extensions

例如:
Flask-SQLAlchemy

19 Deploying to a Web Server

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章