示例#1
0
    def deleteRequestInfo(self, url, isNeedReturnValue=False):
        """
        执行相应的删除请求操作
        @url 请求的url信息,
        @isNeedReturnValue 执行完操作时,是否需要返回相应的信息
        """
        try:
            if not self.currentTenantName or self.currentTenantName != self._tenant_name:
                self.getAuthToken()
                request = requests.delete(self.getServiceURL(url), headers=self.headers)
            else:
                request = requests.delete(self.getServiceURL(url),headers=self.headers)
                if not request.ok and request.content == common.authFailMsg:
                    self.getAuthToken()
                    request = requests.delete(self.getServiceURL(url), headers=self.headers)
                 
            if not request.ok:
#                 print request.content
                log.logger.error("Delete request failed: %s, url: %s" % (request.content, url))
                raise RequestError(url + " " + request.content)  
            
            if request.ok and isNeedReturnValue:
                return request.json()
            
            if request.ok and not isNeedReturnValue:
                return True
            
        except requests.exceptions.ConnectionError, e:
            log.logger.error("Delete request connect failed, url: %s" % url)
            raise RequestConnectError(e.msg)
示例#2
0
 def getAuthToken(self):
     """
     获取认证
     """
   
     urlPath = "http://" + self._host + ":5000/v2.0/tokens"
     payload = {
                 "auth": {
                     "tenantName": self._tenant_name,
                     "passwordCredentials": {
                         "username":self._username,
                         "password":self._password,
                                              }
                                 }
                     }
     
     try:
         r = requests.post(urlPath, data=json.dumps(payload), headers=self.headers)
         if r.ok:
             self.currentTenantName = self._tenant_name
             infoDict = r.json()
             self.setOpenstackServiceHost(infoDict)
             self.headers.update({'X-Auth-Token': infoDict["access"]["token"]["id"]})
             return infoDict
         else:
             raise RequestError(urlPath + " " + r.content)
     except requests.exceptions.ConnectionError, e:
         raise RequestConnectError(e.msg)
示例#3
0
 async def _request(self, http_request):
     try:
         self._response.response = await http_request()
         self._response.text = await self._response.response.text()
     except aiohttp.ClientError as error:
         self._response.error = error
     except TimeoutError as e:
         raise RequestError(f'Call url timeout: {e}')
示例#4
0
文件: friends.py 项目: windann/5_sem
 def response_handler(self, response):
     ret = None
     try:
         data = json.loads(response.text)
         data = data['response']
     except:
         raise RequestError('Bad request')
     else:
         return data
示例#5
0
    def call(self, func, args):
        start_time = time.time()
        log.info("Calling: %s" % (func))
        call = {func: args}
        headers = {
            'Content-Type': 'application/json',
            'appname': self.app_name,
        }

        cookie = {
            'beaker.session.id': self.session_id,
            'appname:': self.app_name
        }
        r = requests.post(self.url,
                          data=json.dumps(call),
                          headers=headers,
                          cookies=cookie)

        if not r.ok:
            try:
                resp = json.loads(r.content)
                err = "%s:%s" % (resp['faultcode'], resp['faultstring'])
            except:
                log.debug("Headers: %s" % headers)
                log.debug("Url: %s" % self.url)
                log.debug("Content: %s" % json.dumps(call))

                if r.content != '':
                    err = r.content
                else:
                    err = "An unknown server has occurred."

                if self.url.find('soap') > 0:
                    log.info(
                        'The URL %s contains "soap". Is the wrong URL being used?',
                        self.url)
                    err.append(
                        ' -- A shot in the dark: the URL contains the word "soap".'
                        + ', but this is a JSON-based plugin.' +
                        ' Perhaps the wrong URL is being specified?')

            raise RequestError(err)

        if self.session_id is None:
            self.session_id = r.cookies['beaker.session.id']
            log.info(self.session_id)

        ret_obj = json.loads(r.content, object_hook=object_hook)

        log.info('done (%s)' % (time.time() - start_time, ))

        return ret_obj
示例#6
0
 def _post(self, url, data):
     resp = requests.post(url, data=data, headers=self.HEADERS)
     status_code = resp.status_code
     if status_code != 200:
         if status_code == 403:
             raise RuntimeError(
                 "403 Forbidden: Server must be configured for REST")
         msg = resp.json()["message"]
         if resp.status_code < 500:
             raise RequestError(resp.status_code, msg)
         else:
             raise GremlinServerError(resp.status_code, msg)
     return resp
示例#7
0
    def getRequestInfo(self, url):
        """
        获取请求的信息
        @url 请求的url信息
        """
        try:
            request = requests.get(self.getServiceURL(url),
                                   headers=self._headers,
                                   verify=False)
            if request.ok:
                return request.json()
            else:
                log.logger.error("RequestError" + url + " " + request.content)
                raise RequestError(url + " " + request.content)

        except requests.exceptions.ConnectionError, e:
            raise CServerConnectionError()
