python包学习——flask

基础

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

@app.route('/user/')
def show_user_profile(username):
    # show the user profile for that user
    return 'User %s' % username

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

if __name__ == '__main__':
    app.run()

构造 URL

>>> from flask import Flask, url_for
>>> app = Flask(__name__)
>>> @app.route('/')
... def index(): pass
...
>>> @app.route('/login')
... def login(): pass
...
>>> @app.route('/user/')
... def profile(username): pass
...
>>> with app.test_request_context():
...  print url_for('index')
...  print url_for('login')
...  print url_for('login', next='/')
...  print url_for('profile', username='John Doe')

HTTP方法

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        do_the_login()
    else:
        show_the_login_form()

模板渲染

from flask import render_template

@app.route('/hello/')
@app.route('/hello/')
def hello(name=None):
    return render_template('hello.html', name=name)
# Flask 会在 templates 文件夹里寻找模板
# /templates/hello.html

Hello from Flask
{% if name %}
  

Hello {{ name }}!

{% else %}

Hello World!

{% endif %}

你可能感兴趣的:(python包学习——flask)