예제 #1
0
파일: auth.py 프로젝트: 2014/qqweibo
    def get_access_token(self, key=None, secret=None, token=None, verifier=None):
        """
        After user has authorized the request token, get access token
        with user supplied verifier.
        """
        try:
            if key and secret:
                token = oauth.OAuthToken(key, secret)
            if token is None:
                token = self.request_token
            
            url = self._get_oauth_url('access_token')
            # build request
            request = oauth.OAuthRequest.from_consumer_and_token(
                self._consumer,
                token=token, http_url=url,
                verifier=str(verifier)
            )
            request.sign_request(self._sigmethod, self._consumer, token)

            # send request
            resp = urlopen(Request(request.to_url()))  # must
            self.access_token = oauth.OAuthToken.from_string(resp.read().decode('ascii'))

            #print ('Access token key: ' + str(self.access_token.key))
            #print ('Access token secret: ' + str(self.access_token.secret))

            return self.access_token
        except Exception as e:
            raise QWeiboError(e)
예제 #2
0
파일: auth.py 프로젝트: xlk521/cloudguantou
    def get_access_token(self, verifier=None):
        """
        After user has authorized the request token, get access token
        with user supplied verifier.
        """
        try:
            url = self._get_oauth_url('access_token')

            # build request
            request = oauth.OAuthRequest.from_consumer_and_token(
                self._consumer,
                token=self.request_token,
                http_url=url,
                verifier=str(verifier))
            request.sign_request(self._sigmethod, self._consumer,
                                 self.request_token)

            # send request
            resp = urlopen(Request(request.to_url()))  # must
            self.access_token = oauth.OAuthToken.from_string(
                resp.read().decode('ascii'))

            #print ('Access token key: ' + str(self.access_token.key))
            #print ('Access token secret: ' + str(self.access_token.secret))

            return self.access_token
        except Exception as e:
            raise QWeiboError(e)
예제 #3
0
파일: binder.py 프로젝트: amituofo/BOHOO2
        def execute(self):
            # Build the request URL
            url = self.scheme + self.host + self.api_root + self.path

            full_url, parameters = self.api.auth.authorize_request(url, self.method, self.headers, self.parameters)
            self.headers.setdefault("User-Agent", "pyqqweibo")
            if self.method == 'POST':
                if self.post_data is None:
                    self.headers.setdefault("Content-Type", "application/x-www-form-urlencoded")
                    # asure in bytes format
                    self.post_data = '&'.join(("%s=%s" % kv) for kv in parameters)
                req = Request(full_url, data=self.post_data, headers=self.headers)
            elif self.method == 'GET':
                req = Request(full_url)
            try:
                resp = urlopen(req)
            except Exception as e:
                    raise QWeiboError("Failed to request %s headers=%s %s" % \
                                      (url, self.headers, e))
            body = resp.read()
            self.api.last_response = resp
            # log handling
            if self.api.log is not None:
                requestUrl = "URL:http://" + self.host + url
                eTime = '%.0f' % ((time.time() - sTime) * 1000)
                postData = ""
                if self.post_data is not None:
                    postData = ",post:" + self.post_data[:500]
                self.api.log.debug("%s, time: %s, %s result: %s" % (requestUrl, eTime, postData, body))

            retcode = 0
            errcode = 0
            # for py3k, ^_^
            if not hasattr(body, 'encode'):
                body = str(body, 'utf-8')
            # if self.api.parser.payload_format == 'json':
            #     try:
            #         # BUG: API BUG, refer api.doc.rst
            #         if body.endswith('out of memery'):
            #             body = body[:body.rfind('}')+1]
            #         json = self.api.parser.parse_error(self, body)
            #         retcode = json.get('ret', 0)
            #         msg = json.get('msg', '')
            #         # only in some post request
            #         errcode = json.get('errcode', 0)
            #     except ValueError as e:
            #         retcode = -1
            #         msg = "Bad json format (%s)" % e
            #     finally:
            #         if retcode + errcode != 0:
            #             raise QWeiboError("Response error: %s. (ret=%s, errcode=%s)" % \
            #                               (msg, retcode, errcode))

            # Parse the response payload
            result = self.api.parser.parse(self, body)

            # Store result into cache if one is available.
            if self.api.cache and self.method == 'GET' and result:
                self.api.cache.store(url, result)
            return result
