flask

flask基本

一个示例:

#conding:utf8
from flask import Flask

app = Flask('todo-list')
app.debug = True

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

if __name__ == "__main__":
app.run(host='0.0.0.0',port=8011)

模板渲染

#conding:utf8
from flask import Flask, render_template

app = Flask('todo-list')
app.debug = True

@app.route('/')
def hello():
return render_template('hello.html')

if __name__ == "__main__":
app.run(host='0.0.0.0',port=8011)
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<H1>Welcome,Jim</H1>
<p>this is my first page</p>
</body>
</html>

变量

URL参数

from flask import Flask
app = Flask(__name__)

@app.route('/user/<name>')
def user(name):
return '<h1>Hello, {0}!</h1>'.format(name)

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

模板渲染

from flask import Flask, render_template
app = Flask(__name__)


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

模板渲染列表

├── templates
│   └── index.html
└── weather.py


# 模板中元素的渲染列表
from flask import Flask, render_template
app = Flask(__name__)


@app.route('/')
def index():
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December']
return render_template('index.html', city='Portland, OR', months=months)
<h1>Weather Averages</h1>
<h2>{{ city }}</h2>
<hr>
<table>
<tr>
<th>Month</th>
<th>Min</th>
<th>Max</th>
<th>Rainfall</th>
</tr>
{% for month in months %}
<tr>
<td>{{ month }}</td>
<td></td>
<td></td>
<td></td>
</tr>
{% endfor %}
</table>

渲染数据结构 for

#coding:utf-8

from flask import Flask, render_template
app = Flask(__name__)



@app.route('/')
def index():
city = u'北京'
months = ['1', '2', '3', '4','5', '6', '7', '8', '9', '10', '11', '12']
weather = {
'1': {'min': 38, 'max': 47, 'rain': 6.14},
'2': {'min': 38, 'max': 51, 'rain': 4.79},
'3': {'min': 41, 'max': 56, 'rain': 4.5},
'4': {'min': 44, 'max': 61, 'rain': 3.4},
'5': {'min': 49, 'max': 67, 'rain': 2.55},
'6': {'min': 53, 'max': 73, 'rain': 1.69},
'7': {'min': 57, 'max': 80, 'rain': 0.59},
'8': {'min': 58, 'max': 80, 'rain': 0.71},
'9': {'min': 54, 'max': 75, 'rain': 1.54},
'10': {'min': 48, 'max': 63, 'rain': 3.42},
'11': {'min': 41, 'max': 52, 'rain': 6.74},
'12': {'min': 36, 'max': 45, 'rain': 6.94}
}
return render_template('index.html', city=city, months=months,weather=weather)

if __name__ == '__main__':
app.run(debug=True)
<!DOCTYPE html>
<html>
<head>
<title>sddsddd</title>
<meta charset="utf-8">
</head>
<body>
<h1>天气平均值</h1>
<h2>{{city}}</h2>
<table border="1px">
<tr>
<th>月份</th>
<th>最大</th>
<th>最小</th>
<th>平均值</th>
</tr>
{% for month in months %}
<tr>
<td>{{ month }}</td>
<td>{{weather[month]['max']}}</td>
<td>{{weather[month]['min']}}</td>
<td>{{weather[month]['rain']}}</td>
</tr>
{% endfor%}
</table>
</body>
</html>

模板中使用条件判断 if

#coding:utf-8

from flask import Flask, render_template
app = Flask(__name__)