示例#8
0
 def putRequestInfo(self, url, info, isNeedReturnValue=False):
     try:
         if not self.currentTenantName or self.currentTenantName != self._tenant_name:
             self.getAuthToken()
             request = requests.put(self.getServiceURL(url), data=json.dumps(info), headers=self.headers)
         else:
             request = requests.put(self.getServiceURL(url), data=json.dumps(info), headers=self.headers)
             if not request.ok and request.content == common.authFailMsg:
                 self.getAuthToken()
                 request = requests.put(self.getServiceURL(url), data=json.dumps(info), headers=self.headers)
         if not request.ok:
             log.logger.error("Put request failed: %s, url: %s" % (request.content, url))
             raise RequestError(url + " " + request.content) 
          
         if request.ok and isNeedReturnValue:
             return request.json()
         
         if request.ok and not isNeedReturnValue:
             return True
     except requests.exceptions.ConnectionError, e:
         log.logger.error("Put request connect failed, url: %s" % url)
         raise RequestConnectError(e.msg)
示例#9
0
 def getRequestInfo(self, url):
     """
     获取请求的信息
     @url 请求的url信息
     """
     try:
         if not self.currentTenantName or self.currentTenantName != self._tenant_name:
             self.getAuthToken()
             request = requests.get(self.getServiceURL(url), headers=self.headers)
         else:        
             request = requests.get(self.getServiceURL(url), headers=self.headers)
             if not request.ok and request.content == common.authFailMsg:
                 self.getAuthToken()
                 request = requests.get(self.getServiceURL(url), headers=self.headers)
                 
         if request.ok:
             return request.json()
         else:
             log.logger.error("Get request failed: %s, url: %s" % (request.content, url))
             raise RequestError(url + " " + request.content)
         
     except requests.exceptions.ConnectionError, e:
         log.logger.error("Get request connect failed, url: %s" % url)
         raise RequestConnectError(e.msg)
示例#10
0
class VMTakeoverTools(object):
    """虚拟机接管工具类"""
    _instance = 0
    def __init__(self,host, tenant_name, username, password):
        super(VMTakeoverTools,self).__init__()
        self._host  = host 
        self._tenant_name = tenant_name
        self._username = username
        self._password = password
        self._tenant_id = ""
        
        self.headers = {
                        'Host': 'identity.api.openstack.org',
                        'Content-Type': 'application/json',
                        'Accept': 'application/json',
                        'Accept-Encoding': 'gzip, deflate',
                        'Accept-Language': 'en-US,en;q=0.5',
                        'Cookie': 'username=root; kimchiLang=zh_CN',
                        'X-Requested-With': 'XMLHttpRequest',
                                }
        self.currentTenantName = ""
        self.openstackServiceHostMap = {}

    def setOpenstackServiceHost(self, accessInfo):
    
        if not accessInfo:
            return
        
        if accessInfo.get("access", None) is None:
            return
        
        if accessInfo["access"].get("serviceCatalog", None) is None:
            return
        
        endPoints = accessInfo["access"]["serviceCatalog"]
    
        for subEndPoint in endPoints:
            if subEndPoint.get("endpoints", None) is None:
                continue
            
            for url in subEndPoint["endpoints"]:
                adminURL = url["adminURL"]
                address = adminURL.split(":")[1][2:]
                port = adminURL.split(":")[2].split('/')[0]
                self.openstackServiceHostMap[port] = address
        

    def getAuthToken(self):
        """
        获取认证
        """
      
        urlPath = "http://" + self._host + ":5000/v2.0/tokens"
        payload = {
                    "auth": {
                        "tenantName": self._tenant_name,
                        "passwordCredentials": {
                            "username":self._username,
                            "password":self._password,
                                                 }
                                    }
                        }
        
        try:
            r = requests.post(urlPath, data=json.dumps(payload), headers=self.headers)
            if r.ok:
                self.currentTenantName = self._tenant_name
                infoDict = r.json()
                self.setOpenstackServiceHost(infoDict)
                self.headers.update({'X-Auth-Token': infoDict["access"]["token"]["id"]})
                return infoDict
            else:
                raise RequestError(urlPath + " " + r.content)
        except requests.exceptions.ConnectionError, e:
            raise RequestConnectError(e.msg)
        except Exception, e:
            raise RequestError(e.msg)
示例#11
0
 def _dw():
     file_name = wget.download(url, out_fname)
     if not file_name:
         raise RequestError(f'Call url:"{url}" failed')
     return file_name