Search code examples
pythonhttplib

Change httplib to http.client


I got error 'No module named httplib'. Then I replaced httplib to http.client. I used 2to3 and added b before secret_key.

import http.client
import urllib.request, urllib.parse, urllib.error
import json
import hashlib
import hmac
from collections import OrderedDict
import time

server = "api.---.net"
api_key = "---"
secret_key = b"---"


def get(url):
     conn = http.client.HTTPSConnection(server)
     conn.request("GET", url)
     response = conn.getresponse()
     data = json.load(response)
     return data

def post(url, params):
     conn = http.client.HTTPSConnection(server)
     data = OrderedDict(sorted(params))
     encoded_data = urllib.parse.urlencode(data)
     sign = hmac.new(secret_key, msg=encoded_data, digestmod=hashlib.sha256).hexdigest().upper()
     headers = {"Api-key": api_key, "Sign": sign, "Content-type": "application/x-www-form-urlencoded"}
     conn.request("POST", url, encoded_data, headers)

def com():
     conn = http.client.HTTPSConnection(server)
     sign = hmac.new(secret_key, b'', digestmod=hashlib.sha256).hexdigest().upper()
     headers = {"Api-key": api_key, "Sign": sign, "Content-type": "application/x-www-form-urlencoded"}
     conn.request("GET", "/ex/com", None, headers) 

Now I get error

'NoneType' object is not subscriptable


Traceback (most recent call last):
  File "lc.py", line , in <module>
    COM = float(com()['fee'])
TypeError: 'NoneType' object is not subscriptable

Solution

  • The function com() returns nothing (that is, a None). On return, you attempt to apply the selection operator to None (['fee']), which would work only if com() returned a dictionary.