当前位置: 首页>>代码示例>>Python>>正文


Python Request.add_header方法代码示例

本文整理汇总了Python中six.moves.urllib.request.Request.add_header方法的典型用法代码示例。如果您正苦于以下问题:Python Request.add_header方法的具体用法?Python Request.add_header怎么用?Python Request.add_header使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在six.moves.urllib.request.Request的用法示例。


在下文中一共展示了Request.add_header方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: download_translations

# 需要导入模块: from six.moves.urllib.request import Request [as 别名]
# 或者: from six.moves.urllib.request.Request import add_header [as 别名]
    def download_translations(self, source, language, text, unit, user):
        """Download list of possible translations from a service."""

        # should the machine translation service be used?
        # (rather than only the term database)
        enable_mt = False
        if isinstance(settings.MT_SAP_USE_MT, bool):
            enable_mt = settings.MT_SAP_USE_MT

        # build the json body
        request_data_as_bytes = json.dumps(
            {
                'targetLanguages': [language],
                'sourceLanguage': source,
                'enableMT': enable_mt,
                'enableTranslationQualityEstimation': enable_mt,
                'units': [{'value': text}]
            },
            ensure_ascii=False
        ).encode('utf-8')

        # create the request
        translation_url = settings.MT_SAP_BASE_URL + 'translate'
        request = Request(
            translation_url if six.PY3 else translation_url.encode("utf-8")
        )
        request.timeout = 0.5
        request.add_header('User-Agent', USER_AGENT.encode('utf-8'))
        request.add_header('Referer', get_site_url().encode('utf-8'))
        request.add_header('Content-Type', 'application/json; charset=utf-8')
        request.add_header('Content-Length', len(request_data_as_bytes))
        request.add_header('Accept', 'application/json; charset=utf-8')
        self.authenticate(request)

        # Read and possibly convert response
        content = urlopen(
            request, request_data_as_bytes
        ).read().decode('utf-8')
        # Replace literal \t
        content = content.strip().replace(
            '\t', '\\t'
        ).replace(
            '\r', '\\r'
        )

        response = json.loads(content)

        translations = []

        # prepare the translations for weblate
        for item in response['units']:
            for translation in item['translations']:
                translations.append((
                    translation['value'],
                    translation.get('qualityIndex', 100),
                    self.name,
                    text
                ))

        return translations
开发者ID:daleathan,项目名称:weblate,代码行数:62,代码来源:saptranslationhub.py

示例2: _notify_emby

# 需要导入模块: from six.moves.urllib.request import Request [as 别名]
# 或者: from six.moves.urllib.request.Request import add_header [as 别名]
    def _notify_emby(self, message, host=None, emby_apikey=None):
        """Handles notifying Emby host via HTTP API

        Returns:
            Returns True for no issue or False if there was an error

        """

        # fill in omitted parameters
        if not host:
            host = sickbeard.EMBY_HOST
        if not emby_apikey:
            emby_apikey = sickbeard.EMBY_APIKEY

        url = 'http://%s/emby/Notifications/Admin' % host
        values = {'Name': 'Medusa', 'Description': message, 'ImageUrl': sickbeard.LOGO_URL}
        data = json.dumps(values)
        try:
            req = Request(url, data)
            req.add_header('X-MediaBrowser-Token', emby_apikey)
            req.add_header('Content-Type', 'application/json')

            response = urlopen(req)
            result = response.read()
            response.close()

            logger.log(u'EMBY: HTTP response: ' + result.replace('\n', ''), logger.DEBUG)
            return True

        except (URLError, IOError) as e:
            logger.log(u'EMBY: Warning: Couldn\'t contact Emby at ' + url + ' ' + ex(e), logger.WARNING)
            return False
开发者ID:Eiber,项目名称:SickRage-Medusa,代码行数:34,代码来源:emby.py

示例3: _query_api

