def _resume(attributes): ''' Pauses a VM. @param attributes: the dictionary of the attributes that will be used to pause a virtual machine @type attributes: dict ''' vm = _get_VM(attributes) if _get_status(attributes) == "PAUSED": conn = Connection(attributes["cm_nova_url"], username="", password="") tenant_id, x_auth_token = _get_keystone_tokens(attributes) body = '{"unpause": null}' headers = {"Content-type": "application/json", "x-auth-token": x_auth_token.encode()} uri = tenant_id + "/servers/" + vm['id'] + "/action" resp = conn.request_post(uri, body=body, headers=headers) status = resp[u'headers']['status'] if status == '200' or status == '304' or status == '202': log.info("VM is unpaused and status is %s" % _get_status(attributes)) else: log.error("_resume: Bad HTTP return code: %s" % status) else: raise ResourceException("The VM must be paused") return _get_status(attributes)
def submit_rdfxml_from_url(self, url_to_file, headers={"Accept": "application/rdf+xml"}): """Convenience method - downloads the file from a given url, and then pushes that into the meta store. Currently, it doesn't put it through a parse-> reserialise step, so that it could handle more than rdf/xml on the way it but it is a future possibility.""" import_rdf_connection = Connection(url_to_file) response = import_rdf_connection.request_get("", headers=headers) if response.get('headers') and response.get('headers').get( 'status') in ['200', '204']: request_headers = {} # Lowercase all response header fields, to make matching easier. # According to HTTP spec, they should be case-insensitive response_headers = response['headers'] for header in response_headers: response_headers[header.lower()] = response_headers[header] # Set the body content body = response.get('body').encode('UTF-8') # Get the response mimetype rdf_type = response_headers.get('content-type', None) return self._put_rdf(body, mimetype=rdf_type)
def __init__(self, conn=None): if not conn: self.conn = Connection(GENERAL_PARAMETERS['base_url'], username=GENERAL_PARAMETERS['username'], password=GENERAL_PARAMETERS['password']) else: self.conn = conn
def _set_flavor(attributes, vm_id, current_flavor, new_flavor): vm_status = _get_status(attributes) conn = Connection(attributes["cm_nova_url"], username="", password="") tenant_id, x_auth_token = _get_keystone_tokens(attributes) if (vm_status == 'ACTIVE' and current_flavor != new_flavor): body = '{"resize": {"flavorRef":"'+ new_flavor + '"}}' headers = {"Content-type": "application/json", "x-auth-token": x_auth_token.encode()} uri = tenant_id + "/servers/" + vm_id + "/action" resp = conn.request_post(uri, body=body, headers=headers) status = resp[u'headers']['status'] if status == '200' or status == '304' or status == '202': return _get_flavor(attributes, vm_id) else: log.error("Bad HTTP return code: %s" % status) elif (vm_status == 'RESIZE'): log.error("Wait for VM resizing before confirming action") elif (vm_status == 'VERIFY_RESIZE'): body = '{"confirmResize": null}' headers = {"Content-type": "application/json", "x-auth-token": x_auth_token.encode()} uri = tenant_id + "/servers/" + vm_id + "/action" resp = conn.request_post(uri, body=body, headers=headers) status = resp[u'headers']['status'] if status == '200' or status == '304' or status == '202': return _get_flavor(attributes, vm_id) else: log.error("_set_flavor: Bad HTTP return code: %s" % status) else: log.error("Wrong VM state or wring destination flavor")
def _delete_VM(attributes): conn = Connection(attributes["cm_nova_url"], username="", password="") tenant_id, x_auth_token = _get_keystone_tokens(attributes) vm = _get_VM(attributes) vm_id = vm['id'] resp = conn.request_delete("/" + tenant_id +"/servers/" + vm_id, args={}, headers={'content-type':'application/json', 'accept':'application/json', 'x-auth-token':x_auth_token}) return _get_status(attributes)
def handle(self, request, data): print "++++++++++++ ////////////// data = %s" % data uri = request.get_full_path() match = re.search('/project/ipsec/([^/]+)/preaddlink/', uri) vpn_id = match.group(1) print "++++++++++++ ////////////// RBA RBA vpn_id = %s" % vpn_id self.p_tk = request.user.token.id try: messages.success( request, _("Link in process of establishement... Pushing low level network configuration..." )) pgsplit = re.split(r'\.', str(data['p_gw'])) self.p_site = pgsplit[0] + '.' + pgsplit[1] egsplit = re.split(r'\.', str(data['e_gw'])) self.e_site = egsplit[0] + '.' + egsplit[1] print "++++++ data to plugin : vpn=%s, psite=%s, pgw=%s, pnets=%s, ptk=%s, esite=%s, egw=%s, enets=%s, etk=%s, bw=%s" % ( vpn_id, self.p_site, data['p_gw'], data['p_nets'], self.p_tk, self.e_site, data['e_gw'], data['e_nets'], self.e_tk, data['bw']) # should use a modular client below once it supports complex jsons: #api.elasticnet.elasticnet_add_link(request, vpn_id, self.p_site, str(data['p_gw']) , str(data['p_nets']), self.p_tk, self.e_site, str(data['e_gw']) , str(data['e_nets']), self.e_tk, str(data['bw'])) if str(request.user.username).startswith("acme"): o = urlparse.urlparse(url_for(request, "ipsecvpn")) else: o = urlparse.urlparse(url_for(request, "vpn")) conn0 = Connection("http://" + str(o.hostname) + ":9797", "ericsson", "ericsson") uri0 = "/v1.0/tenants/acme/networks/" + str(vpn_id) + "/links.json" LOG.debug("http://" + str(o.hostname) + ":9797") LOG.debug(uri0) header = {} header["Content-Type"] = "application/json" jsonbody='{"sites": [{"id":"'+str(self.p_site)+'", "gateway":"'+ str(data['p_gw']) +'", "network":"'+ str(data['p_nets']) +'", "token_id":"'+str(self.p_tk)+ '"}, {"id":"' \ + str(self.e_site)+'", "gateway":"'+ str(data['e_gw']) +'", "network":"'+ str(data['e_nets']) +'", "token_id":"'+str(self.e_tk)+ '"}], "qos":{"bandwidth":"' \ + str(data['bw'])+'", "eir":"'+ str(data['eir'])+ '", "cbs":"'+ str(data['cbs'])+ '", "pbs":"'+ str(data['pbs'])+ '"}}' print "+++ ewan result json body =%s" % jsonbody result = conn0.request_post(uri0, body=jsonbody, headers=header) print "+++ ewan result body =%s" % result["body"] body = json.loads(result["body"]) print "+++ewan body=%s" % body linkid = str(body['link']['id']) print "+++ewan linkid=%s" % linkid messages.success(request, _("Link added successfully.")) shortcuts.redirect("horizon:project:ipsec:index") return True except Exception as e: msg = _( 'Failed to authorize Link from remote Enterprise Site crendentials : %s' ) % e.message LOG.info(msg) return shortcuts.redirect("horizon:project:ipsec:index")
def _get_images(attributes): conn = Connection(attributes["cm_nova_url"], username="", password="") tenant_id, x_auth_token = _get_keystone_tokens(attributes) resp = conn.request_get("/" + tenant_id + "/images", args={}, headers={'content-type':'application/json', 'accept':'application/json', 'x-auth-token':x_auth_token}) status = resp[u'headers']['status'] if status == '200' or status == '304': images = json.loads(resp['body']) return images['images'] else: log.error("_get_images: Bad HTTP return code: %s" % status)
def handle(self, request, data): print "++++++++++++ ////////////// data = %s" % data uri = request.get_full_path() match = re.search('/project/vpns/([^/]+)/autoburst/', uri) vpn_id = match.group(1) print "++++++++++++ ////////////// RBA RBA vpn_id = %s" % vpn_id self.p_tk = request.user.token.id try: messages.success( request, _("AutoBurst is enabled on the remote VMs using this elastic wan..." )) pgsplit = re.split(r'\.', str(data['p_gw'])) self.p_site = pgsplit[0] + '.' + pgsplit[1] egsplit = re.split(r'\.', str(data['e_gw'])) self.e_site = egsplit[0] + '.' + egsplit[1] # should use a modular client below once it supports complex jsons: #api.elasticnet.elasticnet_add_link(request, vpn_id, self.p_site, str(data['p_gw']) , str(data['p_nets']), self.p_tk, self.e_site, str(data['e_gw']) , str(data['e_nets']), self.e_tk, str(data['bw'])) if str(request.user.username).startswith("acme"): o = urlparse.urlparse(url_for(request, "ipsecvpn")) else: o = urlparse.urlparse(url_for(request, "vpn")) conn0 = Connection("http://" + str(o.hostname) + ":9797", "ericsson", "ericsson") uri0 = "/v1.0/tenants/acme/networks/" + str(vpn_id) + "/links.json" LOG.debug("http://" + str(o.hostname) + ":9797") LOG.debug(uri0) bw = None header = {} header["Content-Type"] = "application/json" jsonbody='{"sites": [{"id":"'+str(self.p_site)+'", "gateway":"'+ str(data['p_gw']) +'", "network":"'+ str(data['p_nets']) +'", "token_id":"'+str(self.p_tk)+ '"}, {"id":"' \ + str(self.e_site)+'", "gateway":"'+ str(data['e_gw']) +'", "network":"'+ str(data['e_nets']) +'", "token_id":"'+str(self.e_tk)+ '"}], "qos":{"bandwidth":"' \ + str(bw)+'"}, "usecase":{"action":"autoburst", "vmuuid":"' \ + str(data['e_servers'])+'", "vmtenantid":"'+str(self.vmtenantid)+'", "vmsla":"'+str(data['sla'])+'"}}' print "+++ ewan result json body =%s" % jsonbody result = conn0.request_post(uri0, body=jsonbody, headers=header) print "+++ ewan result body =%s" % result["body"] body = json.loads(result["body"]) print "+++ewan body=%s" % body linkid = str(body['link']['id']) print "+++ewan linkid=%s" % linkid messages.success(request, _("Link added successfully.")) shortcuts.redirect("horizon:project:vpns:index") return True except Exception as e: msg = _( 'Failed to authorize Link from remote Enterprise Site crendentials : %s' ) % e.message LOG.info(msg) return shortcuts.redirect("horizon:project:vpns:index")
def _get_keystone_tokens(attributes): conn = Connection(attributes["cm_keystone_url"]) body = '{"auth": {"tenantName":"'+ attributes["cm_tenant_name"] + '", "passwordCredentials":{"username": "******"cm_username"] + '", "password": "******"cm_password"] + '"}}}' resp = conn.request_post("/tokens", body=body, headers={'Content-type':'application/json'}) status = resp[u'headers']['status'] if status == '200' or status == '304': data = json.loads(resp['body']) tenant_id = data['access']['token']['tenant']['id'] x_auth_token = data['access']['token']['id'] return tenant_id, x_auth_token else: log.error("_get_keystone_tokens: Bad HTTP return code: %s" % status)
def getBusesPositions(self): lcord = [] conn = Connection("http://mc933.lab.ic.unicamp.br:8017/onibus") response = conn.request_get("") buses = json.loads(response["body"]) for i in buses: response = conn.request_get(str(i)) lcord.append(json.loads(response["body"])) #conn.request_put("/sidewinder", {'color': 'blue'}, headers={'content-type':'application/json', 'accept':'application/json'}) return lcord
def _create_VM(res_id, attributes, dict_vm): conn_nova = Connection(attributes["cm_nova_url"], username="", password="") tenant_id, x_auth_token = _get_keystone_tokens(attributes) body = '{"server": {"name":"'+ dict_vm['name'].encode() + '", "imageRef":"' + dict_vm['image'].encode() + '", "key_name": "' + dict_vm['key'].encode() + '", "user_data":"' + dict_vm['user-data'] + '", "flavorRef":"' + dict_vm['flavor'] + '", "max_count": 1, "min_count": 1, "security_groups": [{"name": "default"}]}}' headers = {"Content-type": "application/json", "x-auth-token": x_auth_token.encode()} uri = tenant_id + "/servers" resp = conn_nova.request_post(uri, body=body, headers=headers) status = resp[u'headers']['status'] if status == '200' or status == '304': data = json.loads(resp['body']) return _get_status(attributes) else: log.error("_create_VM: Bad HTTP return code: %s" % status)
def __init__(self, base_store_url, username=None, password=None): """ Base URL for the store should be pretty self-explanatory. E.g. something like "http://api.talis.com/stores/store_name" Only needs to enter the username/password if this class is going to tinker with things.""" if base_store_url.endswith('/'): base_store_url = base_store_url[:-1] self.base_store_url = base_store_url # Split the given URL if base_store_url: self.conn = Connection(base_store_url, username=username, password=password)
def _get_VMs(attributes): conn = Connection(attributes["cm_nova_url"], username="", password="") tenant_id, x_auth_token = _get_keystone_tokens(attributes) resp = conn.request_get("/" + tenant_id +"/servers", args={}, headers={'content-type':'application/json', 'accept':'application/json', 'x-auth-token':x_auth_token}) status = resp[u'headers']['status'] if status == '200' or status == '304': servers = json.loads(resp['body']) i = 0 vms = [] for r in servers['servers']: vms.append(r['name']) i = i+1 return vms else: log.error("_get_VMs: Bad HTTP return code: %s" % status)
def _get_VM(attributes): conn = Connection(attributes["cm_nova_url"], username="", password="") tenant_id, x_auth_token = _get_keystone_tokens(attributes) resp = conn.request_get("/" + tenant_id +"/servers/detail", args={}, headers={'content-type':'application/json', 'accept':'application/json', 'x-auth-token':x_auth_token}) status = resp[u'headers']['status'] found = 0 if status == '200' or status == '304': servers = json.loads(resp['body']) for vm in servers['servers']: if attributes['name'] == vm['name']: found = 1 return vm if found == 0: #return False raise ResourceException("vm %s not found" % attributes['name']) else: log.error("_get_VM: Bad HTTP return code: %s" % status)
def test_rest(myLat, myLng): # http://api.spotcrime.com/crimes.json?lat=40.740234&lon=-73.99103400000001&radius=0.01&callback=jsonp1339858218680&key=MLC spotcrime_base_url = "http://api.spotcrime.com" conn = Connection(spotcrime_base_url) resp = conn.request_get("/crimes.json", args={ 'lat': myLat, 'lon': myLng, 'radius': '0.01', 'key': 'MLC' }, headers={'Accept': 'text/json'}) resp_body = resp["body"] return resp_body
def _get_flavor(attributes, vm_id): conn = Connection(attributes["cm_nova_url"], username="", password="") tenant_id, x_auth_token = _get_keystone_tokens(attributes) resp = conn.request_get("/" + tenant_id +"/servers/" + vm_id, args={}, headers={'content-type':'application/json', 'accept':'application/json', 'x-auth-token':x_auth_token}) status = resp[u'headers']['status'] if status == '200' or status == '304': server = json.loads(resp['body']) flavor_id = server['server']['flavor']['id'] else: log.error("Bad HTTP return code: %s" % status) resp = conn.request_get("/" + tenant_id +"/flavors/" + flavor_id, args={}, headers={'content-type':'application/json', 'accept':'application/json', 'x-auth-token':x_auth_token}) status = resp[u'headers']['status'] if status == '200' or status == '304': flavor = json.loads(resp['body']) else: log.error("_get_flavor: Bad HTTP return code: %s" % status) return flavor['flavor']
def main(): logging.basicConfig(level=logging.DEBUG) try: os.remove('out.sqlite3') except OSError as e: if e.errno != 2: raise db = create_database('out.sqlite3') logging.info('requesting new topic tree...') base_url = 'http://www.khanacademy.org/api/v1/' conn = Connection(base_url) response = conn.request_get('/topictree') logging.info('parsing json response...') tree = json.loads(response.get('body')) logging.info('writing to file...') with open('../topictree', 'w') as f: f.write(json.dumps(tree)) logging.info('loading topic tree file...') with open('../topictree', 'r') as f: tree = json.loads(f.read()) # stick videos in one list and topics in another for future batch insert topics = [] videos = [] topicvideos = [] logging.info('parsing tree...') parse_topic(tree, '', topics, videos, topicvideos) logging.info('inserting topics...') insert_topics(db, topics) logging.info('inserting videos...') insert_videos(db, videos) logging.info('inserting topicvideos...') insert_topicvideos(db, topicvideos) db.commit() logging.info('done!')
def sendPost(serviceId, instanceId, monitoringEndpoint, kpiName, value): timestamp = time.mktime(datetime.now().timetuple()) #UTC-Seconds timestamp = long(timestamp) conn = Connection(monitoringEndpoint) response = conn.request_post("/data/" + serviceId, args={ "serviceId": serviceId, "instanceid": instanceId, "kpiName": kpiName, "value": value, "timestamp": timestamp }) print "Response: ", response status = response.get('headers').get('status') if status not in ["200", 200, "204", 204]: print >> sys.stderr, "Call failed, status:", status return False print "Call successful" return True
def trans(): base_url = "https://partunlimited.demo.triggermesh.io:8080/api" # The API endpoint for the parts store conn = Connection(base_url) ce = request.get_json(force=True) print(request.data) print(request.headers) ceSource = request.headers['Ce-Source'] headers = {} headers['Ce-Specversion'] = '1.0' headers['Ce-Time'] = request.headers['Ce-Time'] headers['Ce-Id'] = request.headers['Ce-Id'] headers[ 'Ce-Source'] = 'translators.triggermesh.io/partsunlimited-demo-translator' # For events we don't care about, just return if ceSource is not None and not ceSource.startswith( 'tmtestdb.demo.triggermesh.com/'): print("invalid source: " + ceSource) return sink() # Handle the replenishment event by posting a message to Zendesk if ceSource == "tmtestdb.demo.triggermesh.com/replenish": headers['Ce-Type'] = 'com.zendesk.ticket.create' # Need to extract the manufacturer details resp = conn.request_get("/product/" + str(ce["new"]["ID"])) respBody = json.loads(resp[u'body']) if ce["op"] == "UPDATE" and ce["new"]["QUANTITY"] == 1: body = { "subject": "Parts Unlimited Replenishment Request", "body": "It is time to reorder " + respBody["name"] + " from " + respBody["manufacturer"]["manufacturer"] } return app.response_class(response=json.dumps(body), headers=headers, status=200, mimetype='application/json') else: print("invalid replenish") return sink() # Handle the new order event by sending it to an Oracle Cloud function if ceSource == "tmtestdb.demo.triggermesh.com/neworder": headers[ 'Ce-Type'] = 'com.triggermesh.targets.oracle.function.partsunlimited-neworder' # Need to extract the order details resp = conn.request_get("/order/" + str(ce["new"]["ID"])) respBody = json.loads(resp[u'body']) if ce["op"] == "INSERT": body = { "name": respBody["user"]["name"], "address": respBody["user"]["address"], "totalCost": respBody["totalCost"], "paymentMethod": respBody["paymentType"], "ordered": respBody["dateOrdered"] } return app.response_class(response=json.dumps(body), headers=headers, status=200, mimetype='application/json') else: print("invalid neworder") return sink() else: print("unknown source" + ceSource) return sink()
def _get_associated_data(self, resource): '''Calls the rest api to get the associated data for the run''' return self._ts_json_get('%s?format=json' % resource) def _ts_json_get(self, resource): ''' do a rest get, throw a TsConnectionError if a 200 is not returned or anything else goes wrong ''' try: print 'in _ts_json_get' response = self.connection.request_get(resource) if str(response['headers']['status']) != str(200): raise TsConnectionError() json_obj = json.loads('[%s]' % response[u'body'])[0] print "resource is: %s, got back json:\n%s" % \ (resource, str(json.dumps(json_obj, sort_keys=True, indent=4, separators=(',', ': ')))) return json_obj except: raise TsConnectionError() if __name__ == "__main__": PLUGIN_CONFIG = _get_plugin_config(sys.argv[1]) PLUGIN_INSTANCE_DATA = _get_plugin_instance_data(sys.argv[2]) RR_CONFIG = RunRecognitionPluginConfig(PLUGIN_CONFIG, PLUGIN_INSTANCE_DATA) TS_CONN = Connection(RR_CONFIG.torrent_server_api_url, RR_CONFIG.torrent_server_api_username, RR_CONFIG.torrent_server_api_password) LB_CONN = Connection(RR_CONFIG.guru_api_url) LB_CONN.h.disable_ssl_certificate_validation = True gather_and_send_data(RR_CONFIG, TS_CONN, LB_CONN)
from rpc_class import coinrpc from restful_lib import Connection from bitcoinrpc.authproxy import AuthServiceProxy # get bitcoin rpc config bitcoinrpc = coinrpc("../../bitcoin-0.10.2/bitcoin/bitcoin.conf").rpccon() # get litecoin rpc config litecoinrpc = coinrpc("../../litcoin-xxx/bitcoin/bitcoin.conf").rpccon() # make a new bitcoin address to receive the shifted funds newaddress = bitcoinrpc.getnewaddress() # connect to shapeshift API base_url = "https://shapeshift.io" conn = Connection(base_url) # change litecoin to bitcoin post_data = {"withdrawal": newaddress, "pair": "ltc_btc"} btc_shift = conn.request_post("/shift/", post_data) for item in btc_shift: if item == "body": response = json.loads(btc_shift[item]) for key, value in response.iteritems(): if key == "deposit": depositaddr = value # send to deposit address litecoinrpc.sendtoaddress(depositaddr, 10)
def __init__(self, username, password): self._conn = Connection(TWITTER_ENDPOINT, username, password)
__author__ = 'chywoo.park' import sys sys.path.append("../python_rest_client") import json from restful_lib import Connection base_url = "http://jira.score/rest/api/latest" conn = Connection(base_url, username="******", password="******") res = conn.request("/issue/TS-17952", headers={ 'Authorization': 'Basic Y2h5d29vLnBhcms6dGl6ZW5zZGsqMTA=', 'Content-type': 'application/json', 'Accept': 'application/json' }, args={}) if res[u'headers']['status'] != "200": print("Fail to get issue data") exit(1) body = json.loads(res[u'body']) print(body.keys()) print("Key: " + body[u'key']) # print("Status: %s\n" % res[u'headers']['status'])
# # Implementation of views # from flask import g, render_template, request, jsonify, Response from restful_lib import Connection from ast import literal_eval import json, re from main import app # connection to FMRD result web service base_url = "http://fmrdlight.herokuapp.com" result = Connection(base_url) # # error handling # @app.errorhandler(400) def bad_request(error=None): message = {'status': 400, 'message': "Bad request."} resp = jsonify(message) resp.status_code = 400 return resp
#!/usr/bin/python from restful_lib import Connection conn = Connection("http://localhost:8888") response = conn.request_get("/getNearestBusStops?lat=-22.8177;lon=-47.0683") print response['body'] conn.request_put("/sidewinder", {'color': 'blue'}, headers={'content-type':'application/json', 'accept':'application/json'})
#!/usr/bin/python import time import csv import simplejson as json from restful_lib import Connection #conn = Connection("http://mc933.lab.ic.unicamp.br:8010") while 1: #mc933.lab.ic.unicamp.br #response = conn.request_get("/getPosition") try: conn = Connection("http://mc933.lab.ic.unicamp.br/getBusesPositions") response = conn.request_get("") except: print "Connection failed: waiting 10 seconds" time.sleep(10) continue buses = json.loads(response["body"]) try: f = open('positions.csv') read = csv.reader(f) #for row in read: # txt+= str(row) + "</br>" #return txt) # 0 - systemDatetime # 1 - moduleDatetime # 2 - licensePlate # 3 - latitude # 4 - longitude
base_url = os.getenv("BASEURL") if base_url is None: base_url = _testConf.get('DEFAULT', 'BaseURL') secure_url = os.getenv("SECUREURL") if secure_url is None: secure_url = _testConf.get('DEFAULT', 'SecureURL') user_tag = _testConf.get('DEFAULT', 'tagUsername') user_prop = _testConf.get('DEFAULT', 'propUsername') user_prop2 = _testConf.get('DEFAULT', 'propUsername2') user_chan = _testConf.get('DEFAULT', 'channelUsername') user_chan2 = _testConf.get('DEFAULT', 'channelUsername2') user_admin = _testConf.get('DEFAULT', 'username') conn_none = Connection(base_url) conn_none_secure = Connection(secure_url) conn_tag = Connection(secure_url, username=user_tag, \ password=_testConf.get('DEFAULT', 'tagPassword')) conn_tag_plain = Connection(base_url, username=user_tag, \ password=_testConf.get('DEFAULT', 'tagPassword')) conn_prop = Connection(secure_url, username=user_prop, \ password=_testConf.get('DEFAULT', 'propPassword')) conn_prop_plain = Connection(base_url, username=user_prop, \ password=_testConf.get('DEFAULT', 'propPassword')) conn_prop2 = Connection(secure_url, username=user_prop2, \ password=_testConf.get('DEFAULT', 'propPassword2')) conn_chan = Connection(secure_url, username=user_chan, \ password=_testConf.get('DEFAULT', 'channelPassword')) conn_chan_plain = Connection(base_url, username=user_chan, \ password=_testConf.get('DEFAULT', 'channelPassword'))
def __init__(self): base_url = settings.get('API_BASE_URL') self.conn = Connection(base_url) self.output = open('items', 'w')
def __init__(self): # In this example we use rest client provided by # http://code.google.com/p/python-rest-client/ # Of course you are free to use any other client. self._connection = Connection(self.BASE_HOST)
##REST API of Kegg from http://exploringlifedata.blogspot.com/ #Python 3.6.5 |Anaconda, Inc. import collections from restful_lib import Connection kegg_url = "http://rest.kegg.jp" conn = Connection(kegg_url) data = conn.request_get('list/ko', headers={'Accept': 'text/json'}) print(data['headers']) print(type(data['body']))