Python requests_oauthlib.OAuth1() Examples

The following are 30 code examples of requests_oauthlib.OAuth1(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module requests_oauthlib , or try the search function .
Example #1
Source File: twitter_connect.py    From Learning-Python-Networking-Second-Edition with MIT License 7 votes vote down vote up
def init_auth(file):

	(CONSUMER_KEY,
     CONSUMER_SECRET,
     OAUTH_TOKEN,
     OAUTH_TOKEN_SECRET) = open(file, 'r').read().splitlines()
	 
	auth_obj = requests_oauthlib.OAuth1(
	CONSUMER_KEY, CONSUMER_SECRET,
	OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
	
	if verify_credentials(auth_obj):
		print('Validated credentials OK')
		return auth_obj
	else:
		print('Credentials validation failed')
		sys.exit(1) 
Example #2
Source File: twitter.py    From kawasemi with MIT License 6 votes vote down vote up
def send(self, message, fail_silently=False, options=None):
        payload = {
            "status": message
        }

        self._set_payload_from_options(payload, options, "twitter", [
            "in_reply_to_status_id", "possibly_sensitive", "lat", "long",
            "place_id", "display_coordinates", "trim_user", "media_ids"])

        auth = OAuth1(self.api_key, self.api_secret, self.access_token,
                      self.access_token_secret)

        try:
            response = requests.post(self.url, auth=auth, data=payload)
            if response.status_code != requests.codes.ok:
                raise HttpError(response.status_code, response.text)
        except Exception:
            if not fail_silently:
                raise 
Example #3
Source File: auth.py    From twitter-stock-recommendation with MIT License 6 votes vote down vote up
def get_xauth_access_token(self, username, password):
        """
        Get an access token from an username and password combination.
        In order to get this working you need to create an app at
        http://twitter.com/apps, after that send a mail to api@twitter.com
        and request activation of xAuth for it.
        """
        try:
            url = self._get_oauth_url('access_token')
            oauth = OAuth1(self.consumer_key,
                           client_secret=self.consumer_secret)
            r = requests.post(url=url,
                              auth=oauth,
                              headers={'x_auth_mode': 'client_auth',
                                       'x_auth_username': username,
                                       'x_auth_password': password})

            credentials = parse_qs(r.content)
            return credentials.get('oauth_token')[0], credentials.get('oauth_token_secret')[0]
        except Exception as e:
            raise TweepError(e) 
Example #4
Source File: linkedin.py    From python3-linkedin with MIT License 6 votes vote down vote up
def make_request(self, method, url, data=None, params=None, headers=None,
                     timeout=60):
        if headers is None:
            headers = {'x-li-format': 'json', 'Content-Type': 'application/json'}
        else:
            headers.update({'x-li-format': 'json', 'Content-Type': 'application/json'})

        if params is None:
            params = {}
        kw = dict(data=data, params=params,
                  headers=headers, timeout=timeout)

        if isinstance(self.authentication, LinkedInDeveloperAuthentication):
            # Let requests_oauthlib.OAuth1 do *all* of the work here
            auth = OAuth1(self.authentication.consumer_key, self.authentication.consumer_secret,
                          self.authentication.user_token, self.authentication.user_secret)
            kw.update({'auth': auth})
        else:
            params.update({'oauth2_access_token': self.authentication.token.access_token})
        
        return requests.request(method.upper(), url, **kw) 
Example #5
Source File: nk.py    From Dailyfresh-B2C with Apache License 2.0 6 votes vote down vote up
def oauth_auth(self, token=None, oauth_verifier=None,
                   signature_type=SIGNATURE_TYPE_AUTH_HEADER):
        key, secret = self.get_key_and_secret()
        oauth_verifier = oauth_verifier or self.data.get('oauth_verifier')
        token = token or {}
        # decoding='utf-8' produces errors with python-requests on Python3
        # since the final URL will be of type bytes
        decoding = None if six.PY3 else 'utf-8'
        state = self.get_or_create_state()
        return OAuth1(key, secret,
                      resource_owner_key=None,
                      resource_owner_secret=None,
                      callback_uri=self.get_redirect_uri(state),
                      verifier=oauth_verifier,
                      signature_type=signature_type,
                      decoding=decoding) 
Example #6
Source File: oauth.py    From Dailyfresh-B2C with Apache License 2.0 6 votes vote down vote up
def unauthorized_token(self):
        """Return request for unauthorized token (first stage)"""
        params = self.request_token_extra_arguments()
        params.update(self.get_scope_argument())
        key, secret = self.get_key_and_secret()
        # decoding='utf-8' produces errors with python-requests on Python3
        # since the final URL will be of type bytes
        decoding = None if six.PY3 else 'utf-8'
        state = self.get_or_create_state()
        response = self.request(
            self.REQUEST_TOKEN_URL,
            params=params,
            auth=OAuth1(key, secret, callback_uri=self.get_redirect_uri(state),
                        decoding=decoding),
            method=self.REQUEST_TOKEN_METHOD
        )
        content = response.content
        if response.encoding or response.apparent_encoding:
            content = content.decode(response.encoding or
                                     response.apparent_encoding)
        else:
            content = response.content.decode()
        return content 
Example #7
Source File: xing.py    From Dailyfresh-B2C with Apache License 2.0 6 votes vote down vote up
def clean_oauth_auth(self, access_token):
        """Override of oauth_auth since Xing doesn't like callback_uri
        and oauth_verifier on authenticated API calls"""
        key, secret = self.get_key_and_secret()
        resource_owner_key = access_token.get('oauth_token')
        resource_owner_secret = access_token.get('oauth_token_secret')
        if not resource_owner_key:
            raise AuthTokenError(self, 'Missing oauth_token')
        if not resource_owner_secret:
            raise AuthTokenError(self, 'Missing oauth_token_secret')
        # decoding='utf-8' produces errors with python-requests on Python3
        # since the final URL will be of type bytes
        decoding = None if six.PY3 else 'utf-8'
        return OAuth1(key, secret,
                      resource_owner_key=resource_owner_key,
                      resource_owner_secret=resource_owner_secret,
                      signature_type=SIGNATURE_TYPE_AUTH_HEADER,
                      decoding=decoding) 
Example #8
Source File: khanacademy.py    From Dailyfresh-B2C with Apache License 2.0 6 votes vote down vote up
def oauth_auth(self, token=None, oauth_verifier=None):
        key, secret = self.get_key_and_secret()
        oauth_verifier = oauth_verifier or self.data.get('oauth_verifier')
        token = token or {}
        # decoding='utf-8' produces errors with python-requests on Python3
        # since the final URL will be of type bytes
        decoding = None if six.PY3 else 'utf-8'
        state = self.get_or_create_state()
        return OAuth1(key, secret,
                      resource_owner_key=token.get('oauth_token'),
                      resource_owner_secret=token.get('oauth_token_secret'),
                      callback_uri=self.get_redirect_uri(state),
                      verifier=oauth_verifier,
                      signature_method=SIGNATURE_HMAC,
                      signature_type=SIGNATURE_TYPE_QUERY,
                      decoding=decoding) 
Example #9
Source File: khanacademy.py    From Dailyfresh-B2C with Apache License 2.0 6 votes vote down vote up
def unauthorized_token_request(self):
        """Return request for unauthorized token (first stage)"""

        params = self.request_token_extra_arguments()
        params.update(self.get_scope_argument())
        key, secret = self.get_key_and_secret()
        # decoding='utf-8' produces errors with python-requests on Python3
        # since the final URL will be of type bytes
        decoding = None if six.PY3 else 'utf-8'
        state = self.get_or_create_state()
        auth = OAuth1(
            key,
            secret,
            callback_uri=self.get_redirect_uri(state),
            decoding=decoding,
            signature_method=SIGNATURE_HMAC,
            signature_type=SIGNATURE_TYPE_QUERY
        )
        url = self.REQUEST_TOKEN_URL + '?' + urlencode(params)
        url, _, _ = auth.client.sign(url)
        return url 
Example #10
Source File: views.py    From impactstory-tng with MIT License 6 votes vote down vote up
def get_twitter_request_token():
    request_token_url = 'https://api.twitter.com/oauth/request_token'

    oauth = OAuth1(
        os.getenv('TWITTER_CONSUMER_KEY'),
        client_secret=os.getenv('TWITTER_CONSUMER_SECRET'),
        callback_uri=request.args.get('redirectUri')
    )

    r = requests.post(request_token_url, auth=oauth)
    oauth_token_dict = dict(parse_qsl(r.text))

    return jsonify(oauth_token_dict)


##########
# admin 
Example #11
Source File: app.py    From video2commons with GNU General Public License v3.0 6 votes vote down vote up
def dologin():
    """Attempt to login."""
    if not (
        'access_token_key' in session and
        'access_token_secret' in session
    ):
        raise NameError("No access keys")

    access_token = AccessToken(
        session['access_token_key'],
        session['access_token_secret']
    )
    session['username'] = handshaker.identify(access_token)['username']
    auth = OAuth1(
        client_key=consumer_token.key,
        client_secret=consumer_token.secret,
        resource_owner_key=access_token.key,
        resource_owner_secret=access_token.secret
    )

    return auth 
Example #12
Source File: utils.py    From django-htk with MIT License 6 votes vote down vote up
def get_profile_data(resource_owner_key, resource_owner_secret):
    oauth = OAuth1(
        settings.SOCIAL_AUTH_LINKEDIN_KEY,
        client_secret=settings.SOCIAL_AUTH_LINKEDIN_SECRET,
        resource_owner_key=resource_owner_key,
        resource_owner_secret=resource_owner_secret
    )

    linkedin_api_endpoint = LINKEDIN_PROFILE_API_BASE_URL % ','.join(LINKEDIN_PROFILE_FIELDS)
    response = requests.get(
        url=linkedin_api_endpoint,
        auth=oauth
    )
    # TODO: uncomment to purposely raise Exception and see format
    #raise Exception(response.text)
    linkedin_profile_data = json.loads(response.text)
    return linkedin_profile_data 
Example #13
Source File: gh2k.py    From grimoirelab-elk with GNU General Public License v3.0 6 votes vote down vote up
def get_oauth():
    filepath = "twitter.oauth"
    with open(filepath, 'r'):
        pass
    config = configparser.SafeConfigParser()
    config.read(filepath)

    params = ['consumer_key', 'consumer_secret', 'oauth_token', 'oauth_token_secret']

    if 'oauth' not in config.sections():
        raise RuntimeError("Bad oauth file format %s, section missing: %s" % (filepath, 'oauth'))
    oauth_config = dict(config.items('oauth'))
    for param in params:
        if param not in oauth_config:
            raise RuntimeError("Bad oauth file format %s, not found param: %s" % (filepath, param))

    oauth = OAuth1(oauth_config['consumer_key'],
                   client_secret=oauth_config['consumer_secret'],
                   resource_owner_key=oauth_config['oauth_token'],
                   resource_owner_secret=oauth_config['oauth_token_secret'])

    return oauth 
Example #14
Source File: twitter_mentions.py    From Learning-Python-Networking-Second-Edition with MIT License 6 votes vote down vote up
def init_auth(file):

	(CONSUMER_KEY,
     CONSUMER_SECRET,
     OAUTH_TOKEN,
     OAUTH_TOKEN_SECRET) = open(file, 'r').read().splitlines()
	 
	auth_obj = requests_oauthlib.OAuth1(
	CONSUMER_KEY, CONSUMER_SECRET,
	OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
	
	if verify_credentials(auth_obj):
		print('Validated credentials OK')
		return auth_obj
	else:
		print('Credentials validation failed')
		sys.exit(1) 
Example #15
Source File: base.py    From django-connected with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def request(self, method, url, **kwargs):
        """Build remote url request. Constructs necessary auth."""
        user_token = kwargs.pop('token', self.token)
        token, secret, _ = self.parse_raw_token(user_token)
        callback = kwargs.pop('oauth_callback', None)
        verifier = kwargs.get('data', {}).pop('oauth_verifier', None)
        oauth = OAuth1(
            resource_owner_key=token,
            resource_owner_secret=secret,
            client_key=self.consumer_key,
            client_secret=self.consumer_secret,
            verifier=verifier,
            callback_uri=callback,
        )
        kwargs['auth'] = oauth
        return super(OAuthProvider, self).request(method, url, **kwargs) 
Example #16
Source File: client.py    From jira with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _create_oauth_session(self, oauth, timeout):
        verify = self._options["verify"]

        from oauthlib.oauth1 import SIGNATURE_RSA
        from requests_oauthlib import OAuth1

        oauth = OAuth1(
            oauth["consumer_key"],
            rsa_key=oauth["key_cert"],
            signature_method=SIGNATURE_RSA,
            resource_owner_key=oauth["access_token"],
            resource_owner_secret=oauth["access_token_secret"],
        )
        self._session = ResilientSession(timeout)
        self._session.verify = verify
        self._session.auth = oauth 
Example #17
Source File: twitter_search_tag.py    From Learning-Python-Networking-Second-Edition with MIT License 6 votes vote down vote up
def init_auth(file):

	(CONSUMER_KEY,
     CONSUMER_SECRET,
     OAUTH_TOKEN,
     OAUTH_TOKEN_SECRET) = open(file, 'r').read().splitlines()
	 
	auth_obj = requests_oauthlib.OAuth1(
	CONSUMER_KEY, CONSUMER_SECRET,
	OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
	
	if verify_credentials(auth_obj):
		print('Validated credentials OK')
		return auth_obj
	else:
		print('Credentials validation failed')
		sys.exit(1) 
Example #18
Source File: mediawiki.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def unauthorized_token(self):
        """
        Return request for unauthorized token (first stage)

        Mediawiki request token is requested from e.g.:
         * https://en.wikipedia.org/w/index.php?title=Special:OAuth/initiate
        """
        params = self.request_token_extra_arguments()
        params.update(self.get_scope_argument())
        params['title'] = 'Special:OAuth/initiate'
        key, secret = self.get_key_and_secret()
        decoding = None if six.PY3 else 'utf-8'
        response = self.request(
            self.setting('MEDIAWIKI_URL'),
            params=params,
            auth=OAuth1(
                key,
                secret,
                callback_uri=self.setting('CALLBACK'),
                decoding=decoding
            ),
            method=self.REQUEST_TOKEN_METHOD
        )

        if response.content.decode().startswith('Error'):
            raise AuthException(self, response.content.decode())

        return response.content.decode() 
Example #19
Source File: app.py    From oabot with MIT License 5 votes vote down vote up
def edit_wiki_page(page_name, content, access_token, summary=None, bot=False):
    auth = OAuth1(
        app.config['CONSUMER_KEY'],
        app.config['CONSUMER_SECRET'],
        access_token['key'],
        access_token['secret'])

    # Get token
    r = requests.get('https://en.wikipedia.org/w/api.php', params={
    'action':'query',
    'meta':'tokens',
        'format': 'json',
    }, auth=auth)
    r.raise_for_status()
    token = r.json()['query']['tokens']['csrftoken']

    data = {
    'action':'edit',
        'title': page_name,
        'text': content,
        'summary': summary,
        'format': 'json',
        'token': token,
        'watchlist': 'nochange',
    }
    if bot:
        data['bot'] = '1'
    r = requests.post('https://en.wikipedia.org/w/api.php', data=data,
            auth=auth)
    r.raise_for_status() 
Example #20
Source File: auth.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def apply_auth(self):
        return OAuth1(self.consumer_key,
                      client_secret=self.consumer_secret,
                      resource_owner_key=self.access_token,
                      resource_owner_secret=self.access_token_secret,
                      decoding=None) 
Example #21
Source File: stream.py    From hoaxy-backend with GNU General Public License v3.0 5 votes vote down vote up
def _authenticate(self):
        """Authenticate and return a requests client object."""
        crd = self.credentials
        oauth = OAuth1(
            client_key=crd['consumer_key'],
            client_secret=crd['consumer_secret'],
            resource_owner_key=crd['access_token'],
            resource_owner_secret=crd['access_token_secret'],
            signature_type='auth_header')
        self.client = requests.session()
        self.client.auth = oauth 
Example #22
Source File: twitter.py    From ask-alexa-pykit with MIT License 5 votes vote down vote up
def get_twitter_auth(user_id):
    consumer_key, consumer_secret = local_cache.get_server_state()['twitter_keys']
    access_token, access_secret = get_cached_access_pair(user_id)
    return OAuth1(consumer_key, consumer_secret, access_token, access_secret) 
Example #23
Source File: twitter.py    From ask-alexa-pykit with MIT License 5 votes vote down vote up
def get_access_token(oauth_token, oauth_verifier):
    url = "https://api.twitter.com/oauth/access_token"
    params = {"oauth_verifier" : oauth_verifier}

    server_state = local_cache.get_server_state()
    request_token  = server_state['request_token']
    request_secret = server_state['request_secret']
    consumer_key, consumer_secret = server_state['twitter_keys']

    auth = OAuth1(consumer_key, consumer_secret, request_token, request_secret)

    r = requests.post(url, params = params, auth=auth)
    response_obj = parse_qs(r.text)

    uid = response_obj['oauth_token'][0]    
    print ("Access token", uid)


    local_cache.set_user_state(user_id = uid,
                               state = { "access_token" : response_obj['oauth_token'][0],
                                         "access_secret" : response_obj['oauth_token_secret'][0],
                                         'twitter_user_id': response_obj['user_id'][0],
                                         'screen_name' : response_obj ['screen_name'][0] 
                               })
    local_cache.serialize()

    fragments = {
        "state" : local_cache.get_server_state()['metadata']['state'],
        "access_token" : uid,
        "token_type" : "Bearer"
    }
    return urlencode(fragments) 
Example #24
Source File: twitter.py    From ask-alexa-pykit with MIT License 5 votes vote down vote up
def get_request_token(callback_url=None):
    url = "https://api.twitter.com/oauth/request_token"
    consumer_key, consumer_secret = local_cache.get_server_state()['twitter_keys']

    auth = OAuth1(consumer_key, consumer_secret)
    params = { "oauth_callback" : callback_url } 
    r = requests.post(url, auth=auth, params=params)
    response_obj = parse_qs(r.text)    
    local_cache.update_server_state({ "request_token" : response_obj['oauth_token'][0],
                                      "request_secret": response_obj['oauth_token_secret'][0] })
    return response_obj['oauth_token_secret'], response_obj['oauth_token'] 
Example #25
Source File: api.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def SetCredentials(self,
                       consumer_key,
                       consumer_secret,
                       access_token_key=None,
                       access_token_secret=None,
                       application_only_auth=False):
        """Set the consumer_key and consumer_secret for this instance

        Args:
          consumer_key:
            The consumer_key of the twitter account.
          consumer_secret:
            The consumer_secret for the twitter account.
          access_token_key:
            The oAuth access token key value you retrieved
            from running get_access_token.py.
          access_token_secret:
            The oAuth access token's secret, also retrieved
            from the get_access_token.py run.
          application_only_auth:
            Whether to generate a bearer token and use Application-Only Auth
        """
        self._consumer_key = consumer_key
        self._consumer_secret = consumer_secret
        self._access_token_key = access_token_key
        self._access_token_secret = access_token_secret

        if application_only_auth:
            self._bearer_token = self.GetAppOnlyAuthToken(consumer_key, consumer_secret)
            self.__auth = OAuth2(token=self._bearer_token)
        else:
            auth_list = [consumer_key, consumer_secret,
                         access_token_key, access_token_secret]
            if all(auth_list):
                self.__auth = OAuth1(consumer_key, consumer_secret,
                                     access_token_key, access_token_secret)

        self._config = None 
Example #26
Source File: wyahooapi.py    From my-weather-indicator with MIT License 5 votes vote down vote up
def __init__(self,
                 longitude=-0.418,
                 latitude=39.360,
                 units=weatherservice.Units()):
        WeatherService.__init__(self, longitude, latitude, units)
        self.oauth = OAuth1(API_KEY, SHARED_SECRET)
        self.woeid = geocodeapi.get_woeid(latitude, longitude) 
Example #27
Source File: api.py    From StockRecommendSystem with MIT License 5 votes vote down vote up
def SetCredentials(self,
                       consumer_key,
                       consumer_secret,
                       access_token_key=None,
                       access_token_secret=None,
                       application_only_auth=False):
        """Set the consumer_key and consumer_secret for this instance

        Args:
          consumer_key:
            The consumer_key of the twitter account.
          consumer_secret:
            The consumer_secret for the twitter account.
          access_token_key:
            The oAuth access token key value you retrieved
            from running get_access_token.py.
          access_token_secret:
            The oAuth access token's secret, also retrieved
            from the get_access_token.py run.
          application_only_auth:
            Whether to generate a bearer token and use Application-Only Auth
        """
        self._consumer_key = consumer_key
        self._consumer_secret = consumer_secret
        self._access_token_key = access_token_key
        self._access_token_secret = access_token_secret

        if application_only_auth:
            self._bearer_token = self.GetAppOnlyAuthToken(consumer_key, consumer_secret)
            self.__auth = OAuth2(token=self._bearer_token)
        else:
            auth_list = [consumer_key, consumer_secret,
                         access_token_key, access_token_secret]
            if all(auth_list):
                self.__auth = OAuth1(consumer_key, consumer_secret,
                                     access_token_key, access_token_secret)

        self._config = None 
Example #28
Source File: plugin.py    From limnoria-plugins with Do What The F*ck You Want To Public License 5 votes vote down vote up
def __init__(self, consumer_key, consumer_secret, token, token_secret):
        self.auth = OAuth1(consumer_key, consumer_secret, token, token_secret) 
Example #29
Source File: views.py    From server with MIT License 5 votes vote down vote up
def get_city_trends(request, city_id):
    """
    Returns a list of top trending tweets in the given city
    :param request:
    :param city_id:
    :return: 404 if invalid city id is sent
    :return: 503 if Twitter API request fails
    :return: 200 successful
    """
    try:
        city = City.objects.get(pk=city_id)
    except City.DoesNotExist:
        error_message = "Invalid City ID"
        return Response(error_message, status=status.HTTP_404_NOT_FOUND)

    twitter_auth = OAuth1(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, TWITTER_OAUTH_TOKEN,
                          TWITTER_OAUTH_TOKEN_SECRET)

    # check if city WOEID is in database or not
    if not city.woeid:
        try:
            url = TWITTER_TRENDS_URL + "closest.json?lat={0}&long={1}".format(city.latitude, city.longitude)
            woeid_response = requests.get(url, auth=twitter_auth)
            city.woeid = woeid_response.json()[0]['woeid']
            city.save()
        except Exception as e:
            return Response(str(e), status=status.HTTP_503_SERVICE_UNAVAILABLE)

    try:
        url = TWITTER_TRENDS_URL + "place.json?id={0}".format(city.woeid)
        api_response = requests.get(url, auth=twitter_auth)
        response = api_response.json()[0]['trends']
    except Exception:
        return DOWNSTREAM_ERROR_RESPONSE

    return Response(response) 
Example #30
Source File: views.py    From server with MIT License 5 votes vote down vote up
def get_search_tweets(request, query):
    """
    Returns a list of related tweets for given search query
    :param request:
    :param queryf:
    :return: 503 if Twitter API request fails
    :return: 200 successful
    """
    twitter_auth = OAuth1(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, TWITTER_OAUTH_TOKEN,
                          TWITTER_OAUTH_TOKEN_SECRET)
    try:
        url = TWITTER_SEARCH_URL + "tweets.json?q={0}".format(query)
        api_response = requests.get(url, auth=twitter_auth)
        api_response_json = api_response.json()
        tweets = api_response_json['statuses']
        response = []
        for tweet in tweets:
            result = SearchTweetResponse(
                created_at=tweet['created_at'],
                text=tweet['text'],
                username=tweet['user']['screen_name'],
                user_screen_name=tweet['user']['name'],
                user_profile_image=tweet['user']['profile_image_url'],
                retweet_count=tweet['retweet_count'],
                favorite_count=tweet['favorite_count'],
                tweet_url="https://www.twitter.com/" + tweet['user']['screen_name'] + "/status/" + tweet['id_str'],
            )
            result_as_json = result.to_json()
            response.append(result_as_json)

    except Exception:
        return DOWNSTREAM_ERROR_RESPONSE

    return Response(response)