# jnet - library for requesting json # Version: 0.0.4 import json import socket import urllib.error import urllib.parse import urllib.request JSONType = "application/json" # Request JSON from a web resource. # Only returning an object if there is application/json data. def requestJson(uri, params=None, extras={}): res = None reqUri = uri if params: reqUri += "?" + urllib.parse.urlencode(params) method = "GET" if "method" in extras: method = extras['method'] headers = {"user-agent": "alpha/jnet"} if "headers" in extras: headers.update(extras['headers']) try: if "payload" in extras: req = urllib.request.Request(reqUri, method=method, data=extras['payload'], headers=headers) res = urllib.request.urlopen(req, None, 60) else: req = urllib.request.Request(reqUri, method=method, headers=headers) res = urllib.request.urlopen(req, None, 60) except socket.timeout: print("JNet: Timeout.") return None except urllib.error.HTTPError as exception: res = exception content = res.read() contentType = res.getheader("content-type", "") res = None if contentType.startswith(JSONType): res = json.loads(content) return res