Flask基础

例子

https://github.com/phoenix13suns/myFlask

介绍

http://flask.pocoo.org/docs/0.10/

The Flask Mega-Tutorial

1. project结构

static folder: for css, javascript, image

templates folder: for Jinja2 templates

https://exploreflask.com/organizing.html

app.py
config.py
requirements.txt
static/
templates/

2. hello world example

from flask import Flask

app = Flask(__name__)


@app.route('/')
def hello():
    return "hello!"


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

3. routing with varibale in path

https://exploreflask.com/views.html#url-converters

@app.route('/user/id/<int:user_id>')
def profile(user_id):
    pass

4. handle both POST and GET

@app.route('/rest/<int:restaurant_id>/new/', methods=['GET', 'POST'])
def newMenuItem(restaurant_id):
    if request.method == 'POST':
        name = request.form['newItemName']
        add_item(name, restaurant_id)
        return redirect(url_for('restaurantMenu', restaurant_id=restaurant_id))
    else:
        rest = get_restaurants_by_id(restaurant_id)
        return render_template('newmenuitem.html', rest=rest)

5. Jinjia2 template example

{{}} if for expression

{% %}is for statement like if, for, with

https://exploreflask.com/templates.html#a-quick-primer-on-jinja

<body>

{% for i in rests %}
<div>
    <p>{{i.id}}</p>

    <p>{{i.name}}</p>


    <a href='{{url_for("restaurantMenu", restaurant_id = i.id) }}'>Detail</a>
    <br><br>

</div>
{% endfor %}
</body>
原文地址:https://www.cnblogs.com/phoenix13suns/p/4519730.html