@app.route('/')
def index():
city = u'北京'
months = ['1', '2', '3', '4','5', '6', '7', '8', '9', '10', '11', '12']
weather = {
'1': {'min': 38, 'max': 47, 'rain': 6.14},
'2': {'min': 38, 'max': 51, 'rain': 4.79},
'3': {'min': 41, 'max': 56, 'rain': 4.5},
'4': {'min': 44, 'max': 61, 'rain': 3.4},
'5': {'min': 49, 'max': 67, 'rain': 2.55},
'6': {'min': 53, 'max': 73, 'rain': 1.69},
'7': {'min': 57, 'max': 80, 'rain': 0.59},
'8': {'min': 58, 'max': 80, 'rain': 0.71},
'9': {'min': 54, 'max': 75, 'rain': 1.54},
'10': {'min': 48, 'max': 63, 'rain': 3.42},
'11': {'min': 41, 'max': 52, 'rain': 6.74},
'12': {'min': 36, 'max': 45, 'rain': 6.94}
}
highlight = {'min': 40, 'max': 80, 'rain': 5}

return render_template('index.html', city=city, months=months,weather=weather,
highlight=highlight)

if __name__ == '__main__':
app.run(debug=True)
<!DOCTYPE html>
<html>
<head>
<title>sddsddd</title>
<meta charset="utf-8">
</head>
<body>
<h1>天气平均值</h1>
<h2>{{city}}</h2>
<table border="1px">
<tr>
<th>月份</th>
<th>最大</th>
<th>最小</th>
<th>平均值</th>
</tr>
{% for month in months %}
<tr>
<td>{{ month }}</td>
<td>
<!-- 如果 每个月的值满足表达式 小于等于 则对其加粗显示 -->
{% set hl = weather[month]['min'] <= highlight['min'] %}
{% if hl %}<b>{% endif %}
{{ weather[month]['min'] }}
{% if hl %}</b>{% endif %}
</td>
<td>
{% set hl = weather[month]['max'] >= highlight['max'] %}
{% if hl %}<b>{% endif %}
{{ weather[month]['max'] }}
{% if hl %}</b>{% endif %}
</td>
<td>
{% set hl = weather[month]['rain'] >= highlight['rain'] %}
{% if hl %}<b>{% endif %}
{{ weather[month]['rain'] }}
{% if hl %}</b>{% endif %}
</td>
</tr>
{% endfor%}
</table>

</body>
</html>

使用模板宏

相当于py中的函数,函数再调用函数减少代码冗余量

#coding:utf-8

from flask import Flask, render_template
app = Flask(__name__)



@app.route('/')
def index():
city = u'北京'
months = ['1', '2', '3', '4','5', '6', '7', '8', '9', '10', '11', '12']
weather = {
'1': {'min': 38, 'max': 47, 'rain': 6.14},
'2': {'min': 38, 'max': 51, 'rain': 4.79},
'3': {'min': 41, 'max': 56, 'rain': 4.5},
'4': {'min': 44, 'max': 61, 'rain': 3.4},
'5': {'min': 49, 'max': 67, 'rain': 2.55},
'6': {'min': 53, 'max': 73, 'rain': 1.69},
'7': {'min': 57, 'max': 80, 'rain': 0.59},
'8': {'min': 58, 'max': 80, 'rain': 0.71},
'9': {'min': 54, 'max': 75, 'rain': 1.54},
'10': {'min': 48, 'max': 63, 'rain': 3.42},
'11': {'min': 41, 'max': 52, 'rain': 6.74},
'12': {'min': 36, 'max': 45, 'rain': 6.94}
}
highlight = {'min': 40, 'max': 80, 'rain': 5}

return render_template('index.html', city=city, months=months,
weather=weather,highlight=highlight)

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

index.html

{% import 'macros.html' as macros %}
<!DOCTYPE html>
<html>
<head>
<title>sddsddd</title>
<meta charset="utf-8">
</head>
<body>
<h1>天气平均值</h1>
<h2>{{city}}</h2>
<table border="1px">
<tr>
<th>月份</th>
<th>最小</th>
<th>最大</th>
<th>降雨量</th>
</tr>

{% for month in months %}
{{ macros.weather_row(month,
weather[month]['min'],
weather[month]['max'],
weather[month]['rain'],
highlight['min'],
highlight['max'],
highlight['rain']
)
}}
{% endfor%}
</table>

