flask

 

安装

   pip3 install flask 

1路由系统 
        - 默认使用app.route('/index',methods=['GET',"POST"])
        - 想要给视图添加装饰器:
            - 装饰器必须设置functools.wappers
            - 紧挨着放在视图之上
                 import functools

def auth(func):
@functools.wraps(func) # 保留函数的元信息
def inner(*args,**kwargs):
if not session.get('user_info'):
return redirect('/login')
ret = func(*args,**kwargs)
return ret
return inner

      
       @app.route('/detail')
       @auth
       def detail():
        nid = request.args.get('nid')
      return render_template('detail.html')


2. 视图函数
  - 请求相关:
    - request.form(取到post请求数据)
    - request.args (取到get数据)
    - request.method (判断是否是XX方法)
    - reqeust.path(获取url,在登录时排除login url设置白名单)
  - 响应相关:

      建在templates目录下
        - return "xxx"(返回字符串)
        - return render_template('index.html')(返回一个html页面,且)

      return render_template('index.html',klist=kuang_list)
      return render_template('index.html',**{'klist':kuang_list})


    - return redirect()(跳转)
5. 模板
    - 索引:
    - python语法(支持python语法)
    - 模板继承

6. 保存会话信息:session (字典)
  - 放在加密的cookie中
  - 依赖:
    app.secret_key = "asdfasdfasdf"
  -操作:
    session['k1'] = 123
    session.get('k1')
    del session['k1']

7. 特殊装饰器:(见截图)
  - before_request(所有请求之前执行)
  - after_request(所有请求之后执行)


 装饰器:

  

 hello_world flask版

from flask import Flask

app=Flask(__name__)
@app.route('/index/')
def index():
    return 'HelloWorld'

if __name__ == '__main__':
    app.run()
flask_helloWorld

session版登录 

保存到了浏览器的cookie中了

static 、templates的目录配置

原文地址:https://www.cnblogs.com/wanghuaqiang/p/9359401.html