2

I'm so lost as to what I'm doing wrong... I've searched the net for a few hours now, tried to reformat my code a bunch, and now I just feel stuck.

This is my code:

import httplib
import json

urlBase = 'amoeba.im'
token = False
username = raw_input('Username? ')

connection = httplib.HTTPConnection(urlBase)

def get(url):
    connection.request("GET", url)
    response = connection.getresponse()
    print response.status, response.reason
    print response.read();
    if token == False:
        token = response.read()
        token = token.split('"token":"')[1]
        token = token.split('","')[0]
        print token

get('/api/login?username=' + username)

get('/api/rooms/join?room=#lobby&token=' + token)

get('/api/postmessage?message=hello%20world&token=' + token)

connection.close()

Here's the terminal output:

Tyler-Keohanes-MacBook-Pro:~ tylerkeohane$ clear && '/usr/bin/pythonw' '/Users/tylerkeohane/Desktop/chatbot.py'
Username? TgwizBot
200 OK
{"success":true,"username":"TgwizBot","token":"103f6a2809eafb6","users":[{"username":"razerwolf","seen":1338582178260},{"username":"tonynoname","seen":1338582178028},{"username":"arrum","seen":1338582177804},{"username":"Valerio","seen":1338582177504},{"username":"Tgwizman","seen":1338582177258},{"username":"tonynoname2","seen":1338582178004},{"username":"TgwizBot","seen":1338582182219}],"time":1338582182219}
Traceback (most recent call last):
  File "/Users/tylerkeohane/Desktop/chatbot.py", line 21, in <module>
    get('/api/login?username=' + username)
  File "/Users/tylerkeohane/Desktop/chatbot.py", line 15, in get
    if token == False:
UnboundLocalError: local variable 'token' referenced before assignment
Tyler-Keohanes-MacBook-Pro:~ tylerkeohane$ 

Can anyone help? :(

4

2 回答 2

7

The clue is here:

UnboundLocalError: local variable 'token' referenced before assignment

You need to declare token as a global:

def get(url):
    global token
    ...

You might also want to consider avoiding global variables as they are generally regarded as a bad practice.

于 2012-06-01T20:32:39.760 回答
1

You assign to token in your function, so it is considered a local variable to that function. As the error message indicates, you have tried to use it before there is anything in it.

The token that you have declared outside the function is "hidden" by the local variable so it is not accessible.

To make it assignable in your function, put global token just after the def line.

But global variables are usually a sign of a bad design. Instead you should probably be passing token into the function as an argument.

You will find life a lot easier if you just use the requests module.

于 2012-06-01T20:35:27.777 回答