</body>
</html>

macros.html

<!-- 定义函数 值与变量 当h1满足条件时加粗字体 -->
{% macro weather_cell(value, hl) %}
<td>
{% if hl %}<b>{% endif %}
{{ value }}
{% if hl %}</b>{% endif %}
</td>
{% endmacro %}



{% macro weather_row(month, min, max, rain, hl_min, hl_max, hl_rain) %}
<tr>
<td>{{ month }}</td>
{{ weather_cell(min, min <= hl_min) }}
{{ weather_cell(max, max >= hl_max) }}

{{ weather_cell(rain, rain >= hl_rain) }}
</tr>
{% endmacro %}
<!-- 函数调用函数 当min 低于预定值时会加粗显示-->

引用bootstrap到模板

pip install flask-bootstrap
app.py

#coding:utf-8

from flask import Flask, render_template
from flask_bootstrap import Bootstrap
app = Flask(__name__)
bootstrap = Bootstrap(app)


@app.route('/')
def index():
city = u'北京'
months = ['1', '2', '3', '4','5', '6', '7', '8', '9', '10', '11', '12']
weather = {
'1': {'min': 38, 'max': 47, 'rain': 6.14},
'2': {'min': 38, 'max': 51, 'rain': 4.79},
'3': {'min': 41, 'max': 56, 'rain': 4.5},
'4': {'min': 44, 'max': 61, 'rain': 3.4},
'5': {'min': 49, 'max': 67, 'rain': 2.55},
'6': {'min': 53, 'max': 73, 'rain': 1.69},
'7': {'min': 57, 'max': 80, 'rain': 0.59},
'8': {'min': 58, 'max': 80, 'rain': 0.71},
'9': {'min': 54, 'max': 75, 'rain': 1.54},
'10': {'min': 48, 'max': 63, 'rain': 3.42},
'11': {'min': 41, 'max': 52, 'rain': 6.74},
'12': {'min': 36, 'max': 45, 'rain': 6.94}
}
highlight = {'min': 40, 'max': 80, 'rain': 5}

return render_template('index.html', city=city, months=months,
weather=weather,highlight=highlight)

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

{% extends 'bootstrap/base.html' %}
{% import 'macros.html' as macros %}

{% block title %}Weather Averages for {{ city }}{% endblock %}

{% block navbar %}
<nav class="navbar navbar-inverse" role="navigation">
<div class="container">
<a class="navbar-brand" href="#">Weather</a>
</div>
</nav>
{% endblock %}

{% block content %}
<div class="container">
<h1>Weather Averages</h1>
<h2>{{ city }}</h2>
<table class="table table-hover">
<tr>
<th>Month</th>
<th>Min</th>
<th>Max</th>
<th>Rainfall</th>
</tr>
{% for month in months %}
{{ macros.weather_row(month,
weather[month]['min'],
weather[month]['max'],
weather[month]['rain'],
highlight['min'],
highlight['max'],
highlight['rain']) }}
{% endfor %}
</table>
</div>
{% endblock %}

macros.html

<!-- 定义函数 值与变量 当h1满足条件时加粗字体 -->
{% macro weather_cell(value, hl) %}
<td{% if hl %} class="warning"{% endif %}>{{ value }}</td>
{% endmacro %}



{% macro weather_row(month, min, max, rain, hl_min, hl_max, hl_rain) %}
<tr>
<td>{{ month }}</td>
{{ weather_cell(min, min <= hl_min) }}
{{ weather_cell(max, max >= hl_max) }}

{{ weather_cell(rain, rain >= hl_rain) }}
</tr>
{% endmacro %}
<!-- 函数调用函数 当min 低于预定值时会加粗显示-->


{% macro weather_cell(value, hl) %}
<td{% if hl %} class="warning"{% endif %}>{{ value }}</td>
{% endmacro %}

自定义404页面

