Search code examples
pythonpython-requestsutorrent

Add torrent with web api


I'm trying to add a torrent with uTorrent web api (http://www.utorrent.com/community/developers/webapi), in Python using Requests library.

import requests
import re

UTORRENT_URL = 'http://%s:%s/gui/' % ('localhost', '55655')
UTORRENT_URL_TOKEN = '%stoken.html' % UTORRENT_URL
REGEX_UTORRENT_TOKEN = r'<div[^>]*id=[\"\']token[\"\'][^>]*>([^<]*)</div>'


auth = requests.auth.HTTPBasicAuth('x', 'x')
headers = {'content-type': 'application/json'}
r = requests.get(UTORRENT_URL_TOKEN, auth=auth, headers=headers)
token = re.search(REGEX_UTORRENT_TOKEN, r.text).group(1)
guid = r.cookies['GUID']
cookies = dict(GUID = guid)

headers = {'content-type': 'multipart/form-data'}
params = {'action':'add-file','token': token}
files = {'torrent_file':'C:\\x.torrent'}
r = requests.post(UTORRENT_URL, auth=auth, cookies=cookies, headers=headers, params=params, files=files)
print r.json()

Error - torrent file content not supplied in form parameter

Any help appreciated


Solution

  • Ok, the problem was setting the headers. Removing them and it finally works!

    import requests
    import re
    
    UTORRENT_URL = 'http://%s:%s/gui/' % ('192.168.1.80', '55655')
    UTORRENT_URL_TOKEN = '%stoken.html' % UTORRENT_URL
    REGEX_UTORRENT_TOKEN = r'<div[^>]*id=[\"\']token[\"\'][^>]*>([^<]*)</div>'
    
    auth = requests.auth.HTTPBasicAuth('x', 'x')
    r = requests.get(UTORRENT_URL_TOKEN, auth=auth)
    token = re.search(REGEX_UTORRENT_TOKEN, r.text).group(1)
    guid = r.cookies['GUID']
    cookies = dict(GUID = guid)
    
    params = {'action':'add-file','token': token}
    files = {'torrent_file': open('C:\\x.torrent', 'rb')}
    r = requests.post(url=UTORRENT_URL, auth=auth, cookies=cookies, params=params, files=files)