Jump to content

Calling the Web API from Python 2.7


wagamama

Recommended Posts

With a bit of help from people on the forum I was able to put together a short code in snippet in Python that:

- logs in to uTorrent, and caches the GUID cookie

- obtains a token

- uses that token to add the URL of a torrent

The 'authentication' part I've taken from here: http://www.voidspace.org.uk/python/articles/authentication.shtml#id22

Ideally, I will encapsulate it into a Python module/class to allow easy reuse w/o copy-paste. In the meantime -


import urllib2
import cookielib
import re

theurl = 'http://192.168.1.106:9090/gui/'
username = 'admin'
password = ''

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
# this creates a password manager
passman.add_password(None, theurl, username, password)

authhandler = urllib2.HTTPBasicAuthHandler(passman)
# create the AuthHandler

opener = urllib2.build_opener(authhandler)

cj = cookielib.CookieJar()
opener.add_handler(urllib2.HTTPCookieProcessor(cj))

urllib2.install_opener(opener)
# All calls to urllib2.urlopen will now use our handler

pagehandle = urllib2.urlopen(theurl)
# authentication is now handled automatically for us

pagehandle = urllib2.urlopen(theurl+"token.html")
token = re.findall("<div.*?>(.*?)</", pagehandle.read())[0]
# obtained the token

torrent_url = 'url-to-your-torrent'
add_url = "%s?action=add-url&token=%s&s=%s" % (theurl, token, torrent_url)
print add_url
pagehandle = urllib2.urlopen(add_url)
# added the URL
print pagehandle.read()

Thanks to all those who helped!

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...