flask基本
一个示例:
#conding:utf8 |
模板渲染
#conding:utf8 |
|
变量
URL参数
from flask import Flask |
模板渲染
from flask import Flask, render_template |
模板渲染列表
├── templates |
<h1>Weather Averages</h1> |
渲染数据结构 for
#coding:utf-8 |
|
模板中使用条件判断 if
#coding:utf-8 |
<!DOCTYPE html> |
使用模板宏
相当于py中的函数,函数再调用函数减少代码冗余量
#coding:utf-8 |
index.html{% import 'macros.html' as macros %}
<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)
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' %} |
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 |
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)
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页面
'''
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 |
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.pyfrom 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')
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.pyfrom 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')
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.pyimport 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')
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" %} |
session 信息
plus.pyfrom flask import Flask, render_template, session
app = Flask(__name__)
app.config['SECRET_KEY'] = 'top secret!'
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.pyfrom datetime import datetime
from flask import Flask, render_template, session, g
app = Flask(__name__)
app.config['SECRET_KEY'] = 'top secret!'
def before_request():
if not 'count' in session:
session['count'] = 1
else:
session['count'] += 1
g.when = datetime.now().strftime('%H:%M:%S')
def index():
return render_template('index.html', count=session['count'], when=g.when)
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.pyfrom flask import Flask, render_template, make_response, jsonify, redirect, \
url_for
app = Flask(__name__)
def index():
return render_template('index.html')
def text():
return render_template('text.txt'), 200, {'Content-Type': 'text/plain'}
def xml():
return '<h1>this is shown as <b>XML</b> in the browser</h1>', 200, \
{'Content-Type': 'application/xml'}
def json():
return jsonify({'first_name': 'John', 'last_name': 'Smith'})
def redir():
return redirect(url_for('text'))
def cookie():
resp = redirect(url_for('index'))
resp.set_cookie('cookie', 'Hello, I\'m a cookie')
return resp
def error():
return 'Bad Request', 400
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.textThis 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"> |
flask获取上传表单(列表形式)
# html内容 |