检查是否在瓶

时间:2016-05-17 22:49:13

标签: python-3.x bottle

我试图使用瓶子来更新聊天机器人命令中输入的网站上的信息,但是在检查变量是否已定义的同时,我正在努力从一条路线获取信息到另一条路线。

在我添加之前它一切正常:

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

检查变量是否已定义。除非我使用/ in设置值,否则它可以工作。

错误
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)

2 个答案:

答案 0 :(得分:0)

而不是使用4个全局变量 - 您必须在几个地方使用global关键字限定 - 只需在模块级别创建一个dict,并将您的状态存储在该dict中;无需在任何地方声明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'],
    )

请注意,我对代码进行了多项改进(例如,每个路由函数应返回一个字符串列表,而不是字符串),但这些是我为了解决您的问题而做出的最小改动问题。希望它有所帮助!

答案 1 :(得分:0)

Bottle还有一个内置的解决方案。

http://bottlepy.org/docs/dev/stpl.html#bottle.SimpleTemplate

基本上{{get('title', 'No Title')}}

当然,你总是可以在任何字典上使用dict.get(variable, default_value)