全局变量是None而不是实例-Python [英] Global variable is None instead of instance - Python

查看:93
本文介绍了全局变量是None而不是实例-Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理Python中的全局变量.该代码应该可以正常工作,但是有问题.我必须为类 Back 的实例使用全局变量.当我运行应用程序时,它说back为None,这应该是不正确的,因为 setup()函数的第二行-'back = Back.Back()'

I'm dealing with global variables in Python. The code should work fine, but there is a problem. I have to use global variable for instance of class Back. When I run the application it says that back is None which should be not true because the second line in setup() function - 'back = Back.Back()'

# -*- coding: utf-8 -*-
from flask import Flask
from flask import request
from flask import render_template


import Search
import Back

app = Flask(__name__)
global back
back = None

@app.route('/')
def my_form():
    return render_template('my-form.html')

def setup():
    global back
    back = Back.Back()

def is_ascii(s):
    return all(ord(c) < 128 for c in s)  

@app.route('/', methods=['POST'])
def search():
    from time import time

    pattern = request.form['text']

    startTime = time()

    pattern=pattern.lower()

    arr = []

    if len(pattern)<1:
        arr.append('Incorrect input')

        currentTime = time()-startTime

        return render_template('my-form.html', arr=arr, time=currentTime)


    arr = []

    search = Search.Search(pattern,back)
    results =  search.getResults()

    ..................

    return render_template('my-form.html', arr=arr, time=currentTime, pattern=pattern)


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

为什么后退变量None而不是Back类的实例?谢谢

Why is the back variable None instead of instance of Back class? Thanks

推荐答案

Flask开发服务器运行您的模块两次.一次是运行服务器本身,另一次是在子进程中运行,以便每次对它进行更改时都可以重新加载整个脚本.就是第二进程将不会运行 __ main __ 受保护的代码,而全局变量将保留为 None .

The Flask development server runs your module twice. Once to run the server itself, and another time in a child process so it can reload your whole script each time you make a change to it. It is that second process that won't run the __main__ guarded code and the global is left as None.

如果您使用其他WSGI服务器,也会遇到相同的问题;会将文件作为模块导入,而不是作为初始脚本导入,并且不会执行 __ main __ 保护.

You'll get the same problem if you used another WSGI server; it'd import your file as a module, not as the initial script and the __main__ guard is not executed.

使用 @ app.before_first_request 功能代替;确保在处理此过程的第一个请求时执行该命令.如果您移至使用多个子进程来扩展站点的适当WSGI容器,这也可以使全局工作保持正常.

Use a @app.before_first_request function instead; it is guaranteed to be executed when the very first request is handled for this process. This also keeps your global working if you moved to a proper WSGI container that used multiple child processes to scale your site:

@app.before_first_request
def setup():
    global back
    back = Back.Back()

这篇关于全局变量是None而不是实例-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