#coding:utf-8

from flask import Flask, render_template
from flask_bootstrap import Bootstrap
app = Flask(__name__)
bootstrap = Bootstrap(app)


@app.route('/')
def index():
city = u'北京'
months = ['1', '2', '3', '4','5', '6', '7', '8', '9', '10', '11', '12']
weather = {
'1': {'min': 38, 'max': 47, 'rain': 6.14},
'2': {'min': 38, 'max': 51, 'rain': 4.79},
'3': {'min': 41, 'max': 56, 'rain': 4.5},
'4': {'min': 44, 'max': 61, 'rain': 3.4},
'5': {'min': 49, 'max': 67, 'rain': 2.55},
'6': {'min': 53, 'max': 73, 'rain': 1.69},
'7': {'min': 57, 'max': 80, 'rain': 0.59},
'8': {'min': 58, 'max': 80, 'rain': 0.71},
'9': {'min': 54, 'max': 75, 'rain': 1.54},
'10': {'min': 48, 'max': 63, 'rain': 3.42},
'11': {'min': 41, 'max': 52, 'rain': 6.74},
'12': {'min': 36, 'max': 45, 'rain': 6.94}
}
highlight = {'min': 40, 'max': 80, 'rain': 5}

return render_template('index.html', city=city, months=months,
weather=weather,highlight=highlight)
'''
404页面
'''

@app.errorhandler(404)
def not_found(e):
return render_template('404.html')

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

base.html

{% extends 'bootstrap/base.html' %}

{% block navbar %}
<nav class="navbar navbar-inverse" role="navigation">
<div class="container">
<a class="navbar-brand" href="#">Weather</a>
</div>
</nav>
{% endblock %}

{%- block metas %}
<meta charset="utf-8">
{%- endblock metas %}

{% block content %}
<div class="container">
{% block page_content %}{% endblock %}
</div>
{% endblock %}

macros.html

{% macro weather_cell(value, hl) %}
<td{% if hl %} class="warning"{% endif %}>{{ value }}</td>
{% endmacro %}

{% macro weather_row(month, min, max, rain, hl_min, hl_max, hl_rain) %}
<tr>
<td>{{ month }}</td>
{{ weather_cell(min, min <= hl_min) }}
{{ weather_cell(max, max >= hl_max) }}

{{ weather_cell(rain, rain >= hl_rain) }}
</tr>
{% endmacro %}

index.html


{% extends 'base.html' %}
{% import 'macros.html' as macros %}

{% block title %}Weather Averages for {{ city }}{% endblock %}

{% block page_content %}
<h1>Weather Averages</h1>
<h2>{{ city }}</h2>
<table class="table table-hover">
<tr>
<th>Month</th>
<th>Min</th>
<th>Max</th>
<th>Rainfall</th>
</tr>
{% for month in months %}
{{ macros.weather_row(month,
weather[month]['min'],
weather[month]['max'],
weather[month]['rain'],
highlight['min'],
highlight['max'],
highlight['rain']) }}
{% endfor %}
</table>
{% endblock %}

404.html

{% extends 'base.html' %}

{% block title %}Not Found{% endblock %}

{% block page_content %}
<h1>404 页面未找到</h1>
{% endblock %}

url_for() 函数

直接跳转到控制层某函数
app.py

#coding:utf-8

from flask import Flask, render_template
from flask_bootstrap import Bootstrap
app = Flask(__name__)
bootstrap = Bootstrap(app)


