Skip to content

Flask 用法

简单模板

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from flask import Flask, session, redirect, url_for, escape, request

app=Flask(__name__)

@app.errorhandler(404)
def page_not_found(e):
    template = '''{%% extends "layout.html" %%}
{%% block body %%}
    <div class="center-content error">
        <h1>Oops! That page doesn't exist.</h1>
        <h3>%s</h3>
    </div>
{%% endblock %%}
''' % (request.url)
    return render_template_string(template), 404

@app.route('/nodes/get', methods=['GET'])
def get_nodes():
    request.args.get('aaa')
    return jsonify(response), 200

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=8888)

获取参数

  • GET:

    1
    request.args.get('aaa')
    

  • POST:

    1
        request.form["key"]
    

  • Session:

    1
    session["key"]
    

  • Cookie

    1
    2
    username = request.cookies.get('username')
    resp.set_cookie('username', 'the username')
    

路径参数

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
```python
@app.route('/user/<username>')
def show_user_profile(username):
    # show the user profile for that user
    return 'User %s' % escape(username)

@app.route('/post/<int:post_id>')
def show_post(post_id):
    # show the post with the given id, the id is an integer
    return 'Post %d' % post_id

@app.route('/path/<path:subpath>')
def show_subpath(subpath):
    # show the subpath after /path/
    return 'Subpath %s' % escape(subpath)
```

跳转

1
2
3
4
5
6
7
@app.route('/')
def index():
    return redirect(url_for('login'))

@app.route('/')
def hello():
    return redirect("https://www.exampleURL.com", code = 302)