用flask开发个人博客(4)—— flask中4种全局变量

https://blog.csdn.net/hyman_c/article/details/53512109

一  current_app

        current_app代表当前的flask程序实例,使用时需要flask的程序上下文激活,我们以本专栏第一篇文章中写的test.py为例介绍下它的用法:

1.1 激活程序上下文

[python] view plain copy
  1. >>> from test import app  
  2. >>> from flask import current_app  
  3. >>> from flask import g  
  4. >>> ctx=app.app_context()  
  5. >>> ctx.push()  

        app.app_context()为flask程序的上下文,简单说来就是flask程序需要运行的环境变量等等.ctx.push()是激活上下文的操作,类似的,如果我们想要回收上下文,用ctx.pop()

1.2 打印当前程序名称

[python] view plain copy
  1. >>> current_app.name  
  2. 'test'  

二  g变量

        g作为flask程序全局的一个临时变量,充当者中间媒介的作用,我们可以通过它传递一些数据,下面的例子,通过g传递了一个名字叫做"Hyman",使用g之前也需要激活程序上下文:

[plain] view plain copy
  1. >>> g.name='Hyman'  
  2. >>> g.name  
  3. 'Hyman'  

三 request对象

        请求对象,封装了客户端发送的HTTP请求的内容.可参照<<用flask开发个人博客(2)—— Flask中的请求对象request>>  .

四 session

        用户会话,用来记住请求(比如前后一个GET请求和一个POST请求)之间的值,从数据格式上来说它是字典类型。它存在于连接到服务器的每个客户端中,属于私有存储,会保存在客户端的cookie中。如下面的代码,用于重定向url:

[python] view plain copy
    1. @app.route('/', methods=['GET','POST'])  
    2. def index():  
    3.     form = NameForm()  
    4.     if form.validate_on_submit():  
    5.         session['name']=form.name.data  
    6.         return redirect(url_for('index'))  
    7.     renturn render_template('index.html',form=form,name=session.get('name')) 

------------------------------------------------

前端请求form:

[html] view plain copy
  1. <form action="/user/add" method="get">  
  2.         <input type="text" name="username" value="111">  
  3.         <input type="submit" value="提交">  
  4. </form>  

前端提交时,后端接收参数,可以把登录数据保存在session中:

扫描二维码关注公众号,回复: 1022365 查看本文章
[html] view plain copy
  1. @user.route('/add',methods=['GET'])  
  2. def add():  
  3.     username=request.values.get('username');  
  4.     session['username']=username  
  5.     return session['username']  

其中获取表单数据使用

[html] view plain copy
  1. request.values.get('username');  

复选框参数获取:

[html] view plain copy
  1. s_option =  request.values.getlist("s_option")  
  2. for s in s_option:  
  3.     pass  

使用@before_request拦截请求url

[html] view plain copy
  1. @user.before_request  
  2. def before_user():  
  3.     if 'username' in session:  
  4.         return '已登录'  
  5.         pass  
  6.  else:  
  7.         return '未登录'  

如果已经登录,通过拦截,若果未登录,返回提示信息或跳转到登录页面

猜你喜欢

转载自www.cnblogs.com/fengff/p/9087488.html
今日推荐