@app.route('/')
def index():
city = u'北京'
months = ['1', '2', '3', '4','5', '6', '7', '8', '9', '10', '11', '12']
weather = {
'1': {'min': 38, 'max': 47, 'rain': 6.14},
'2': {'min': 38, 'max': 51, 'rain': 4.79},
'3': {'min': 41, 'max': 56, 'rain': 4.5},
'4': {'min': 44, 'max': 61, 'rain': 3.4},
'5': {'min': 49, 'max': 67, 'rain': 2.55},
'6': {'min': 53, 'max': 73, 'rain': 1.69},
'7': {'min': 57, 'max': 80, 'rain': 0.59},
'8': {'min': 58, 'max': 80, 'rain': 0.71},
'9': {'min': 54, 'max': 75, 'rain': 1.54},
'10': {'min': 48, 'max': 63, 'rain': 3.42},
'11': {'min': 41, 'max': 52, 'rain': 6.74},
'12': {'min': 36, 'max': 45, 'rain': 6.94}
}
highlight = {'min': 40, 'max': 80, 'rain': 5}

return render_template('index.html', city=city, months=months,
weather=weather,highlight=highlight)
'''
404页面
'''

@app.errorhandler(404)
def not_found(e):
return render_template('404.html')

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

index.html



{% extends 'bootstrap/base.html' %}
{% import 'macros.html' as macros %}

{% block title %}Weather Averages for {{ city }}{% endblock %}

{% block navbar %}
<nav class="navbar navbar-inverse" role="navigation">
<div class="container">
<a class="navbar-brand" href="#">Weather</a>
</div>
</nav>
{% endblock %}

{% block content %}
<div class="container">
<h1>Weather Averages</h1>
<h2>{{ city }}</h2>
<table class="table table-hover">
<tr>
<th>Month</th>
<th>Min</th>
<th>Max</th>
<th>Rainfall</th>
</tr>
{% for month in months %}
{{ macros.weather_row(month,
weather[month]['min'],
weather[month]['max'],
weather[month]['rain'],
highlight['min'],
highlight['max'],
highlight['rain']) }}
{% endfor %}
</table>
</div>
{% endblock %}

macros.html

<!-- 定义函数 值与变量 当h1满足条件时加粗字体 -->
{% macro weather_cell(value, hl) %}
<td{% if hl %} class="warning"{% endif %}>{{ value }}</td>
{% endmacro %}



{% macro weather_row(month, min, max, rain, hl_min, hl_max, hl_rain) %}
<tr>
<td>{{ month }}</td>
{{ weather_cell(min, min <= hl_min) }}
{{ weather_cell(max, max >= hl_max) }}

{{ weather_cell(rain, rain >= hl_rain) }}
</tr>
{% endmacro %}
<!-- 函数调用函数 当min 低于预定值时会加粗显示-->


{% macro weather_cell(value, hl) %}
<td{% if hl %} class="warning"{% endif %}>{{ value }}</td>
{% endmacro %}

404.html

{% extends 'base.html' %}

{% block title %}Not Found{% endblock %}

{% block page_content %}
<h1>404 页面未找到</h1>
<p><a href="{{ url_for('index') }}">Return to home page</a></p>
{% endblock %}

base.html

{% extends 'bootstrap/base.html' %}

{% block navbar %}
<nav class="navbar navbar-inverse" role="navigation">
<div class="container">
<a class="navbar-brand" href="{{ url_for('index') }}">Weather</a>
</div>
</nav>
{% endblock %}
{%- block metas %}
<meta charset="utf-8">
{%- endblock metas %}

{% block content %}
<div class="container">
{% block page_content %}{% endblock %}
</div>
{% endblock %}

request 函数

from flask import Flask, render_template, request
from flask_bootstrap import Bootstrap

app = Flask(__name__)
bootstrap = Bootstrap(app)

@app.route('/', methods=['GET', 'POST'])
def index():
name = None
print request.form
if request.method == 'POST' and 'name' in request.form:
name = request.form['name']
return render_template('index.html', name=name)

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

index.html

{% extends "bootstrap/base.html" %}

{% block title %}Form Example{% endblock %}

{% block navbar %}
<nav class="navbar navbar-inverse" role="navigation">
<div class="container">
<a class="navbar-brand" href="{{ url_for('index') }}">Hello</a>
</div>
</nav>
{% endblock %}

