简体   繁体   English

烧瓶会话变量在请求后不会更改

[英]flask session variable doesn't change after a request

I want to update the variable('CAPTCHA_NUM') when I visit the url('/captcha') and get this variable in templates: 当我访问url('/ captcha')并在模板中获取此变量时,我想更新变量('CAPTCHA_NUM'):

@app.route('/captcha')
def captcha():
    from captcha.image import ImageCaptcha
    from random import random
    image = ImageCaptcha()
    x = int(round(random() * 10000))
    if x < 1000: x += 1000
    session['CAPTCHA_NUM'] = x
    return image.generate(str(session['CAPTCHA_NUM']), 'png').getvalue()

But each time when I refresh my page(visit this url), the captcha updates, however the session['CAPTCHA_NUM'] doesn't. 但是每次我刷新页面(访问此URL)时,验证码都会更新,但是session['CAPTCHA_NUM']不会更新。

For example, first I get the captcha 7530 , then I refresh register.html (which visits the url) and captcha is updated but the session['CAPTCHA_NUM'] still is 7530 . 例如,首先获取验证码7530 ,然后刷新register.html (访问URL),并更新验证码,但session['CAPTCHA_NUM']仍然为7530

And this is where I visit the url(captcha): 这是我访问url(captcha)的地方:

register.html register.html

<img id="vcode" src="{{url_for('captcha')}}" alt="captcha" />

and I get session['CAPTCHA_NUM'] in validate_capcha() : 我在validate_capcha()获得了session['CAPTCHA_NUM']

<input type="text" name="captcha" onblur="validate_captcha()" />

=================Solution======================== ================解决方案=========================

In the official doc of flask session , it says: flask会话的正式文档 ,它说:

This variable is unavailable if the template was rendered without an active request context.

I just change the src attribute of img tag, and apparently this isn't an active request context. 我只是更改了img标签的src属性,显然这不是一个活动的请求上下文。

And finally I put the captcha validation part at the server-side so that I can avoid this problem. 最后,我将验证码验证部分放在服务器端,这样就可以避免此问题。

if you use visit http://***.com/captcha it won't refresh. 如果您使用http://***.com/captcha ,则不会刷新。 you Need to give it a param so it will refresh 你需要给它一个参数,这样它才能刷新

at first you write 起初你写

url_for('.captcha')

change it to 更改为

url_for('.captcha',t=some_random_value)

then it will refresh cause it generate a url like this: http://***.com/captcha?t=some_random_value 那么它将刷新,因为它会生成如下所示的网址: http://***.com/captcha?t=some_random_value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM