本文整理匯總了Python中restful_lib.Connection類的典型用法代碼示例。如果您正苦於以下問題:Python Connection類的具體用法?Python Connection怎麽用?Python Connection使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了Connection類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _resume
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)
示例2: NESClient
class NESClient(object):
'''
classdocs
'''
def __init__(self, appId, servId):
'''
Constructor
'''
self.ip="pre.3rd.services.telefonica.es"
self.port="444"
self.protocol="https"
self.path="/services/BA/REST/UCSS/UCSSServer/"
self.appId = appId
self.servId = servId
self.headers = {'appId' : self.appId, 'servId' : self.servId}
def set_connection(self):
self.base_url= self.protocol + "://" + self.ip +":"+ str(self.port) + self.path
self.conn = Connection(self.base_url, username='jajah', password='j4j4h')
def create_subscription(self, json_data):
response = self.conn.request_post("nes/subscriptions/",body=json_data, headers=self.headers)
print "create_subscription"
return response['headers']['status'], response['headers']['location'], response['body']
def delete_subscription(self, correlators_list):
response = self.conn.request_delete("nes/subscriptions?correlators="+correlators_list, headers=self.headers)
print "delete_subscription"
return response['headers']['status'], response['body']
示例3: _set_flavor
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")
示例4: __init__
def __init__(self, domain, domain_key, endpoint=None, user="system", timeout=5, cache_dir=".cache"):
if not endpoint:
endpoint = "http://%s" % domain
Connection.__init__(self, endpoint)
self.domain = domain
self.domain_key = domain_key
self.user = user
self.timeout=timeout
示例5: _delete_VM
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)
示例6: __init__
def __init__(self, agent_url, verbose=False):
self._logger.setLevel(logging.DEBUG if verbose else logging.NOTSET)
if not agent_url.endswith('/'):
agent_url += '/'
self.agent_url = agent_url
base_url = urljoin(agent_url, 'rest')
self._conn = Connection(base_url)
self._conn = Connection(self.get_session_url())
示例7: _get_images
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)
示例8: _get_keystone_tokens
def _get_keystone_tokens(attributes):
conn = Connection(attributes["cm_keystone_url"])
body = '{"auth": {"tenantName":"'+ attributes["cm_tenant_name"] + '", "passwordCredentials":{"username": "' + attributes["cm_username"] + '", "password": "' + attributes["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)
示例9: getBusesPositions
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
示例10: DiffsClient
class DiffsClient(object):
_logger = logging.getLogger('DiffsClient')
_logger.addHandler(logging.StreamHandler(sys.stderr))
def __init__(self, agent_url, verbose=False):
self._logger.setLevel(logging.DEBUG if verbose else logging.NOTSET)
if not agent_url.endswith('/'):
agent_url += '/'
self.agent_url = agent_url
base_url = urljoin(agent_url, 'rest')
self._conn = Connection(base_url)
self._conn = Connection(self.get_session_url())
def get_session_url(self):
url = '/diffs/sessions'
response = self._post(url)
return response['headers']['location']
def get_diffs(self, pair_key, range_start, range_end):
url = '/?pairKey={0}&range-start={1}&range-end={2}'.format(
pair_key,
range_start.strftime(DATETIME_FORMAT),
range_end.strftime(DATETIME_FORMAT))
response = self._get(url)
return json.loads(response['body'])
def get_diffs_zoomed(self, range_start, range_end, bucketing):
"A dictionary of pair keys mapped to lists of bucketed diffs"
url = '/zoom?range-start={0}&range-end={1}&bucketing={2}'.format(
range_start.strftime(DATETIME_FORMAT),
range_end.strftime(DATETIME_FORMAT),
bucketing)
response = self._get(url)
return json.loads(response['body'])
def _get(self, url):
self._logger.debug("GET %s", self._rebuild_url(url))
response = self._conn.request_get(url)
self._logger.debug(response)
return response
def _post(self, url):
self._logger.debug("POST %s", self._rebuild_url(url))
response = self._conn.request_post(url)
self._logger.debug(response)
return response
def _rebuild_url(self, url):
return self._conn.url.geturl() + url
def __repr__(self):
return "DiffsClient(%s)" % repr(self.agent_url)
示例11: _create_VM
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)
示例12: handle
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")
示例13: test_rest
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
示例14: _get_VMs
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)
示例15: sendPost
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