예제 #4
0
파일: auth.py 프로젝트: xlk521/cloudguantou
 def _get_request_token(self):
     try:
         url = self._get_oauth_url('request_token')
         request = oauth.OAuthRequest.from_consumer_and_token(
             self._consumer, http_url=url, callback=self.callback)
         request.sign_request(self._sigmethod, self._consumer, None)
         resp = urlopen(Request(request.to_url()))  # must
         return oauth.OAuthToken.from_string(resp.read().decode('ascii'))
     except RuntimeError as e:
         raise QWeiboError(e)
예제 #5
0
파일: auth.py 프로젝트: 2014/qqweibo
 def _get_request_token(self):
     try:
         url = self._get_oauth_url('request_token')
         request = oauth.OAuthRequest.from_consumer_and_token(
             self._consumer, http_url=url, callback=self.callback
         )
         request.sign_request(self._sigmethod, self._consumer, None)
         resp = urlopen(Request(request.to_url()))  # must
         return oauth.OAuthToken.from_string(resp.read().decode('ascii'))
     except RuntimeError as e:
         raise QWeiboError(e)
예제 #6
0
        def execute(self):
            # Build the request URL
            url = self.api_root + self.path
            #if self.api.source is not None:
            #    self.parameters.setdefault('source',self.api.source)

            if len(self.parameters):
                if self.method == 'GET':
                    url = '%s?%s' % (url, urlencode(self.parameters))
                else:
                    self.headers.setdefault("User-Agent", "python")
                    if self.post_data is None:
                        self.headers.setdefault("Accept", "text/html")
                        self.headers.setdefault("Content-Type", "application/x-www-form-urlencoded")
                        # asure in bytes format
                        self.post_data = urlencode(self.parameters).encode('ascii')
            # Query the cache if one is available
            # and this request uses a GET method.
            if self.api.cache and self.method == 'GET':
                cache_result = self.api.cache.get(url)
                # if cache result found and not expired, return it
                if cache_result:
                    # must restore api reference
                    if isinstance(cache_result, list):
                        for result in cache_result:
                            result._api = self.api
                    else:
                        cache_result._api = self.api
                    return cache_result
                #urllib.urlencode(self.parameters)
            # Continue attempting request until successful
            # or maximum number of retries is reached.
            sTime = time.time()
            retries_performed = 0
            while retries_performed < self.retry_count + 1:
                # Open connection
                # FIXME: add timeout
                # Apply authentication
                if self.require_auth and self.api.auth:
                    url_full = self.api.auth.get_authed_url(
                        self.scheme + self.host + url,
                        self.method, self.headers, self.parameters
                    )
                else:                   # this brunch is never accoured
                    url_full = self.api.auth.get_signed_url(
                        self.scheme + self.host + url,
                        self.method, self.headers, self.parameters
                    )
                try:
                    if self.method == 'POST':
                        req = Request(url_full, data=self.post_data, headers=self.headers)
                    else:
                        req = Request(url_full)
                    resp = urlopen(req)
                except Exception, e:
                    raise QWeiboError("Failed to request %s headers=%s %s" % \
                                      (url, self.headers, e))

                # Exit request loop if non-retry error code
                if self.retry_errors:
                    if resp.code not in self.retry_errors:
                        break
                else:
                    if resp.code == 200:
                        break

                # Sleep before retrying request again
                time.sleep(self.retry_delay)
                retries_performed += 1
예제 #7
0
파일: binder.py 프로젝트: wyrover/pyqqweibo
        def execute(self):
            # Build the request URL
            url = self.scheme + self.host + self.api_root + self.path

            full_url, parameters = self.api.auth.authorize_request(
                url, self.method, self.headers, self.parameters)
            self.headers.setdefault("User-Agent", "pyqqweibo")
            if self.method == 'POST':
                if self.post_data is None:
                    self.headers.setdefault(
                        "Content-Type", "application/x-www-form-urlencoded")
                    # asure in bytes format
                    self.post_data = '&'.join(
                        ("%s=%s" % kv) for kv in parameters)
                req = Request(full_url,
                              data=self.post_data,
                              headers=self.headers)
            elif self.method == 'GET':
                req = Request(full_url)
            try:
                resp = urlopen(req)
            except Exception as e:
                raise QWeiboError("Failed to request %s headers=%s %s" % \
                                  (url, self.headers, e))
            body = resp.read()
            self.api.last_response = resp
            # log handling
            if self.api.log is not None:
                requestUrl = "URL:http://" + self.host + url
                eTime = '%.0f' % ((time.time() - sTime) * 1000)
                postData = ""
                if self.post_data is not None:
                    postData = ",post:" + self.post_data[:500]
                self.api.log.debug("%s, time: %s, %s result: %s" %
                                   (requestUrl, eTime, postData, body))

            retcode = 0
            errcode = 0
            # for py3k, ^_^
            if not hasattr(body, 'encode'):
                body = str(body, 'utf-8')
            # if self.api.parser.payload_format == 'json':
            #     try:
            #         # BUG: API BUG, refer api.doc.rst
            #         if body.endswith('out of memery'):
            #             body = body[:body.rfind('}')+1]
            #         json = self.api.parser.parse_error(self, body)
            #         retcode = json.get('ret', 0)
            #         msg = json.get('msg', '')
            #         # only in some post request
            #         errcode = json.get('errcode', 0)
            #     except ValueError as e:
            #         retcode = -1
            #         msg = "Bad json format (%s)" % e
            #     finally:
            #         if retcode + errcode != 0:
            #             raise QWeiboError("Response error: %s. (ret=%s, errcode=%s)" % \
            #                               (msg, retcode, errcode))

            # Parse the response payload
            result = self.api.parser.parse(self, body)

            # Store result into cache if one is available.
            if self.api.cache and self.method == 'GET' and result:
                self.api.cache.store(url, result)
            return result