# 需要导入模块: from six.moves.urllib.request import Request [as 别名]
# 或者: from six.moves.urllib.request.Request import add_header [as 别名]
 def _query_api(self, clip):
     # Adapted from SpeechRecognition source code, modified to get text onsets
     flac_data = clip.get_flac_data(
         convert_rate = None if clip.sample_rate >= 16000 else 16000,
         convert_width = None if clip.sample_width >= 2 else 2
     )
     model = "{0}_BroadbandModel".format("en-US")
     url = "https://stream.watsonplatform.net/speech-to-text/api/v1/recognize?{0}".format(urlencode({
         "profanity_filter": "false",
         "continuous": "true",
         "model": model,
         "timestamps": "true",
     }))
     request = Request(url, data = flac_data, headers = {
         "Content-Type": "audio/x-flac",
         "X-Watson-Learning-Opt-Out": "true",
     })
     
     if hasattr("", "encode"): # Python 2.6 compatibility
         authorization_value = base64.standard_b64encode("{0}:{1}".format(self.username, self.password).encode("utf-8")).decode("utf-8")
     else:
         authorization_value = base64.standard_b64encode("{0}:{1}".format(self.username, self.password))
     request.add_header("Authorization", "Basic {0}".format(authorization_value))
     
     try:
         response = urlopen(request, timeout=None)
     except HTTPError as e:
         raise Exception("recognition request failed: {0}".format(getattr(e, "reason", "status {0}".format(e.code))))
     except URLError as e:
         raise Exception("recognition connection failed: {0}".format(e.reason))
     
     response_text = response.read().decode("utf-8")
     result = json.loads(response_text)
     return result
开发者ID:qmac,项目名称:featureX,代码行数:36,代码来源:api.py

示例4: get_version

# 需要导入模块: from six.moves.urllib.request import Request [as 别名]
# 或者: from six.moves.urllib.request.Request import add_header [as 别名]
    def get_version(self):
        """Get the version of this Master.

        :returns: This master's version number ``str``

        Example::

            >>> j = Jenkins()
            >>> info = j.get_version()
            >>> print info
            >>> 1.541

        """
        try:
            request = Request(self.server + "/login")
            request.add_header('X-Jenkins', '0.0')
            response = urlopen(request, timeout=self.timeout)
            if response is None:
                raise EmptyResponseException(
                    "Error communicating with server[%s]: "
                    "empty response" % self.server)

            if six.PY2:
                return response.info().getheader('X-Jenkins')

            if six.PY3:
                return response.getheader('X-Jenkins')

        except (HTTPError, BadStatusLine):
            raise BadHTTPException("Error communicating with server[%s]"
                                   % self.server)
开发者ID:mannahusum,项目名称:python-jenkins,代码行数:33,代码来源:__init__.py

示例5: execute

# 需要导入模块: from six.moves.urllib.request import Request [as 别名]
# 或者: from six.moves.urllib.request.Request import add_header [as 别名]
    def execute(cls, uri, http_verb, extra_headers=None, batch=False, _body=None, **kw):
        """
        if batch == False, execute a command with the given parameters and
        return the response JSON.
        If batch == True, return the dictionary that would be used in a batch
        command.
        """
        if batch:
            urlsplitter = urlparse(API_ROOT).netloc
            ret = {"method": http_verb, "path": uri.split(urlsplitter, 1)[1]}
            if kw:
                ret["body"] = kw
            return ret

        if not ('app_id' in ACCESS_KEYS and 'rest_key' in ACCESS_KEYS):
            raise core.ParseError('Missing connection credentials')

        app_id = ACCESS_KEYS.get('app_id')
        rest_key = ACCESS_KEYS.get('rest_key')
        master_key = ACCESS_KEYS.get('master_key')

        url = uri if uri.startswith(API_ROOT) else cls.ENDPOINT_ROOT + uri
        if _body is None:
            data = kw and json.dumps(kw, default=date_handler) or "{}"
        else:
            data = _body
        if http_verb == 'GET' and data:
            url += '?%s' % urlencode(kw)
            data = None
        else:
            data = data

        headers = {
            'Content-type': 'application/json',
            'X-Parse-Application-Id': app_id,
            'X-Parse-REST-API-Key': rest_key
        }
        headers.update(extra_headers or {})

        request = Request(url.encode('utf-8'), data, headers)

        if ACCESS_KEYS.get('session_token'):
            request.add_header('X-Parse-Session-Token', ACCESS_KEYS.get('session_token'))
        elif master_key:
            request.add_header('X-Parse-Master-Key', master_key)

        request.get_method = lambda: http_verb

        try:
            response = urlopen(request, timeout=CONNECTION_TIMEOUT)
        except HTTPError as e:
            exc = {
                400: core.ResourceRequestBadRequest,
                401: core.ResourceRequestLoginRequired,
                403: core.ResourceRequestForbidden,
                404: core.ResourceRequestNotFound
                }.get(e.code, core.ParseError)
            raise exc(e.read())

        return json.loads(response.read().decode('utf-8'))
开发者ID:sunsongxp,项目名称:ParsePy,代码行数:62,代码来源:connection.py

示例6: _request_with_auth

# 需要导入模块: from six.moves.urllib.request import Request [as 别名]
# 或者: from six.moves.urllib.request.Request import add_header [as 别名]
def _request_with_auth(url, username, password):
    request = Request(url)
    base64string = base64.b64encode(
        username.encode('ascii') + b':' + password.encode('ascii')
    )
    request.add_header(b"Authorization", b"Basic " + base64string)
    return urlopen(request)
开发者ID:Bjwebb,项目名称:vcrpy,代码行数:9,代码来源:test_filter.py

示例7: test_extract_macaroons_from_request

# 需要导入模块: from six.moves.urllib.request import Request [as 别名]
# 或者: from six.moves.urllib.request.Request import add_header [as 别名]
    def test_extract_macaroons_from_request(self):
        def encode_macaroon(m):
            macaroons = '[' + utils.macaroon_to_json_string(m) + ']'
            return base64.urlsafe_b64encode(utils.to_bytes(macaroons)).decode('ascii')

        req = Request('http://example.com')
        m1 = pymacaroons.Macaroon(version=pymacaroons.MACAROON_V2, identifier='one')
        req.add_header('Macaroons', encode_macaroon(m1))
        m2 = pymacaroons.Macaroon(version=pymacaroons.MACAROON_V2, identifier='two')
        jar = requests.cookies.RequestsCookieJar()
        jar.set_cookie(utils.cookie(
            name='macaroon-auth',
            value=encode_macaroon(m2),
            url='http://example.com',
        ))
        jar.set_cookie(utils.cookie(
            name='macaroon-empty',
            value='',
            url='http://example.com',
        ))
        jar.add_cookie_header(req)

        macaroons = httpbakery.extract_macaroons(req)
        self.assertEquals(len(macaroons), 2)
        macaroons.sort(key=lambda ms: ms[0].identifier)
        self.assertEquals(macaroons[0][0].identifier, m1.identifier)
        self.assertEquals(macaroons[1][0].identifier, m2.identifier)
开发者ID:go-macaroon-bakery,项目名称:py-macaroon-bakery,代码行数:29,代码来源:test_client.py

示例8: download

# 需要导入模块: from six.moves.urllib.request import Request [as 别名]
# 或者: from six.moves.urllib.request.Request import add_header [as 别名]
def download(baseurl, parameters={}, headers={}):
    """Download Data from an url and returns it as a String
    @param baseurl Url to download from (e.g. http://www.google.com)
    @param parameters Parameter dict to be encoded with url
    @param headers Headers dict to pass with Request
    @returns String of data from URL
    """
    url = "?".join([baseurl, urlencode(parameters)])
    log.debug("Downloading: " + url)
    data = ""
    for _ in range(MAX_RETRIES):
        try:
            req = Request(url, headers=headers)
            req.add_header(USER_AGENT, USER_AGENT_STRING)
            response = urlopen(req)
            if six.PY2:
                data = response.read()
            else:
                data = response.read().decode("utf-8")
            response.close()
            break
        except Exception as err:
            if not isinstance(err, URLError):
                log.debug("Error %s during HTTP Request, abort", repr(err))
                raise  # propagate non-URLError
            log.debug("Error %s during HTTP Request, retrying", repr(err))
    else:
        raise
    return data
开发者ID:shughes-uk,项目名称:python-twitch,代码行数:31,代码来源:scraper.py

示例9: download_from_repository

# 需要导入模块: from six.moves.urllib.request import Request [as 别名]
# 或者: from six.moves.urllib.request.Request import add_header [as 别名]
    def download_from_repository(self, repo_source, target):
        """
        Download given source file from the repository and store
        it as target file

        The repo_source location is used relative to the repository
        location and will be part of a mime type source like:
        file://repo_path/repo_source

        :param string source: source file in the repo
        :param string target: file path
        """
        try:
            request = Request(
                os.sep.join([self._get_mime_typed_uri(), repo_source])
            )
            if self.user and self.secret:
                credentials = b64encode(
                    format(':'.join([self.user, self.secret])).encode()
                )
                request.add_header(
                    'Authorization', b'Basic ' + credentials
                )
            location = urlopen(request)
        except Exception as e:
            raise KiwiUriOpenError(
                '{0}: {1}'.format(type(e).__name__, format(e))
            )
        with open(target, 'wb') as target_file:
            target_file.write(location.read())
开发者ID:AdamMajer,项目名称:kiwi-ng,代码行数:32,代码来源:base.py

示例10: _send_to_kodi

# 需要导入模块: from six.moves.urllib.request import Request [as 别名]
# 或者: from six.moves.urllib.request.Request import add_header [as 别名]
    def _send_to_kodi(command, host=None, username=None, password=None, dest_app="KODI"):  # pylint: disable=too-many-arguments
        """Handles communication to KODI servers via HTTP API

        Args:
            command: Dictionary of field/data pairs, encoded via urllib and passed to the KODI API via HTTP
            host: KODI webserver host:port
            username: KODI webserver username
            password: KODI webserver password

        Returns:
            Returns response.result for successful commands or False if there was an error

        """

        # fill in omitted parameters
        if not username:
            username = sickbeard.KODI_USERNAME
        if not password:
            password = sickbeard.KODI_PASSWORD

        if not host:
            logger.log(u'No %s host passed, aborting update' % dest_app, logger.WARNING)
            return False

        for key in command:
            if isinstance(command[key], text_type):
                command[key] = command[key].encode('utf-8')

        enc_command = urlencode(command)
        logger.log(u"%s encoded API command: %r" % (dest_app, enc_command), logger.DEBUG)

        # url = 'http://%s/xbmcCmds/xbmcHttp/?%s' % (host, enc_command)  # maybe need for old plex?
        url = 'http://%s/kodiCmds/kodiHttp/?%s' % (host, enc_command)
        try:
            req = Request(url)
            # if we have a password, use authentication
            if password:
                base64string = base64.encodestring('%s:%s' % (username, password))[:-1]
                authheader = "Basic %s" % base64string
                req.add_header("Authorization", authheader)
                logger.log(u"Contacting %s (with auth header) via url: %s" % (dest_app, ss(url)), logger.DEBUG)
            else:
                logger.log(u"Contacting %s via url: %s" % (dest_app, ss(url)), logger.DEBUG)

            try:
                response = urlopen(req)
            except (BadStatusLine, URLError) as e:
                logger.log(u"Couldn't contact %s HTTP at %r : %r" % (dest_app, url, ex(e)), logger.DEBUG)
                return False

            result = response.read().decode(sickbeard.SYS_ENCODING)
            response.close()

            logger.log(u"%s HTTP response: %s" % (dest_app, result.replace('\n', '')), logger.DEBUG)
            return result

        except Exception as e:
            logger.log(u"Couldn't contact %s HTTP at %r : %r" % (dest_app, url, ex(e)), logger.DEBUG)
            return False
开发者ID:Thraxis,项目名称:pymedusa,代码行数:61,代码来源:kodi.py

示例11: post_soap

# 需要导入模块: from six.moves.urllib.request import Request [as 别名]
# 或者: from six.moves.urllib.request.Request import add_header [as 别名]
 def post_soap(self, url, xml, soapaction=None):
     url = self.opener.relative(url)
     request = Request(url, etree.tostring(soap_body(xml)))
     request.add_header('Content-type', 'text/xml; charset=utf-8')
     if soapaction:
         request.add_header('Soapaction', soapaction)
     response = self.opener.open(request, timeout=self.timeout)
     return etree.parse(response).xpath('/soap:Envelope/soap:Body/*', namespaces=namespaces)[0]
开发者ID:ox-it,项目名称:python-sharepoint,代码行数:10,代码来源:site.py

示例12: http_request

# 需要导入模块: from six.moves.urllib.request import Request [as 别名]
# 或者: from six.moves.urllib.request.Request import add_header [as 别名]
def http_request(method, url, request=None, timeout=30):
    """Perform HTTP request"""
    if method == 'POST':
        return http_post(url, request, timeout=timeout)
    else:  # GET
        request = Request(url)
        request.add_header('User-Agent', 'pycsw (http://pycsw.org/)')
        return urlopen(request, timeout=timeout).read()
开发者ID:GSA,项目名称:pycsw,代码行数:10,代码来源:util.py

示例13: test_filter_json_post_data

# 需要导入模块: from six.moves.urllib.request import Request [as 别名]
# 或者: from six.moves.urllib.request.Request import add_header [as 别名]
def test_filter_json_post_data(tmpdir):
    data = json.dumps({"id": "secret", "foo": "bar"}).encode("utf-8")
    request = Request("http://httpbin.org/post", data=data)
    request.add_header("Content-Type", "application/json")

    cass_file = str(tmpdir.join("filter_jpd.yaml"))
    with vcr.use_cassette(cass_file, filter_post_data_parameters=["id"]):
        urlopen(request)
    with vcr.use_cassette(cass_file, filter_post_data_parameters=["id"]) as cass:
        assert b'"id": "secret"' not in cass.requests[0].body
开发者ID:koobs,项目名称:vcrpy,代码行数:12,代码来源:test_filter.py

示例14: download_avatar_image

# 需要导入模块: from six.moves.urllib.request import Request [as 别名]
# 或者: from six.moves.urllib.request.Request import add_header [as 别名]
def download_avatar_image(user, size):
    """Download avatar image from remote server."""
    url = avatar_for_email(user.email, size)
    request = Request(url)
    request.add_header('User-Agent', USER_AGENT)

    # Fire request
    handle = urlopen(request, timeout=1.0)

    # Read and possibly convert response
    return bytes(handle.read())
开发者ID:nijel,项目名称:weblate,代码行数:13,代码来源:avatar.py

示例15: submit_request

# 需要导入模块: from six.moves.urllib.request import Request [as 别名]
# 或者: from six.moves.urllib.request.Request import add_header [as 别名]
    def submit_request(self, query):
        opener = build_opener(HTTPHandler)
        data = json.dumps(query.fetch_json()).encode('utf8')

        request = Request("http://{}/{}{}".format(
            self.admin_addr, query.path, query.fetch_url_params()), data=data)
        request.get_method = lambda: 'POST'
        request.add_header("Content-Type", 'application/json')
        request.add_header("Content-Length", len(data))

        connection = opener.open(request)
        return connection.read().decode('utf-8')
开发者ID:thelastpickle,项目名称:python-driver,代码行数:14,代码来源:utils.py


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