flask基础

2018-10-29  本文已影响0人  孙子衡

配置文件

from flask import \
    (Flask,
     url_for,
     render_template,
     redirect,
     request,
     jsonify,
     make_response,
     session,
     Markup,
     flash,
     get_flashed_messages,
     )

app = Flask(__name__)

print(app.config)
app.config.from_object('setting.Foo') # 更改配置文件

路由系统


@app.route('/index',methods=['GET','POST'],endpoint='n1')
#  endpoint='n1' 相当于django里面的 name='n1' 
# 如果不写 endpoint='n1' 系统默认 endpoint= 函数名
def hello_world():
    print(url_for('n1'))
    return 'Hello World!'

@app.route('/test/<username>/<int:nid>')
def func(username,nid):

    print(url_for('func',username='sunziheng',nid=10))

    return username

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

视图

请求相关

request.form
request.args
request.method

响应

    #定制响应头:
    obj = make_response('aaa')
    obj.headers['xxx'] = '123'
    obj.set_cookie('k','v')
    return obj

    return "index"
    return render_template()
    return jsonify({'k','v'})
    

模板渲染

#特殊装饰器
@app.template_global() # 全局调用
def sum(x,y):
    return x+ y

@app.template_filter()  # 可用于条件判断
def ff(x,y,z):
    return x + y + z
#视图:
@app.template_global()
def sum(x,y):
    return x+ y

@app.template_filter()  # 可用于条件判断
def ff(x,y,z):
    return x + y + z
@app.route('/test')
def test():

    context = {
        'foo':foo,
        'data':{'name':'sunziheng'}
    }

    return render_template('test.html',**context)

#模板层
{% extends 'base.html' %}
{% block content %}

    {% include 'include.html' %}
    <hr>
    {{ foo(3,4) }}
    {{ data['name'] }}
    {{ sum(1,2) }}
    {{ 3 | ff(4,5) }}
    <br>
    <p>定义宏</p>
    {% macro tem(name, type='text', value='') %}
        <input type="{{ type }}" name="{{ name }}" value="{{ value }}">
        <input type="submit">
    {% endmacro %}
    {{ tem('n1') }}
    {{ tem('n2') }}

{% endblock %}

session 和 cookie

session['xxx'] = 123
session.get['xx']

闪现

@app.route('/linshi')
def linshi():
    flash("临时数据01","error")
    flash("临时数据02", "error")
    flash("临时数据03", "info")

    return 'ok'

@app.route('/read')
def read():
    print(get_flashed_messages(category_filter=['error']))

    return 'Session'



中间件


蓝图


特殊装饰器

@app.before_request
@app.after_request
@app.template_filter()
@app.template_global()

登录

#版本一: 使用装饰器
import functools
def auth(func):
    @functools.wraps(func)
    def inner(*args,**kwargs):
        if  not session.get('user'):
            return redirect(url_for('login'))
        ret = func(*args,**kwargs)
        return ret
    return inner


@app.route('/login/',methods=['GET','POST'])
def login():
    if request.method == "POST":
        user = request.form.get('user')
        pwd = request.form.get('pwd')
        if user=="sunziheng" and pwd=='123':
            session['user'] = '123'
            return redirect(url_for('show'))
        else:
            error = '用户名或密码错误'
            return render_template('login.html',error=error)
    else:
        return render_template('login.html')

data = {
    1:{"name":"sunziheng","age":20,"sex":"男"},
    2:{"name":"徐周","age":22,"sex":"男"},
    3:{"name":"天天","age":18,"sex":"女"},
    4:{"name":"海东","age":25,"sex":"男"},
    5:{"name":"静姝","age":6,"sex":"女"}


}

@app.route('/show')
@auth
def show():
    # user = session.get('user')
    # print(user)
    # if not user:
    #     return redirect(url_for('login'))
    return render_template('index.html',info=data)


@app.route('/desc/<int:nid>')
@auth
def desc(nid):
    # print(nid)
    info = data[nid]
    # print(info)

    return render_template('detail.html',info=info)

@app.route('/delete/<int:nid>')
@auth
def delete(nid):
    del data[nid]
    return redirect(url_for('show'))

# 版本二: flask封装之 before_request
@app.before_request
def hahaha():
    if request.path == '/login/':
        return None
    if session.get('user'):
        return None
    return redirect(url_for('login'))

@app.route('/login/',methods=['GET','POST'])
def login():
    if request.method == "POST":
        user = request.form.get('user')
        pwd = request.form.get('pwd')
        if user=="sunziheng" and pwd=='123':
            session['user'] = '123'
            return redirect(url_for('show'))
        else:
            error = '用户名或密码错误'
            return render_template('login.html',error=error)
    else:
        return render_template('login.html')

data = {
    1:{"name":"sunziheng","age":20,"sex":"男"},
    2:{"name":"徐周","age":22,"sex":"男"},
    3:{"name":"天天","age":18,"sex":"女"},
    4:{"name":"海东","age":25,"sex":"男"},
    5:{"name":"静姝","age":6,"sex":"女"}


}

@app.route('/show')
def show():
    # user = session.get('user')
    # print(user)
    # if not user:
    #     return redirect(url_for('login'))
    return render_template('index.html',info=data)


@app.route('/desc/<int:nid>')
def desc(nid):
    # print(nid)
    info = data[nid]
    # print(info)

    return render_template('detail.html',info=info)

@app.route('/delete/<int:nid>')
def delete(nid):
    del data[nid]
    return redirect(url_for('show'))

上一篇下一篇

猜你喜欢

热点阅读