Python基础9 Web开发框架Flask入门
- 一、安装
- 二、开始
- 1. 入口
- 要公开服务,可以使用
- 打开调试模式
- 2. 路由
- 路由变量规则
- 构造URL
- HTTP方法
- 静态文件
- 3. 模板渲染
- 4. request对象的使用
- 5. 文件上传
- 6. Cookies操作
- 读取
- 存储
- 7. 重定向和错误
- 8. session
- 9. 日志
本文学习过程主要来源网址:
- http://flask.pocoo.org/docs/0.12/
- http://docs.jinkan.org/docs/flask/quickstart.html
一、安装
配置repo
wget http://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
rpm -ivh epel-release-latest-7.noarch.rpm
# 使用虚拟环境
sudo pip install virtualenv
#ubuntu:
#sudo apt-get install python-virtualenv
#创建项目
mkdir myproject
cd myproject
#virtualenv venv
#windows下运行
venv\Scripts\activate
只需要激活一致性环境,就可以开启项目了。
而运行
deactivate
就可以回到正常环境。
再运行
pip install Flask
pip install --upgrade pip setuptools
二、开始
1. 入口
hello.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
运行
python hello.py
可以看到http://127.0.0.1:5000/
要公开服务,可以使用
app.run(host='0.0.0.0')
打开调试模式
app.debug=true
启用调试模式后,每次修改代码不需要重启python。
也可以:
app.run(debug=True)
调试模式一定不能用于生产环境。
2. 路由
@app.route('/')
def index():
return 'Index Page'
@app.route('/hello')
def hello():
return 'Hello World'
路由变量规则
@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return 'User %s' % 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
构造URL
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()
静态文件
url_for('static', filename='style.css')
3. 模板渲染
Jinja2模板文档:http://docs.jinkan.org/docs/jinja2
Flask使用了Jinja2模板引擎。
/application.py
/templates
/hello.html
from flask import render_template
@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
<title>Hello from Flask</title>
{% if name %}
<h1>Hello {{ name }}!</h1>
{% else %}
<h1>Hello World!</h1>
{% endif %}
在模板里,你也可以访问 request 、 session 和 g [1] 对象, 以及 get_flashed_messages() 函数。
默认情况下.html 、 .htm 、.xml 、 .xhtml 自动转义功能是打开的。可以使用Markup类或|safe过滤器将变量标记为安全的。
>>> from flask import Markup
>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'
Markup(u'<strong>Hello <blink>hacker</blink>!</strong>')
>>> Markup.escape('<blink>hacker</blink>')
Markup(u'<blink>hacker</blink>')
>>> Markup('<em>Marked up</em> » HTML').striptags()
u'Marked up \xbb HTML'
4. request对象的使用
from flask import request
@app.route('/login', methods=['POST', 'GET'])
def login():
error = None
if request.method == 'POST':
if valid_login(request.form['username'],
request.form['password']):
return log_the_user_in(request.form['username'])
else:
error = 'Invalid username/password'
# the code below is executed if the request method
# was GET or the credentials were invalid
return render_template('login.html', error=error)
可以通过args属性来访问URL中提交的参数。
searchword = request.args.get('q', '')
5. 文件上传
from flask import request
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
f = request.files['the_file']
f.save('/var/www/uploads/uploaded_file.txt')
...
from flask import request
from werkzeug import secure_filename
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
f = request.files['the_file']
f.save('/var/www/uploads/' + secure_filename(f.filename))
...
6. Cookies操作
读取
# 读取
from flask import request
@app.route('/')
def index():
username = request.cookies.get('username')
# use cookies.get(key) instead of cookies[key] to not get a
# KeyError if the cookie is missing.
存储
# 存储
from flask import make_response
@app.route('/')
def index():
resp = make_response(render_template(...))
resp.set_cookie('username', 'the username')
return resp
7. 重定向和错误
from flask import abort, redirect, url_for
@app.route('/')
def index():
return redirect(url_for('login'))
@app.route('/login')
def login():
abort(401)
this_is_never_executed()
定制错误页面
from flask import render_template
@app.errorhandler(404)
def page_not_found(error):
return render_template('page_not_found.html'), 404
8. session
from flask import Flask, session, redirect, url_for, escape, request
app = Flask(__name__)
@app.route('/')
def index():
if 'username' in session:
return 'Logged in as %s' % escape(session['username'])
return 'You are not logged in'
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
session['username'] = request.form['username']
return redirect(url_for('index'))
return '''
<form action="" method="post">
<p><input type=text name=username>
<p><input type=submit value=Login>
</form>
'''
@app.route('/logout')
def logout():
# remove the username from the session if it's there
session.pop('username', None)
return redirect(url_for('index'))
# set the secret key. keep this really secret:
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
9. 日志
app.logger.debug('A value for debugging')
app.logger.warning('A warning occurred (%d apples)', 42)
app.logger.error('An error occurred')