當前位置: 首頁>>代碼示例>>Python>>正文


Python Connection.request_post方法代碼示例

本文整理匯總了Python中restful_lib.Connection.request_post方法的典型用法代碼示例。如果您正苦於以下問題:Python Connection.request_post方法的具體用法?Python Connection.request_post怎麽用?Python Connection.request_post使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在restful_lib.Connection的用法示例。


在下文中一共展示了Connection.request_post方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _set_flavor

# 需要導入模塊: from restful_lib import Connection [as 別名]
# 或者: from restful_lib.Connection import request_post [as 別名]
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,代碼行數:30,代碼來源:cm_openstack.py

示例2: LocalClient

# 需要導入模塊: from restful_lib import Connection [as 別名]
# 或者: from restful_lib.Connection import request_post [as 別名]
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,代碼行數:30,代碼來源:client.py

示例3: _resume

# 需要導入模塊: from restful_lib import Connection [as 別名]
# 或者: from restful_lib.Connection import request_post [as 別名]
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,代碼行數:29,代碼來源:cm_openstack.py

示例4: NESClient

# 需要導入模塊: from restful_lib import Connection [as 別名]
# 或者: from restful_lib.Connection import request_post [as 別名]
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,代碼行數:37,代碼來源:client.py

示例5: DiffsClient

# 需要導入模塊: from restful_lib import Connection [as 別名]
# 或者: from restful_lib.Connection import request_post [as 別名]
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,代碼行數:55,代碼來源:client.py

示例6: _get_keystone_tokens

# 需要導入模塊: from restful_lib import Connection [as 別名]
# 或者: from restful_lib.Connection import request_post [as 別名]
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,代碼行數:14,代碼來源:cm_openstack.py

示例7: _create_VM

# 需要導入模塊: from restful_lib import Connection [as 別名]
# 或者: from restful_lib.Connection import request_post [as 別名]
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,代碼行數:15,代碼來源:cm_openstack.py

示例8: handle

# 需要導入模塊: from restful_lib import Connection [as 別名]
# 或者: from restful_lib.Connection import request_post [as 別名]
    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,代碼行數:52,代碼來源:forms.py

示例9: sendPost

# 需要導入模塊: from restful_lib import Connection [as 別名]
# 或者: from restful_lib.Connection import request_post [as 別名]
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,代碼行數:17,代碼來源:restclient.py

示例10: Chemcaster

# 需要導入模塊: from restful_lib import Connection [as 別名]
# 或者: from restful_lib.Connection import request_post [as 別名]
class Chemcaster(object):
    def __init__(self, username='[email protected]',password='secret'):
        self._conn = Connection(CHEMCASTER_ENDPOINT, username, password)
        
    def post(self, body):
        resp = self._conn.request_post("structures",body=body )
        status= resp.get('headers').get('status') 
        if status not in ["200", 200, "204", 204]:
            print resp
            if status in ["422", 422]:
                resp['body']
                foo=xml.dom.minidom.parseString(resp['body'])
                for e in foo.getElementsByTagName('error'):
                    print e.firstChild.wholeText
            raise FailError
        return resp
開發者ID:rwest,項目名稱:Burcat-PrIMe,代碼行數:18,代碼來源:chemcaster.py

示例11: __init__

# 需要導入模塊: from restful_lib import Connection [as 別名]
# 或者: from restful_lib.Connection import request_post [as 別名]
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,代碼行數:19,代碼來源:server.py

示例12: coinrpc

# 需要導入模塊: from restful_lib import Connection [as 別名]
# 或者: from restful_lib.Connection import request_post [as 別名]
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)
開發者ID:marzig76,項目名稱:bitcoin-scripts,代碼行數:32,代碼來源:shift_example.py

示例13: Client

# 需要導入模塊: from restful_lib import Connection [as 別名]
# 或者: from restful_lib.Connection import request_post [as 別名]
class Client(object):

    version = "0.002001"

    def __init__(self, server, search="/search", index="/index", debug=False, username=False, password=False):

        self.server = server
        self.search = search
        self.index = index
        self.debug = debug
        self.un = username
        self.pw = password

        # docs:
        # http://code.google.com/p/python-rest-client/wiki/Using_Connection
        self.ua = Connection(server)

        # interrogate server
        resp = self.ua.request_get("/")
        # pprint.pprint(resp)
        paths = json.loads(resp["body"])
        self.searcher = Connection(paths["search"])
        self.indexer = Connection(paths["index"], username=username, password=password)
        self.commit_uri = paths["commit"]
        self.rollback_uri = paths["rollback"]
        self.fields = paths["fields"]
        self.facets = paths["facets"]

    def __str__(self):
        return unicode(self).encode("utf-8")

    def __unicode__(self):
        return pprint.pformat(vars(self))

    def _put_doc(self, doc, uri=None, content_type=None):
        # print "adding to index: %s" % doc

        body_buf = ""

        if isinstance(doc, Doc):
            # print "doc isa Dezi.Doc\n"
            body_buf = doc.as_string()
            if uri == None:
                uri = doc.uri
            if content_type == None:
                content_type = doc.mime_type

        elif os.path.isfile(doc):
            f = open(doc, "r")
            body_buf = f.read()
            if uri == None:
                uri = doc

        else:
            # print "doc isa string\n"
            body_buf = doc
            if uri == None:
                raise Exception("uri required")

        server_uri = "/" + uri
        if self.debug:
            print("uri=" + server_uri)
            print("body=%s" % body_buf)

        resp = self.indexer.request_post(server_uri, body=body_buf, headers={"Content-Type": content_type})

        # pprint.pprint(resp)
        return Dezi.Response(resp)

    def add(self, doc, uri=None, content_type=None):
        return self._put_doc(doc, uri, content_type)

    def update(self, doc, uri=None, content_type=None):
        return self._put_doc(doc, uri, content_type)

    def delete(self, uri):
        resp = self.indexer.request_delete(uri)
        return Dezi.Response(resp)

    def commit(self):
        ua = Connection(self.commit_uri, username=self.un, password=self.pw)
        resp = ua.request_post("/")
        return Dezi.Response(resp)

    def rollback(self):
        ua = Connection(self.rollback_uri, username=self.un, password=self.pw)
        resp = ua.request_post("/")
        return Dezi.Response(resp)

    def get(self, **my_args):
        if "q" not in my_args:
            raise Exception("'q' param required")

        resp = self.searcher.request_get("/", args=my_args)
        # pprint.pprint(resp)
        r = Dezi.Response(resp)
        if r.is_success == False:
            self.last_response = r
            return False
        else:
#.........這裏部分代碼省略.........
開發者ID:karpet,項目名稱:dezi-client-python,代碼行數:103,代碼來源:client.py

示例14: rollback

# 需要導入模塊: from restful_lib import Connection [as 別名]
# 或者: from restful_lib.Connection import request_post [as 別名]
 def rollback(self):
     ua = Connection(self.rollback_uri, username=self.un, password=self.pw)
     resp = ua.request_post("/")
     return Dezi.Response(resp)
開發者ID:karpet,項目名稱:dezi-client-python,代碼行數:6,代碼來源:client.py

示例15: commit

# 需要導入模塊: from restful_lib import Connection [as 別名]
# 或者: from restful_lib.Connection import request_post [as 別名]
 def commit(self):
     ua = Connection(self.commit_uri, username=self.un, password=self.pw)
     resp = ua.request_post("/")
     return Dezi.Response(resp)
開發者ID:karpet,項目名稱:dezi-client-python,代碼行數:6,代碼來源:client.py


注:本文中的restful_lib.Connection.request_post方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。