python flask web开发实战

路由:
@app.route('/')
def index():
return '

hello

'

@app.route('/user/')
def user(name):
return '

hello

'

-------------------------完整的程序-------------------------------
from flask import Flask
app = Flask(name)
@app.route('/')
def index():
return '

Hello World!

'
if name == 'main':
app.run(debug=True)


request.headers.get('User-Agent')
获取request对象
from flask import request
@app.route('/')
def index():
user_agent = request.headers.get('User-Agent')
return '

Your browser is %s

' % user_agent
//
from flask import session
from flask import current_app


钩子:
before_first_request
before_request
after_request
teardown_request


返回400状态码

@app.route('/')
def index():
return '

Bad Request

', 400

返回response

from flask import make_response
@app.route('/')
def index():
response = make_response('

This document carries a cookie!

')
response.set_cookie('answer', '42')
return response

make_response

response


重定向

from flask import redirect
@app.route('/')
def index():
return redirect('http://www.baidu.com')


返回404

from flask import abort
@app.route('/user/')
def get_user(id):
user = load_user(id)
if not user:
abort(404)
return '

Hello, %s

' % user.name


用flask-script 启动

from flask.ext.script import Manager
manager = Manager(app)

...

if name == 'main':
manager.run()
启动:python hello.py runserver --host 0.0.0.0
参数:-t host,-p port,--threaded,--processes xx,-d --no-debug


自定义错误页面
@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


动态链接:

url_for('user', name='john', _external=True)
url_for('index', page=2)
url_for('static', filename='css/styles.css', _external=True)


base.html 定义收藏夹图标

{% block head %}
{{ super() }}
type="image/x-icon">
type="image/x-icon">
{% endblock %}


你可能感兴趣的:(python flask web开发实战)