3

I am learning Python and am working with the API for MediaFire and trying to just automate some simple processes. But I am running into a bit of confusion after I pass the POST to get the Session Token. The problem is that I am not sure how to extract the token from the response. Here is the call to get the session token:

import hashlib
import time
import urllib.request

token = hashlib.sha1()
token.update("calvinrock0406@gmail.comheaven3610255k592k2di4u9uok3e8u9pkfepjfoc809kfutv5z".encode('utf-8'))
token_dig = token.hexdigest()

with urllib.request.urlopen("https://www.mediafire.com/api/user/get_session_token.php?application_id=36102&signature=" + token_dig + "&[email protected]&password=heaven&token_version=2&response_format=json") as response:
    html = response.read()

And here is the responce I get back from the call:

b'{"response":{"action":"user\\/get_session_token","session_token":"618679cd5046c48fface93dee366a1a07eacfefc5bce88173d5118bb3f128f539602dc54f6d667825a376bc2f86b41a5b1cbe178cd45dfcb4ddfc8e9652f7c529db233181655ec42","secret_key":"774329384","time":"1454700043.4884","ekey":"a84adbba31f9ae8ef717486616a97c63","pkey":"b4dfdc307d","result":"Success","current_api_version":"1.5"}}'

Any help for the noob would be greatly appreciated

1 Answer 1

6

I would recommend using requests instead of urllib, and use json() to work with the response:

import json
import hashlib
import requests

token = hashlib.sha1()
token.update("calvinrock0406@gmail.comheaven3610255k592k2di4u9uok3e8u9pkfepjfoc809kfutv5z".encode('utf-8'))
token_dig = token.hexdigest()

response = requests.get("https://www.mediafire.com/api/user/get_session_token.php?application_id=36102&signature=" + token_dig + "&[email protected]&password=heaven&token_version=2&response_format=json")

json_response = response.json()
print json_response["response"]["session_token"]
Sign up to request clarification or add additional context in comments.

3 Comments

I put it and gave it a test run and ran into an error, do I need to set a argument to convert to a string? Traceback (most recent call last): File "C:\Users\rhood\Documents\test.py", line 16, in <module> json_response = json.loads(html) File "C:\Users\rhood\AppData\Local\Programs\Python\Python35\lib\json_init_.py", line 312, in loads s.__class__.__name__)) TypeError: the JSON object must be str, not 'bytes'
loads takes a string as an input
You can simplify further by using response.json() instead of json.loads(response.text)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.