python flask web开发实战

2019-07-05 11:00:16 浏览数 (1)

路由: @app.route('/') def index(): return '<h1>hello</h1>'

<int:id>

@app.route('/user/<name>') def user(name): return '<h1>hello</h1>'

-------------------------完整的程序------------------------------- from flask import Flask app = Flask(name) @app.route('/') def index(): return '<h1>Hello World!</h1>' 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 '<p>Your browser is %s</p>' % 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 '<h1>Bad Request</h1>', 400

返回response

from flask import make_response @app.route('/') def index(): response = make_response('<h1>This document carries a cookie!</h1>') 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/<id>') def get_user(id): user = load_user(id) if not user: abort(404) return '<h1>Hello, %s</h1>' % 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() }} <link rel="shortcut icon" href="{{ url_for('static', filename = 'favicon.ico') }}" type="image/x-icon"> <link rel="icon" href="{{ url_for('static', filename = 'favicon.ico') }}" type="image/x-icon"> {% endblock %}

0 人点赞