{% block content %}
<div class="container">
<form method="POST" action="">
What is your name? <input type="text" name="name">
<input type="submit" name="submit" value="Submit">
</form>
{% if name %}
<h1>Hello, {{ name }}!</h1>
{% endif %}
</div>
{% endblock %}

限定上传长度

hello.py

from flask import Flask, render_template
from flask_bootstrap import Bootstrap
from flask_wtf import Form

from wtforms import StringField, SubmitField
from wtforms.validators import Required, Length

app = Flask(__name__)
app.config['SECRET_KEY'] = 'top secret!'
bootstrap = Bootstrap(app)


class NameForm(Form):
name = StringField('What is your name?', validators=[Required(),
Length(1, 16)])
submit = SubmitField('Submit')


@app.route('/', methods=['GET', 'POST'])
def index():
name = None
form = NameForm()
if form.validate_on_submit():
name = form.name.data
form.name.data = ''
return render_template('index.html', form=form, name=name)


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

index.html

{% extends "bootstrap/base.html" %}

{% block title %}Form Example{% endblock %}

{% block navbar %}
<nav class="navbar navbar-inverse" role="navigation">
<div class="container">
<a class="navbar-brand" href="{{ url_for('index') }}">Hello</a>
</div>
</nav>
{% endblock %}

{% block content %}
<div class="container">
<form method="POST" action="">
{{ form.name.label }} {{ form.name(size=16) }}
{% for error in form.name.errors %}
{{ error }}
{% endfor %}
<br>
{{ form.submit() }}
{{ form.hidden_tag() }}
</form>
{% if name %}
<h1>Hello, {{ name }}!</h1>
{% endif %}
</div>
{% endblock %}

bootstrap美化表单

hello.py

from flask import Flask, render_template
from flask_bootstrap import Bootstrap
from flask_wtf import Form

from wtforms import StringField, SubmitField
from wtforms.validators import Required, Length

app = Flask(__name__)
app.config['SECRET_KEY'] = 'top secret!'
bootstrap = Bootstrap(app)


class NameForm(Form):
name = StringField('What is your name?', validators=[Required(),
Length(1, 16)])
submit = SubmitField('Submit')


@app.route('/', methods=['GET', 'POST'])
def index():
name = None
form = NameForm()
if form.validate_on_submit():
name = form.name.data
form.name.data = ''
return render_template('index.html', form=form, name=name)


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

index.html


{% extends "bootstrap/base.html" %}
{% import "bootstrap/wtf.html" as wtf %}

{% block title %}Form Example{% endblock %}

{% block navbar %}
<nav class="navbar navbar-inverse" role="navigation">
<div class="container">
<a class="navbar-brand" href="{{ url_for('index') }}">Hello</a>
</div>
</nav>
{% endblock %}

{% block content %}
<div class="container">
<div class="row">
<div class="col-md-3">
{{ wtf.quick_form(form) }}
{% if name %}
<h1>Hello, {{ name }}!</h1>
{% endif %}
</div>
</div>
</div>
{% endblock %}

文件上传

├── static
│ └── uploads
│ └── README.md 文件会上传到此目录
├── templates
│ └── index.html
└── upload.py

3 directories, 3 files

upload.py

import os
import imghdr

from flask import Flask, render_template
from flask_bootstrap import Bootstrap
from flask_wtf import Form
from wtforms import FileField, SubmitField, ValidationError

app = Flask(__name__)
app.config['SECRET_KEY'] = 'top secret!'
bootstrap = Bootstrap(app)


class UploadForm(Form):
image_file = FileField('Image file')
submit = SubmitField('Submit')

def validate_image_file(self, field):
if field.data.filename[-4:].lower() != '.jpg':
raise ValidationError('Invalid file extension')
if imghdr.what(field.data) != 'jpeg':
raise ValidationError('Invalid image format')


