flask基础

1、Flask文件及基础功能

from flask import Flask, render_template, request, make_response, redirect, url_for

# 静态文件和模板路径配置
app = Flask(__name__)

# 返回模板
def test():
    return '<a>test</a>'

# 可以设置请求方式 methods=['get','post']
@app.route('/',methods=['get','post'])
def hello_world():
    # 返回字符串
    return 'Hello World!'

    # 获取用户请求的数据
    print(request.args)

    # 数据库 Django orm框架 SQLAlchemy
    # 或者PyMySQL

    # 返回额外的数据,设置cookie
    return make_response(render_template('index.html', k1='root', k2=[11, 22, 33, 44], k3={'name': 'lh', 'age': 18}, k4=test))
    obj = set_cookie(k1='v1')
    return obj

    # 重定向
    url = url_for('test2','about')
    return redirect(url)

    # 返回模板(可以传参数,单值,列表,字典)
    return render_template('index.html', k1='root', k2=[11, 22, 33, 44], k3={'name': 'lh', 'age': 18}, k4=test)

# 路由any只能用括号中的几个
@app.route('/<any(about,help,class,"foo bar"):page_name>')
def test2(page_name):
    return page_name

if __name__ == '__main__':
    # run中进行IP和端口的配置
    app.run()
View Code

  循环后端传回的字典时,{% for i in k3.items() %},需要在items后边加括号

  返回自定制模板时,需要对标签进行转义{{ k4()|safe }}

2、Flask的session及中间件

# session 设置
    session['name'] = 'lh'
    request.form['name']
View Code
from flask import Flask, render_template, request, make_response, redirect, url_for, session

app = Flask(__name__)

@app.route('/',methods=['get','post'])
def hello_world():
    return 'Hello'

class Foo():
    def __init__(self, w):
        self.w = w
    def __call__(self, environ, start_response):
        print '222222'
        obj = self.w(environ, start_response)
        print '111111'
        return obj
if __name__ == '__main__':
    # 先创建对象,把内部的app.wsgi_app传进去
    app.wsgi_app = Foo(app.wsgi_app)
    app.run()
中间件

3、Flask中Message的使用和原理

from flask import Flask, render_template, request, make_response, redirect, url_for, session, flash

app = Flask(__name__)

@app.route('/',methods=['get','post'])
def hello_world():
    return render_template('index.html')

@app.route('/set')
def set_num():
    # 设置值
    flash('error')
    return 'OK'

if __name__ == '__main__':
    app.run()
Message后端
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>index</h1>
    {% with messages = get_flashed_messages() %}
        {% if messages %}
            {% for message in messages %}
                {{ message }}
            {% endfor %}
        {% endif %}
    {% endwith %}
</body>
</html>
Message前端

 

posted on 2017-12-12 11:58  python屌丝的逆袭  阅读(72)  评论(0编辑  收藏  举报

导航