如何使用urllib2将数据发布到服务器?

时间:2013-03-13 14:38:34

标签: python

我正在为python制作python twitch.tv API Wrapper,到目前为止我有:

import urllib2
import json
import time


waittime = 1
baseurl = 'https://api.twitch.tv/kraken/'
secret = '(CLASSIFIED)'


class twitchchannelinfo(): #Ignore me ;D I'm Here for reference's sake
    def __init__ (self,channel):
        self.channel = channel
        time.sleep(waittime)
        self.dict1 = json.loads(urllib2.urlopen(baseurl + 'channels/' + channel).read())

    def getstatus(self):
        return self.dict1 ['status']
    def getdisplay_name(self):
        return self.dict1 ['display_name']
    def getmature(self):
        return self.dict1 ['mature']
    def getchanurl(self):
        return self.dict1 ['url']
    def getcreated_at(self):
        return self.dict1 ['created_at']
    def getteams(self):
        return self.dict1 ['teams']
    def getgame(self):
        return self.dict1 ['game']
    def getupdated_at(self):
        return self.dict1 ['updated_at']

class twichtvwrapper():
    def __init__(self,username,password):        
        self.username = username
        self.password = password
        self.dict1 = json.loads(urllib2.urlopen(baseurl + 'oauth2/token',\
                        "client_id=<3kfp6al05voejvv7ofmpc94g4jga0tb>&\
                        client_secret=<" + secret + ">&\
                        username=<" + self.username + ">&\
                        password=<" + self.password + ">&\
                        scope=user_read&\
                        grant_type=password"))
        print self.dict1

me = twichtvwrapper('martincharles07','(CLASSIFIED)')

(秘密是API标识符,密码已被撤回,原因很明显; D)。

服务器应该返回如下的JSON响应:

{
    "scope":["user_read"],
    "access_token":"df4yofxyn2s7240ojfrh9chz8"
}

Here is the API reference.

程序因异常urllib2.HTTPError: HTTP Error 400: Bad Request而崩溃。我不知道我做错了什么,是行拆分还是错误使用urllib2?我该如何解决?

1 个答案:

答案 0 :(得分:0)

不要将字符串连接在一起尝试类似

的内容
body={'username':'someusername','password':'somepassword', ...}
txdata = urllib.urlencode(body)

您必须使用urllib代替urllib2才能使用该方法。

这是一个未经测试的代码段。

import json
import urllib
import urllib2

def wrapper(user, password, secret):

    data = {"client_id":"<3kfp6al05voejvv7ofmpc94g4jga0tb>",
            "client_secret":secret,
            "username":username,
            "password":password,
            "scope":"user_read",
            "grant_type":"password",
            }

    txdata = urllib.urlencode(data)
    response = urllib2.urlopen(baseurl + 'oauth2/token', txdata)
    return_data = json.loads(response.read())

    return return_data