@app.route('/', methods=['GET', 'POST'])
def index():
image = None
form = UploadForm()
if form.validate_on_submit():
image = 'uploads/' + form.image_file.data.filename
form.image_file.data.save(os.path.join(app.static_folder, image))
return render_template('index.html', form=form, image=image)


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

{% extends "bootstrap/base.html" %}
{% import "bootstrap/wtf.html" as wtf %}

{% block title %}File Upload Example{% endblock %}

{% block navbar %}
<nav class="navbar navbar-inverse" role="navigation">
<div class="container">
<a class="navbar-brand" href="{{ url_for('index') }}">Upload</a>
</div>
</nav>
{% endblock %}

{% block content %}
<div class="container">
<div class="row">
<div class="col-md-4">
{{ wtf.quick_form(form, enctype='multipart/form-data') }}
</div>
</div>
{% if image %}
<img src="{{ url_for('static', filename=image) }}">
{% endif %}
</div>
{% endblock %}

session 信息

plus.py

from flask import Flask, render_template, session
app = Flask(__name__)
app.config['SECRET_KEY'] = 'top secret!'


@app.route('/')
def index():
print session
if 'count' not in session:
session['count'] = 1
else:
session['count'] += 1
return render_template('index.html', count=session['count'])


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

index.html

<h1>You have seen this page {{ count }} times.</h1>
<p>Hit refresh to increase.</p>

页面访问统计 以及时间

plus1.py

from datetime import datetime
from flask import Flask, render_template, session, g
app = Flask(__name__)
app.config['SECRET_KEY'] = 'top secret!'


@app.before_request
def before_request():
if not 'count' in session:
session['count'] = 1
else:
session['count'] += 1
g.when = datetime.now().strftime('%H:%M:%S')


@app.route('/')
def index():
return render_template('index.html', count=session['count'], when=g.when)


@app.route('/other')
def other():
return render_template('other.html', count=session['count'], when=g.when)


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

index.html

<h1>Index Page</h1>
<p>You have a total of {{ count }} page views in this site, the last of which was at {{ when }}.</p>
<p><a href="{{ url_for('other') }}">Click here</a> to see the other page.</p>

other.html

<h1>Other Page</h1>
<p>You have a total of {{ count }} page views in this site, the last of which was at {{ when }}.</p>
<p><a href="{{ url_for('index') }}">Click here</a> to see the index page.</p>

多种请求 响应方式

responses.py

from flask import Flask, render_template, make_response, jsonify, redirect, \
url_for
app = Flask(__name__)


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


@app.route('/text')
def text():
return render_template('text.txt'), 200, {'Content-Type': 'text/plain'}


@app.route('/xml')
def xml():
return '<h1>this is shown as <b>XML</b> in the browser</h1>', 200, \
{'Content-Type': 'application/xml'}


@app.route('/json')
def json():
return jsonify({'first_name': 'John', 'last_name': 'Smith'})


@app.route('/redirect')
def redir():
return redirect(url_for('text'))


@app.route('/cookie')
def cookie():
resp = redirect(url_for('index'))
resp.set_cookie('cookie', 'Hello, I\'m a cookie')
return resp


@app.route('/error')
def error():
return 'Bad Request', 400


@app.route('/response')
def response():
resp = make_response(render_template('text.txt'))
resp.headers['Content-Type'] = 'text/plain'
return resp


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

text.text

This page contains plain text.
Use your back button to go back to the index page.

index.html


<h1>This page contains HTML</h1>
<p>
Cookie:
{% if 'cookie' in request.cookies %}
<b>{{ request.cookies['cookie'] }}</b>
{% else %}
not set
{% endif %}
</p>
<p><a href="{{ url_for('text') }}">Click here</a> to view a page that contains plain text.</p>
<p><a href="{{ url_for('xml') }}">Click here</a> to view a page that contains XML data.</p>
<p><a href="{{ url_for('json') }}">Click here</a> to view a page that contains JSON data.</p>
<p><a href="{{ url_for('redir') }}">Click here</a> to view a page that redirects to the plain text page.</p>
<p><a href="{{ url_for('cookie') }}">Click here</a> to view a page that sets a cookie and then redirects back to this page.</p>
<p><a href="{{ url_for('response') }}">Click here</a> to view a page that shows plain text through a response object.</p>

