2016-05-17 60 views
0

我试图用瓶子来更新从聊天机器人中的命令馈入的站点上的信息,但是在检查变量是否被定义的同时,我正努力从一个路由获取信息到另一个。检查瓶子中是否定义了全局变量

它正常工作,直到我补充一下:

if 'area' not in globals(): 
     area = '' 
    if 'function' not in globals(): 
     function = '' 
    if 'user' not in globals(): 
     user = '' 
    if 'value' not in globals(): 
     value =''` 

要检查变量定义。它工作除非我使用/设置一个值。否则它与

Traceback (most recent call last): 
File "/usr/local/lib/python3.5/dist-packages/bottle.py", line 862, in _handle 
return route.call(**args) 
File "/usr/local/lib/python3.5/dist-packages/bottle.py", line 1732, in wrapper 
rv = callback(*a, **ka) 
File "API.py", line 43, in botOut 
return area + function + user + value 
UnboundLocalError: local variable 'area' referenced before assignment 

全部代码中的错误:

from bottle import route, error, post, get, run, static_file, abort, redirect, response, request, template 
Head = '''<!DOCTYPE html> 
    <html lang="en"> 
    <head> 
    <meta charset="utf-8"> 
    <link rel="stylesheet" href="style.css"> 
    <script src="script.js"></script> 
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> 
    </head> 
    ''' 

foot = '''</body></html>''' 

@route('/in') 
def botIn(): 
    global area 
    global function 
    global user 
    global value 
    area = request.query.area 
    function = request.query.function 
    user = request.query.user 
    value = request.query.value 
    print(area) 
    return "in" 


@route('/out') 
def botOut(): 
    if 'area' not in globals(): 
     area = '' 
    if 'function' not in globals(): 
     function = '' 
    if 'user' not in globals(): 
     user = '' 
    if 'value' not in globals(): 
     value ='' 
return area + function + user + value 

run (host='0.0.0.0', port=8080) 

回答

0

而不是使用4个全局的 - 这你就必须在几个地方global关键字的资格 - 只需在模块中创建一个字典级别,并存储您的状态在该字典中;无需在任何地方声明global

例如,

bot_state = { 
    'area': '', 
    'function': '', 
    'user': '', 
    'value': '' 
} 


@route('/in') 
def botIn(): 
    bot_state['area'] = request.query.area 
    bot_state['function'] = request.query.function 
    bot_state['user'] = request.query.user 
    bot_state['value'] = request.query.value 
    print(area) 
    return 'in' 


@route('/out') 
def botOut(): 
    return ''.join(
     bot_state['area'], 
     bot_state['function'], 
     bot_state['user'], 
     bot_state['value'], 
    ) 

注意,有几个改进,我会做的代码(例如,每个路由功能应该返回一个字符串列表,而不是一个字符串),但这些都是最小的变化我会为了解决你的眼前的问题而做出来的。希望能帮助到你!