本文共 2124 字,大约阅读时间需要 7 分钟。
view function会自动转换返回对象类型为response
1 如果返回值为string,那么返回值作为参数创建一个response2 如果返回值为tuple,例如 (response, status, headers) or (response, headers)make_response()会创建一个response
除了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 abovedsession.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的信息还是存在的。通过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中对比分析。使用logger来记录
例如:
app.logger.debug('A value for debugging')app.logger.warning('A warning occurred (%d apples)', 42)app.logger.error('An error occurred')例如:
Flask-SQLAlchemy转载于:https://blog.51cto.com/12408798/2376669