예제 #8
0
파일: binder.py 프로젝트: alphazw/moedj
        def execute(self):
            # Build the request URL
            url = self.api_root + self.path
            #if self.api.source is not None:
            #    self.parameters.setdefault('source',self.api.source)

            if len(self.parameters):
                if self.method == 'GET':
                    url = '%s?%s' % (url, urlencode(self.parameters))
                else:
                    self.headers.setdefault("User-Agent", "pyqqweibo")
                    if self.post_data is None:
                        self.headers.setdefault("Accept", "text/html")
                        self.headers.setdefault("Content-Type", "application/x-www-form-urlencoded")
                        # asure in bytes format
                        self.post_data = urlencode(self.parameters).encode('ascii')
            # Query the cache if one is available
            # and this request uses a GET method.
            if self.api.cache and self.method == 'GET':
                cache_result = self.api.cache.get(url)
                # if cache result found and not expired, return it
                if cache_result:
                    # must restore api reference
                    if isinstance(cache_result, list):
                        for result in cache_result:
                            result._api = self.api
                    else:
                        cache_result._api = self.api
                    return cache_result
                #urllib.urlencode(self.parameters)
            # Continue attempting request until successful
            # or maximum number of retries is reached.
            sTime = time.time()
            retries_performed = 0
            while retries_performed < self.retry_count + 1:
                # Open connection
                # FIXME: add timeout
                # Apply authentication
                if self.require_auth and self.api.auth:
                    url_full = self.api.auth.get_authed_url(
                        self.scheme + self.host + url,
                        self.method, self.headers, self.parameters
                    )
                else:                   # this brunch is never accoured
                    url_full = self.api.auth.get_signed_url(
                        self.scheme + self.host + url,
                        self.method, self.headers, self.parameters
                    )
                try:
                    if self.method == 'POST':
                        req = Request(url_full, data=self.post_data, headers=self.headers)
                    else:
                        req = Request(url_full)
                    resp = urlopen(req, timeout=20)
                except Exception as e:
                    raise QWeiboError("Failed to request %s headers=%s %s" % \
                                      (url, self.headers, e))

                # Exit request loop if non-retry error code
                if self.retry_errors:
                    if resp.code not in self.retry_errors:
                        break
                else:
                    if resp.code == 200:
                        break

                # Sleep before retrying request again
                time.sleep(self.retry_delay)
                retries_performed += 1

            # If an error was returned, throw an exception
            body = resp.read()
            self.api.last_response = resp
            if self.api.log is not None:
                requestUrl = "URL:http://" + self.host + url
                eTime = '%.0f' % ((time.time() - sTime) * 1000)
                postData = ""
                if self.post_data is not None:
                    postData = ",post:" + self.post_data[:500]
                self.api.log.debug("%s, time: %s, %s result: %s" % (requestUrl, eTime, postData, body))

            retcode = 0
            errcode = 0
            # for py3k, ^_^
            if not hasattr(body, 'encode'):
                body = str(body, 'utf-8')
            if self.api.parser.payload_format == 'json':
                try:
                    # BUG: API BUG, refer api.doc.rst
                    if body.endswith('out of memery'):
                        body = body[:body.rfind('}')+1]
                    json = self.api.parser.parse_error(self, body)
                    retcode = json.get('ret', 0)
                    msg = json.get('msg', '')
                    # only in some post request
                    errcode = json.get('errcode', 0)
                except ValueError as e:
                    retcode = -1
                    msg = "Bad json format (%s)" % e
                finally:
                    if retcode + errcode != 0:
                        raise QWeiboError("Response error: %s. (ret=%s, errcode=%s)" % \
                                          (msg, retcode, errcode))

            # Parse the response payload
            result = self.api.parser.parse(self, body)

            # Store result into cache if one is available.
            if self.api.cache and self.method == 'GET' and result:
                self.api.cache.store(url, result)
            return result
예제 #9
0
        def execute(self):
            # Build the request URL
            url = self.api_root + self.path
            #if self.api.source is not None:
            #    self.parameters.setdefault('source',self.api.source)

            if len(self.parameters):
                if self.method == 'GET':
                    url = '%s?%s' % (url, urlencode(self.parameters))
                else:
                    self.headers.setdefault("User-Agent", "pyqqweibo")
                    if self.post_data is None:
                        self.headers.setdefault("Accept", "text/html")
                        self.headers.setdefault(
                            "Content-Type",
                            "application/x-www-form-urlencoded")
                        # asure in bytes format
                        self.post_data = urlencode(
                            self.parameters).encode('ascii')
            # Query the cache if one is available
            # and this request uses a GET method.
            if self.api.cache and self.method == 'GET':
                cache_result = self.api.cache.get(url)
                # if cache result found and not expired, return it
                if cache_result:
                    # must restore api reference
                    if isinstance(cache_result, list):
                        for result in cache_result:
                            result._api = self.api
                    else:
                        cache_result._api = self.api
                    return cache_result
                #urllib.urlencode(self.parameters)
            # Continue attempting request until successful
            # or maximum number of retries is reached.
            sTime = time.time()
            retries_performed = 0
            while retries_performed < self.retry_count + 1:
                # Open connection
                # FIXME: add timeout
                # Apply authentication
                if self.require_auth and self.api.auth:
                    url_full = self.api.auth.get_authed_url(
                        self.scheme + self.host + url, self.method,
                        self.headers, self.parameters)
                else:  # this brunch is never accoured
                    url_full = self.api.auth.get_signed_url(
                        self.scheme + self.host + url, self.method,
                        self.headers, self.parameters)
                try:
                    if self.method == 'POST':
                        req = Request(url_full,
                                      data=self.post_data,
                                      headers=self.headers)
                    else:
                        req = Request(url_full)
                    resp = urlopen(req, timeout=20)
                except Exception as e:
                    raise QWeiboError("Failed to request %s headers=%s %s" % \
                                      (url, self.headers, e))

                # Exit request loop if non-retry error code
                if self.retry_errors:
                    if resp.code not in self.retry_errors:
                        break
                else:
                    if resp.code == 200:
                        break

                # Sleep before retrying request again
                time.sleep(self.retry_delay)
                retries_performed += 1

            # If an error was returned, throw an exception
            body = resp.read()
            self.api.last_response = resp
            if self.api.log is not None:
                requestUrl = "URL:http://" + self.host + url
                eTime = '%.0f' % ((time.time() - sTime) * 1000)
                postData = ""
                if self.post_data is not None:
                    postData = ",post:" + self.post_data[:500]
                self.api.log.debug("%s, time: %s, %s result: %s" %
                                   (requestUrl, eTime, postData, body))

            retcode = 0
            errcode = 0
            # for py3k, ^_^
            if not hasattr(body, 'encode'):
                body = str(body, 'utf-8')
            if self.api.parser.payload_format == 'json':
                try:
                    # BUG: API BUG, refer api.doc.rst
                    if body.endswith('out of memery'):
                        body = body[:body.rfind('}') + 1]
                    json = self.api.parser.parse_error(self, body)
                    retcode = json.get('ret', 0)
                    msg = json.get('msg', '')
                    # only in some post request
                    errcode = json.get('errcode', 0)
                except ValueError as e:
                    retcode = -1
                    msg = "Bad json format (%s)" % e
                finally:
                    if retcode + errcode != 0:
                        raise QWeiboError("Response error: %s. (ret=%s, errcode=%s)" % \
                                          (msg, retcode, errcode))

            # Parse the response payload
            result = self.api.parser.parse(self, body)

            # Store result into cache if one is available.
            if self.api.cache and self.method == 'GET' and result:
                self.api.cache.store(url, result)
            return result