from表单取值

复选框

<div class="form-group">
<label class="control-label col-sm-2 col-lg-2 text-navy" for="id_title">操作系统</label>
<div class="col-sm-10">
<input type="checkbox" name="hobby" value="football"/>足球
<input type="checkbox" name="hobby" value="basketball" checked="checked"/>篮球
<input type="checkbox" name="hobby" value="pingpong" checked="checked" />乒乓球
</div>
</div>

-----
@app.route('/aa', methods=['POST'])
def assts_aa():
tmp = request.values.getlist('hobby')
print tmp
for i in tmp
pass
get_id = 1

单选框

<div class="form-group">
<label class="control-label col-sm-2 col-lg-2 text-navy" for="id_title">操作系统</label>
<div class="col-sm-10">
<input type="radio" name="sex" value="1" checked="checked" />男
<input type="radio" name="sex" value="0" />女
</div>
</div>


@app.route('/aa', methods=['POST'])
def assts_aa():
print request.form.get('sex','')

flask获取上传表单(列表形式)

# html内容
<div class="form-group">
<label class="col-sm-2 control-label">项目组:</label>
<div class="col-sm-10">
<! -- start-->
{% if project_group_list %}
{% for foo in project_group_list %}
<input id="id_title" type="checkbox" name="project_group_name"
value="{{ foo['id'] }}"/>{{ foo['project_group_name'] }}&nbsp&nbsp
{% endfor %}

{% endif %}
<! -- end-->
</div>
</div>

# 上传的表单数据
project_group_name:1
project_group_name:2
project_group_name:3
project_group_name:4
project_group_name:5

# python flask获取列表
project_group_name = request.values.getlist('project_group_name')
print projects_id

# 返回值
[u'1', u'2', u'3', u'4', u'5']

# 传给models进行处理
status, result= models.project_id_project_group_id_correlation(project_group_name_id_list_s, project_name)
if not status:
return json.dumps({'code': 400, 'result': result})
return json.dumps({'code': 200, 'result': result})


# models代码
'''
项目ID.项目组ID关联关系.保存
'''
def project_id_project_group_id_correlation(project_group_name_id_list_s, project_name):
SQL_GET_PROJECT_NAME_ID = '''
SELECT `id` FROM project WHERE `project_name`=%s
'''
sql = SQL_GET_PROJECT_NAME_ID
args =(project_name,)
rt_cnt , rt_list = dbutils.execute_sql(sql, args, True)
# 获取刚添加项目ID
project_id = rt_list[0][0]

SQL_PROJECT_ID_PROJECT_GROUP_ID_CORRELATION='''
INSERT INTO `project_id_project_group_id` (`project_id`, `project_group_id`) VALUES
'''
sql_insert = SQL_PROJECT_ID_PROJECT_GROUP_ID_CORRELATION
cnt = 0
for project_group_name_id_list in project_group_name_id_list_s:
if cnt == 0:
sql_insert = sql_insert + '({project_id},{project_group_name_id_list})'.format(project_id=project_id,project_group_name_id_list=project_group_name_id_list)
sql_insert = sql_insert + ' ,({project_id},{project_group_name_id_list})'.format(project_id=project_id,project_group_name_id_list=project_group_name_id_list)
cnt = 1
args = ()
try:
rt_cnt, rt_list = dbutils.execute_sql(sql_insert, args, False)
except:
return (False,u'保存项目id与项目组id关联失败')
return (True, u'保存项目id与项目组id关联成功')