2016-05-17 84 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'], 
    ) 

注意,有幾個改進,我會做的代碼(例如,每個路由功能應該返回一個字符串列表,而不是一個字符串),但這些都是最小的變化我會爲了解決你的眼前的問題而做出來的。希望能幫助到你!