Flask 学习笔记

来源:互联网 发布:淘宝5元店铺红包怎么用 编辑:程序博客网 时间:2024/06/06 08:50

学习网址:
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.rpmrpm -ivh epel-release-latest-7.noarch.rpm
sudo pip install virtualenv#ubuntu:#sudo apt-get install python-virtualenv#创建项目mkdir myprojectcd myproject#virtualenv venv#windows下运行venv\Scripts\activate

只需要激活一致性环境,就可以开启项目了。

而运行

deactivate

就可以回到正常环境。

再运行

pip install Flaskpip install --upgrade pip setuptools

开始

输入一个文件
hello.py

from flask import Flaskapp = 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)

调试模式一定不能用于生产环境。

路由

@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')

模板渲染

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)
<!doctype html><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 &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')>>> Markup.escape('<blink>hacker</blink>')Markup(u'&lt;blink&gt;hacker&lt;/blink&gt;')>>> Markup('<em>Marked up</em> &raquo; HTML').striptags()u'Marked up \xbb HTML'

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', '')

文件上传

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 requestfrom 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))    ...

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

重定向和错误

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

session

from flask import Flask, session, redirect, url_for, escape, requestapp = 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'

日志

app.logger.debug('A value for debugging')app.logger.warning('A warning occurred (%d apples)', 42)app.logger.error('An error occurred')
原创粉丝点击