• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python restful_lib.Connection类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中restful_lib.Connection的典型用法代码示例。如果您正苦于以下问题:Python Connection类的具体用法?Python Connection怎么用?Python Connection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Connection类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:UshiDesign,项目名称:synapse-agent,代码行数:27,代码来源:cm_openstack.py


示例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']
开发者ID:smielgo99,项目名称:testRepo,代码行数:35,代码来源:client.py


示例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")
开发者ID:UshiDesign,项目名称:synapse-agent,代码行数:28,代码来源:cm_openstack.py


示例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
开发者ID:stuross,项目名称:py-livefyre-client,代码行数:8,代码来源:__init__.py


示例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)
开发者ID:UshiDesign,项目名称:synapse-agent,代码行数:8,代码来源:cm_openstack.py


示例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())
开发者ID:bmjames,项目名称:diffa-console,代码行数:8,代码来源:client.py


示例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)
开发者ID:UshiDesign,项目名称:synapse-agent,代码行数:10,代码来源:cm_openstack.py


示例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)
开发者ID:UshiDesign,项目名称:synapse-agent,代码行数:12,代码来源:cm_openstack.py


示例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
开发者ID:andreterron,项目名称:Mobile,代码行数:12,代码来源:server.py


示例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)
开发者ID:bmjames,项目名称:diffa-console,代码行数:53,代码来源:client.py


示例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)
开发者ID:UshiDesign,项目名称:synapse-agent,代码行数:13,代码来源:cm_openstack.py


示例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")
开发者ID:mssumanth,项目名称:Temp,代码行数:50,代码来源:forms.py


示例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
开发者ID:miriammelnick,项目名称:dont-get-mugged,代码行数:15,代码来源:demo.py


示例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)
开发者ID:UshiDesign,项目名称:synapse-agent,代码行数:15,代码来源:cm_openstack.py


示例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
开发者ID:vladdie,项目名称:optimistoolkit,代码行数:15,代码来源:restclient.py


示例16: __init__

	def __init__(self, api_key, username, password):
		self.username = username
		login_username = api_key + "%" + username

		connection_base = CTCTConnection.API_BASE_URL + username + "/"

		self.connection = Connection(connection_base, username=login_username, password=password)
开发者ID:ChaosDevelopment,项目名称:lockitfuel,代码行数:7,代码来源:__init__.py


示例17: LocalClient

class LocalClient(object):
    '''
    classdocs
    '''


    def __init__(self):
        '''
        Constructor
        '''
        self.ip="localhost"
        self.port="81"
        self.protocol="http"
        self.path="/nes_server"
         
        
    def set_connection(self):
        self.base_url= self.protocol + "://" + self.ip +":"+ str(self.port) + self.path
        self.conn = Connection(self.base_url)
        
    def create_subscription(self, json_data):
        response = self.conn.request_post("/subs.json")
        response['headers']['location']="http://212.179.159.77/nesphase2/nes/subscriptions/1234567891321"
        return response['headers']['status'],response['headers']['location'], response['body']

    def delete_subscription(self, correlators_list):
        
        return 200, "{}"    
开发者ID:smielgo99,项目名称:testRepo,代码行数:28,代码来源:client.py


示例18: _get_VM

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)
开发者ID:UshiDesign,项目名称:synapse-agent,代码行数:17,代码来源:cm_openstack.py


示例19: _get_flavor

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']
开发者ID:UshiDesign,项目名称:synapse-agent,代码行数:17,代码来源:cm_openstack.py


示例20: __init__

class Server:

    def __init__(self, root_url="http://led-o-matic.appspot.com"):
    	self.root_url = root_url
    	self.conn = Connection(self.root_url)
    	self.name = ""

    def getPinStatus(self, pins_name, pin_id):
        request = self.name + '/' + pins_name + '/' + pin_id
        response = self.conn.request_get(request)
        return response['body']
  

    def login(self, name):
		self.name = name
		response = self.conn.request_post('/' + name)
		return self.root_url + '/' + self.name + response['body']
开发者ID:dipeshkumar,项目名称:ledomatic,代码行数:17,代码来源:server.py



注:本文中的restful_lib.Connection类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python retrieval.get_repo函数代码示例发布时间:2022-05-26
下一篇:
Python test.get_mock_resource函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap