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


Python http.client方法代码示例

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


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

示例1: __init__

# 需要导入模块: import http [as 别名]
# 或者: from http import client [as 别名]
def __init__(self, info):
        # info is either an email.message or
        # an httplib.HTTPResponse object.
        if isinstance(info, http.client.HTTPResponse):
            for key, value in info.getheaders():
                key = key.lower()
                prev = self.get(key)
                if prev is not None:
                    value = ", ".join((prev, value))
                self[key] = value
            self.status = info.status
            self["status"] = str(self.status)
            self.reason = info.reason
            self.version = info.version
        elif isinstance(info, email.message.Message):
            for key, value in list(info.items()):
                self[key.lower()] = value
            self.status = int(self["status"])
        else:
            for key, value in info.items():
                self[key.lower()] = value
            self.status = int(self.get("status", self.status)) 
开发者ID:remg427,项目名称:misp42splunk,代码行数:24,代码来源:__init__.py

示例2: call_asgi

# 需要导入模块: import http [as 别名]
# 或者: from http import client [as 别名]
def call_asgi(
        self,
        app: Any = None,
        base_url: Optional[str] = "http://testserver",
        headers: Optional[Dict[str, str]] = None,
        **kwargs: Any,
    ) -> requests.Response:
        application = app or self.app
        if application is None:
            raise RuntimeError(
                "ASGI application instance is required. "
                "Please, set `app` argument in the schema constructor or pass it to `call_asgi`"
            )
        client = ASGIClient(application)

        return self.call(base_url=base_url, session=client, headers=headers, **kwargs) 
开发者ID:kiwicom,项目名称:schemathesis,代码行数:18,代码来源:models.py

示例3: debug

# 需要导入模块: import http [as 别名]
# 或者: from http import client [as 别名]
def debug(self, value):
        """
        Sets the debug status.

        :param value: The debug status, True or False.
        :type: bool
        """
        self.__debug = value
        if self.__debug:
            # if debug status is True, turn on debug logging
            for _, logger in iteritems(self.logger):
                logger.setLevel(logging.DEBUG)
            # turn on httplib debug
            httplib.HTTPConnection.debuglevel = 1
        else:
            # if debug status is False, turn off debug logging,
            # setting log level to default `logging.WARNING`
            for _, logger in iteritems(self.logger):
                logger.setLevel(logging.WARNING)
            # turn off httplib debug
            httplib.HTTPConnection.debuglevel = 0 
开发者ID:danielfrg,项目名称:jupyterhub-kubernetes_spawner,代码行数:23,代码来源:configuration.py

示例4: SetXTwitterHeaders

# 需要导入模块: import http [as 别名]
# 或者: from http import client [as 别名]
def SetXTwitterHeaders(self, client, url, version):
        """Set the X-Twitter HTTP headers that will be sent to the server.

        Args:
          client:
             The client name as a string.  Will be sent to the server as
             the 'X-Twitter-Client' header.
          url:
             The URL of the meta.xml as a string.  Will be sent to the server
             as the 'X-Twitter-Client-URL' header.
          version:
             The client version as a string.  Will be sent to the server
             as the 'X-Twitter-Client-Version' header.
        """
        self._request_headers['X-Twitter-Client'] = client
        self._request_headers['X-Twitter-Client-URL'] = url
        self._request_headers['X-Twitter-Client-Version'] = version 
开发者ID:doncat99,项目名称:StockRecommendSystem,代码行数:19,代码来源:api.py

示例5: setUp

# 需要导入模块: import http [as 别名]
# 或者: from http import client [as 别名]
def setUp(self):
		RegisterPath("^{0}$".format(self.test_resource[1:]), self.handler_class.__name__)(self._test_resource_handler)
		self.server = self.server_class(self.handler_class, **self._server_kwargs)
		self.assertTrue(isinstance(self.server, AdvancedHTTPServer))
		self.server_thread = threading.Thread(target=self.server.serve_forever)
		self.server_thread.daemon = True
		self.server_thread.start()
		self.assertTrue(self.server_thread.is_alive())
		self.shutdown_requested = False
		if len(self.server_address) == 3 and self.server_address[2]:
			context = ssl.create_default_context()
			context.check_hostname = False
			context.verify_mode = ssl.CERT_NONE
			self.http_connection = http.client.HTTPSConnection(self.server_address[0], self.server_address[1], context=context)
		else:
			self.http_connection = http.client.HTTPConnection(self.server_address[0], self.server_address[1])
		self.http_connection.connect() 
开发者ID:zeroSteiner,项目名称:AdvancedHTTPServer,代码行数:19,代码来源:advancedhttpserver.py

示例6: http_request

# 需要导入模块: import http [as 别名]
# 或者: from http import client [as 别名]
def http_request(self, resource, method='GET', headers=None):
		"""
		Make an HTTP request to the test server and return the response.

		:param str resource: The resource to issue the request to.
		:param str method: The HTTP verb to use (GET, HEAD, POST etc.).
		:param dict headers: The HTTP headers to provide in the request.
		:return: The HTTP response object.
		:rtype: :py:class:`http.client.HTTPResponse`
		"""
		headers = (headers or {})
		if not 'Connection' in headers:
			headers['Connection'] = 'keep-alive'
		self.http_connection.request(method, resource, headers=headers)
		time.sleep(0.025)
		response = self.http_connection.getresponse()
		response.data = response.read()
		return response 
开发者ID:zeroSteiner,项目名称:AdvancedHTTPServer,代码行数:20,代码来源:advancedhttpserver.py

示例7: setUp

# 需要导入模块: import http [as 别名]
# 或者: from http import client [as 别名]
def setUp(self):
        super().setUp()
        self.loop = asyncio.new_event_loop()

        # Make sure we are setting which loop we are using explicitly
        asyncio.set_event_loop(None)

        self.gnatsd = Gnatsd(port=4224, tls=True)
        start_gnatsd(self.gnatsd)

        self.ssl_ctx = ssl.create_default_context(
            purpose=ssl.Purpose.SERVER_AUTH
        )
        # self.ssl_ctx.protocol = ssl.PROTOCOL_TLSv1_2
        self.ssl_ctx.load_verify_locations('tests/certs/ca.pem')
        self.ssl_ctx.load_cert_chain(
            certfile='tests/certs/client-cert.pem',
            keyfile='tests/certs/client-key.pem'
        ) 
开发者ID:nats-io,项目名称:nats.py,代码行数:21,代码来源:utils.py

示例8: start_gnatsd

# 需要导入模块: import http [as 别名]
# 或者: from http import client [as 别名]
def start_gnatsd(gnatsd: Gnatsd):
    gnatsd.start()

    endpoint = f'127.0.0.1:{gnatsd.http_port}'
    retries = 0
    while True:
        if retries > 100:
            break

        try:
            httpclient = http.client.HTTPConnection(endpoint, timeout=5)
            httpclient.request('GET', '/varz')
            response = httpclient.getresponse()
            if response.code == 200:
                break
        except:
            retries += 1
            time.sleep(0.1) 
开发者ID:nats-io,项目名称:nats.py,代码行数:20,代码来源:utils.py

示例9: collect

# 需要导入模块: import http [as 别名]
# 或者: from http import client [as 别名]
def collect():
    '''Send usage info to Stitch.'''

    try:
        version = pkg_resources.get_distribution('target-stitch').version
        conn = http.client.HTTPSConnection('collector.stitchdata.com', timeout=10)
        conn.connect()
        params = {
            'e': 'se',
            'aid': 'singer',
            'se_ca': 'target-stitch',
            'se_ac': 'open',
            'se_la': version,
        }
        conn.request('GET', '/i?' + urllib.parse.urlencode(params))
        conn.getresponse()
        conn.close()
    except: # pylint: disable=bare-except
        LOGGER.debug('Collection request failed') 
开发者ID:singer-io,项目名称:target-stitch,代码行数:21,代码来源:__init__.py

示例10: _Request

# 需要导入模块: import http [as 别名]
# 或者: from http import client [as 别名]
def _Request(self, method, headers=None, post_data=None, json_root=None):
        if headers is None:
            headers = {}
        headers.update(self.api_headers.items())
        try:
            request = urllib.request.Request(self.api_url + method, post_data, headers)
            response = urllib.request.urlopen(request)
            try:
                response_json = json.loads(response.read().decode('utf-8'))
                if not json_root:
                    json_root = method
                if not json_root in response_json:
                    raise exchange_api.ExchangeException('JSON root "%s" not in "%s".' %
                                                         (json_root, method))
                return response_json[json_root]
            finally:
                response.close()
        except (urllib.error.URLError, urllib.error.HTTPError, http.client.HTTPException,
                ValueError) as e:
            raise exchange_api.ExchangeException(e) 
开发者ID:ericjang,项目名称:cryptocurrency_arbitrage,代码行数:22,代码来源:coinex_api_v2.py

示例11: handle_expect_100

# 需要导入模块: import http [as 别名]
# 或者: from http import client [as 别名]
def handle_expect_100(self):
        """Decide what to do with an "Expect: 100-continue" header.

        If the client is expecting a 100 Continue response, we must
        respond with either a 100 Continue or a final response before
        waiting for the request body. The default is to always respond
        with a 100 Continue. You can behave differently (for example,
        reject unauthorized requests) by overriding this method.

        This method should either return True (possibly after sending
        a 100 Continue response) or send an error response and return
        False.

        """
        self.send_response_only(HTTPStatus.CONTINUE)
        self.end_headers()
        return True 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:19,代码来源:server.py

示例12: log_message

# 需要导入模块: import http [as 别名]
# 或者: from http import client [as 别名]
def log_message(self, format, *args):
        """Log an arbitrary message.

        This is used by all other logging functions.  Override
        it if you have specific logging wishes.

        The first argument, FORMAT, is a format string for the
        message to be logged.  If the format string contains
        any % escapes requiring parameters, they should be
        specified as subsequent arguments (it's just like
        printf!).

        The client ip and current date/time are prefixed to
        every message.

        """

        sys.stderr.write("%s - - [%s] %s\n" %
                         (self.address_string(),
                          self.log_date_time_string(),
                          format%args)) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:23,代码来源:server.py

示例13: _enable_http_debugging

# 需要导入模块: import http [as 别名]
# 或者: from http import client [as 别名]
def _enable_http_debugging(self):
        import logging
        import http.client
        http.client.HTTPConnection.debuglevel = 1
        logging.basicConfig()
        logging.getLogger().setLevel(logging.DEBUG)
        requests_log = logging.getLogger('requests.packages.urllib3')
        requests_log.setLevel(logging.DEBUG)
        requests_log.propagate = True 
开发者ID:sassoftware,项目名称:python-esppy,代码行数:11,代码来源:connection.py

示例14: create_project

# 需要导入模块: import http [as 别名]
# 或者: from http import client [as 别名]
def create_project(self, proj, **kwargs):
        '''
        Create a new Project object

        Notes
        -----
        This method does not add the project to the server.  The
        returned object is client-side only until you install the project
        using :meth:`load_project`.

        Parameters
        ----------
        proj : string
            Either the name of the project, or a filename / URL
            pointing to a project definition
        kwargs : keyword arguments
            Optional parameters to the Project constructor.
            These are only used in the `project` argument is a
            project name.

        See Also
        --------
        :meth:`load_project`

        Returns
        -------
        :class:`Project`

        '''
        if os.path.isfile(proj) or re.match(r'\w+://', proj):
            out = project.Project.from_xml(get_project_data(proj))
        elif proj.startswith('<') and proj.endswith('>'):
            out = project.Project.from_xml(proj)
        else:
            out = project.Project(proj, **kwargs)
        out.session = self.session
        return out 
开发者ID:sassoftware,项目名称:python-esppy,代码行数:39,代码来源:connection.py

示例15: from_import

# 需要导入模块: import http [as 别名]
# 或者: from http import client [as 别名]
def from_import(module_name, *symbol_names, **kwargs):
    """
    Example use:
        >>> HTTPConnection = from_import('http.client', 'HTTPConnection')
        >>> HTTPServer = from_import('http.server', 'HTTPServer')
        >>> urlopen, urlparse = from_import('urllib.request', 'urlopen', 'urlparse')

    Equivalent to this on Py3:

        >>> from module_name import symbol_names[0], symbol_names[1], ...

    and this on Py2:

        >>> from future.moves.module_name import symbol_names[0], ...

    or:

        >>> from future.backports.module_name import symbol_names[0], ...

    except that it also handles dotted module names such as ``http.client``.
    """

    if PY3:
        return __import__(module_name)
    else:
        if 'backport' in kwargs and bool(kwargs['backport']):
            prefix = 'future.backports'
        else:
            prefix = 'future.moves'
        parts = prefix.split('.') + module_name.split('.')
        module = importlib.import_module(prefix + '.' + module_name)
        output = [getattr(module, name) for name in symbol_names]
        if len(output) == 1:
            return output[0]
        else:
            return output 
开发者ID:Soft8Soft,项目名称:verge3d-blender-addon,代码行数:38,代码来源:__init__.py


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