• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python httputil.format_timestamp函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中tornado.httputil.format_timestamp函数的典型用法代码示例。如果您正苦于以下问题:Python format_timestamp函数的具体用法?Python format_timestamp怎么用?Python format_timestamp使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: get

    def get(self, distro=None, comp=None):

        db = self.settings['db']
        (expired, dt) = yield self._cache_expired('components', {'distro': distro, 'component': comp})
        if not expired:
            self.set_status(304)
            return
        if not dt:
            self.set_status(404)
            return
        self.add_header('Last-Modified', httputil.format_timestamp(dt))
        self.set_header('Content-Type', 'application/octet-stream')

        doc = yield db.cacus.components.find_one({'distro': distro, 'component': comp})
        if doc:
            s = common.config['repo_daemon']
            if s['proxy_storage']:
                headers = [ ('Content-Length', doc['size']), ('Last-Modified', httputil.format_timestamp(dt)) ]
                yield self.stream_from_storage(doc['sources_file'], headers=headers)
            else:
                # we use x-accel-redirect instead of direct proxying via storage plugin to allow 
                # user to offload cacus' StorageHandler if current storage allows it
                url = os.path.join(s['repo_base'], s['storage_subdir'], doc['sources_file'])
                app_log.info("Redirecting %s/%s/source/Sources to %s", distro, comp, arch, url)
                self.add_header("X-Accel-Redirect", url)
                self.set_status(200)
        else:
            self.set_status(404)
开发者ID:beebeeep,项目名称:cacus,代码行数:28,代码来源:repo_daemon.py


示例2: rel_as_dict

 def rel_as_dict(self, rel) :
     return {"uuid" : None if rel.uuid.startswith("pseudo:") else rel.uuid,
             "date_created" : httputil.format_timestamp(rel.date_created),
             "deleted" : getattr(rel, "deleted", None),
             "name" : rel.name,
             "subject" : rel.subject_uuid,
             "object" : rel.object_uuid,
             "payload" : rel.payload}
开发者ID:kmill,项目名称:metaview2,代码行数:8,代码来源:methods.py


示例3: set_cookie

    def set_cookie(self, name, value, expires_days=30, version=None,
                   domain=None, expires=None, path="/", **kwargs):
        """ Sets the given cookie name/value with the given options. Set value
        to None to clear. The cookie value is secured using
        `flexx.config.cookie_secret`; don't forget to set that config
        value in your server. Additional keyword arguments are set on
        the Cookie.Morsel directly.
        """
        # This code is taken (in modified form) from the Tornado project
        # Copyright 2009 Facebook
        # Licensed under the Apache License, Version 2.0

        # Assume tornado is available ...
        from tornado.escape import native_str
        from tornado.httputil import format_timestamp
        from tornado.web import create_signed_value

        # Clear cookie?
        if value is None:
            value = ""
            expires = datetime.datetime.utcnow() - datetime.timedelta(days=365)
        else:
            secret = config.cookie_secret
            value = create_signed_value(secret, name, value, version=version,
                                        key_version=None)

        # The cookie library only accepts type str, in both python 2 and 3
        name = native_str(name)
        value = native_str(value)
        if re.search(r"[\x00-\x20]", name + value):
            # Don't let us accidentally inject bad stuff
            raise ValueError("Invalid cookie %r: %r" % (name, value))
        if name in self._cookies:
            del self._cookies[name]
        self._cookies[name] = value
        morsel = self._cookies[name]
        if domain:
            morsel["domain"] = domain
        if expires_days is not None and not expires:
            expires = datetime.datetime.utcnow() + datetime.timedelta(
                days=expires_days)
        if expires:
            morsel["expires"] = format_timestamp(expires)
        if path:
            morsel["path"] = path
        for k, v in kwargs.items():
            if k == 'max_age':
                k = 'max-age'
            # skip falsy values for httponly and secure flags because
            # SimpleCookie sets them regardless
            if k in ['httponly', 'secure'] and not v:
                continue
            morsel[k] = v

        self._exec('document.cookie = "%s";' %
                   morsel.OutputString().replace('"', '\\"'))
开发者ID:Konubinix,项目名称:flexx,代码行数:56,代码来源:_session.py


示例4: redirect_after

 def redirect_after(self, request):
     "Perform a redirect to ``target``"
     date = request.params.get("date")
     if date:
         retry_after = str(httputil.format_timestamp(datetime.fromtimestamp(float(date))))
     else:
         retry_after = "1"
     target = request.params.get("target", "/")
     headers = [("Location", target), ("Retry-After", retry_after)]
     return Response(status="303 See Other", headers=headers)
开发者ID:Disassem,项目名称:urllib3,代码行数:10,代码来源:handlers.py


示例5: blob_as_dict

 def blob_as_dict(self, blob, with_content=False) :
     ret = {"uuid" : blob.uuid,
            "date_created" : httputil.format_timestamp(blob.date_created),
            "editor_email" : blob.editor_email,
            "content_type" : blob.content_type}
     if blob.content_type.startswith("mime:text/") :
         ret["summary"] = self.blob_summary(blob)
     if with_content :
         ret["content"] = blob.content.stuff
     return ret
开发者ID:kmill,项目名称:metaview2,代码行数:10,代码来源:methods.py


示例6: set_default_headers

 def set_default_headers(self):
     default_headers = {
         "Server": "TornadoServer/%s" % tornado.version,
         "Content-Type": "text/event-stream",
         "access-control-allow-origin": "*",
         "connection": "keep-alive",
         "Date": httputil.format_timestamp(time.time()),
     }
     default_headers.update(self.custom_headers())
     self._headers = httputil.HTTPHeaders(default_headers)
开发者ID:digideskio,项目名称:tornado-eventsource,代码行数:10,代码来源:handler.py


示例7: redirect_after

 def redirect_after(self, request):
     "Perform a redirect to ``target``"
     date = request.params.get('date')
     if date:
         retry_after = str(httputil.format_timestamp(
                 datetime.fromtimestamp(float(date))))
     else:
         retry_after = '1'
     target = request.params.get('target', '/')
     headers = [('Location', target), ('Retry-After', retry_after)]
     return Response(status='303 See Other', headers=headers)
开发者ID:NickMinnellaCS96,项目名称:urllib3,代码行数:11,代码来源:handlers.py


示例8: clear

 def clear(self):
     """Resets all headers and content for this response."""
     self._headers = httputil.HTTPHeaders({
         "Server": "Durotar/%s" % durotar.version,
         "Content-Type": "text/html; charset=UTF-8",
         "Date": httputil.format_timestamp(time.time()),
     })
     self.set_default_headers()
     self._write_buffer = []
     self._status_code = 200
     self._reason = httputil.responses[200]
开发者ID:marslabtron,项目名称:durotar,代码行数:11,代码来源:web.py


示例9: assert_modified

    def assert_modified(self, url, mod_date):
        response = self.fetch(
            url, if_modified_since=(mod_date - timedelta(seconds=1)))

        # 200 OK, not 304 Not Modified.
        self.assertEqual(200, response.code)
        self.assertEqual(
            httputil.format_timestamp(mod_date),
            response.headers['Last-Modified'])

        response = self.fetch(url, if_modified_since=mod_date)
        self.assertEqual(304, response.code)
开发者ID:BeginMan,项目名称:motor-blog,代码行数:12,代码来源:__init__.py


示例10: _convert_header_value

 def _convert_header_value(self, value):
     if isinstance(value, bytes):
         pass
     elif isinstance(value, unicode_type):
         value = value.encode("utf-8")
     elif isinstance(value, numbers.Integral):
         return str(value)
     elif isinstance(value, datetime.datetime):
         return httputil.format_timestamp(value)
     else:
         raise TypeError("Unsupported header value %r" % value)
     if len(value) > 4000 or RequestHandler._INVALID_HEADER_CHAR_RE.search(value):
         raise ValueError("Unsafe header value %r", value)
     return value
开发者ID:confucianzuoyuan,项目名称:tinytornado,代码行数:14,代码来源:web.py


示例11: upload_file

    def upload_file(self, file_data, file_path, content_type=None):
        """上传文件到oss服务器上

        :param file_data: 文件的数据
        :param file_path: 保存到OSS的路径
        :return:
        """
        oss = OssAPI(self.regional_node, self.id, self.key)
        expires = format_timestamp(datetime.datetime.today() + datetime.timedelta(days=+90))
        header = {'expires': expires,
                  'Cache-Control': 'max-age=%s' % (90*24*60*60)}
        if content_type:
            res = oss.put_object_from_string(self.bucket, file_path, file_data, headers=header, content_type=content_type)
        else:
            res = oss.put_object_from_string(self.bucket, file_path, file_data)
        if 200 == res.status:
            return True, file_path
        else:
            # log
            res_message = "OSS ERROR\n%s\n%s" % (res.status, res.read())
            logging.info(res_message)
            return False, u'上传文件出错!'
开发者ID:yl812708519,项目名称:tornado_test_web,代码行数:22,代码来源:oss_factory.py


示例12: force_clear_cookie

    def force_clear_cookie(self, name, path="/", domain=None):
        """Deletes the cookie with the given name.

        Tornado's cookie handling currently (Jan 2018) stores cookies in a dict
        keyed by name, so it can only modify one cookie with a given name per
        response. The browser can store multiple cookies with the same name
        but different domains and/or paths. This method lets us clear multiple
        cookies with the same name.

        Due to limitations of the cookie protocol, you must pass the same
        path and domain to clear a cookie as were used when that cookie
        was set (but there is no way to find out on the server side
        which values were used for a given cookie).
        """
        name = escape.native_str(name)
        expires = datetime.datetime.utcnow() - datetime.timedelta(days=365)

        morsel = Morsel()
        morsel.set(name, '', '""')
        morsel['expires'] = httputil.format_timestamp(expires)
        morsel['path'] = path
        if domain:
            morsel['domain'] = domain
        self.add_header("Set-Cookie", morsel.OutputString())
开发者ID:SylvainCorlay,项目名称:notebook,代码行数:24,代码来源:handlers.py


示例13: check

 def check(self, value):
     self.assertEqual(format_timestamp(value), self.EXPECTED)
开发者ID:00zhengfu00,项目名称:viewfinder,代码行数:2,代码来源:httputil_test.py


示例14: test_format

 def test_format(self):
     format = "%A, %d-%b-%y %H:%M:%S GMT"
     expected = 'Sunday, 27-Jan-13 18:43:20 GMT'
     self.assertEqual(format_timestamp(self.TIMESTAMP, format),
                      expected)
开发者ID:fabiant7t,项目名称:tornado,代码行数:5,代码来源:httputil_test.py


示例15: fetch

    def fetch(self, target, refresh=False, cache=True, delay=None,
              follow=True, extract=None, **kwargs):
        """Fetch a URL from the wild, but first check the Cache.

        Args:
            target (str or HTTPRequest): to be fetched.
            refresh (bool, optional): should the CacheClient ask the remote
                source to refresh cached files?  Defaults to False.
            cache (bool, optional): should results be cached? Defaults to True.
            delay (int, optional): a period, in seconds, for which the client
                should delay before sending the next request after a successful
                fetch.
            follow (bool, optional): should redirects be followed? If False,
                the Response object will only contain a string to the redirect
                url target. Defaults to True.
            extract (str, optional): if supplied, the Client will try to
                extract a filename of `extract` from any resulting compressed
                file. 
            **kwargs (misc., optional): any additional keyword arguments that
                should be passed when a new HTTPRequest is initialized. 

        Returns (/ Raises):
            response (cache.Response or None): a named tuple containing values:
                - `url` (string): the url of the fetch/cache load.
                - `buffer` (BytesIO): the body of the fetch result.
                - `fresh` (bool): True if the Response object is the result of
                    a fresh response from the target server.
                or None if an error occurred (which is logged).
        """
        request = self._cached_http_request(target, follow_redirects=follow,
                                            **kwargs)
        self._log.debug("Fetching file @ {}".format(request.url))
        if not refresh and IF_MODIFIED_SINCE in request.headers:
            self._log.debug("Have cached file, not asking for a refresh.")
            response = self.cache.load(request.url)
            raise gen.Return(response)
        elif IF_MODIFIED_SINCE in request.headers:
            last_mod = request.headers[IF_MODIFIED_SINCE]
            age = datetime.datetime.now() - last_mod
            if age.seconds < REFRESH_COOLDOWN:
                self._log.debug("Have recent cached file, not refreshing.")
                raise gen.Return(self.cache.load(request.url))
            else:
                request.headers[IF_MODIFIED_SINCE] = format_timestamp(last_mod)
        try:
            response = yield self._client.fetch(request)
        except HTTPError as err:
            if err.code == FILE_UNCHANGED:
                self._log.debug("File unchanged, using cached version.")
                raise gen.Return(self.cache.load(request.url))

            # If we get a 302, and we're expecting it, return the location and
            # fresh to indicate that the destination is a new one (since we
            # had to reach out to the server.
            elif err.code == SOFT_REDIRECT and not follow:
                loc = err.response.headers[LOCATION_HEADER]
                self._log.debug('Redirected to {}, not following'.format(loc))
                response = Response(BytesIO(loc), request.url, True)
                raise gen.Return(response)
            else:
                self._log.error(
                    "{0} ({1}) fetching {2}".format(err, err.code, request.url))
                raise gen.Return(None)

        except Exception as excp:
            self._log.exception(excp)
            raise gen.Return(None)
        else:
            self._log.debug("Got fresh file @ {0}".format(request.url))
            if extract:
                response.buffer = decompress_response(response.buffer, extract)

            if cache:
                self._log.debug("Caching {0}".format(request.url))
                self.cache_response(response, overwrite=True)
            response = Response(response.buffer, request.url, True)
            raise gen.Return(response)
        finally:
            if delay:
                self._log.debug("Pausing @ {0} for {1} sec(s)".format(
                    self.ioloop.time(), delay))
                yield gen.sleep(delay)
开发者ID:graypools,项目名称:client,代码行数:82,代码来源:__init__.py


示例16: __init__


#.........这里部分代码省略.........
           or return the 3xx response?
        :arg int max_redirects: Limit for ``follow_redirects``
        :arg string user_agent: String to send as ``User-Agent`` header
        :arg bool use_gzip: Request gzip encoding from the server
        :arg string network_interface: Network interface to use for request.
           ``curl_httpclient`` only; see note below.
        :arg callable streaming_callback: If set, ``streaming_callback`` will
           be run with each chunk of data as it is received, and
           ``HTTPResponse.body`` and ``HTTPResponse.buffer`` will be empty in
           the final response.
        :arg callable header_callback: If set, ``header_callback`` will
           be run with each header line as it is received (including the
           first line, e.g. ``HTTP/1.0 200 OK\r\n``, and a final line
           containing only ``\r\n``.  All lines include the trailing newline
           characters).  ``HTTPResponse.headers`` will be empty in the final
           response.  This is most useful in conjunction with
           ``streaming_callback``, because it's the only way to get access to
           header data while the request is in progress.
        :arg callable prepare_curl_callback: If set, will be called with
           a ``pycurl.Curl`` object to allow the application to make additional
           ``setopt`` calls.
        :arg string proxy_host: HTTP proxy hostname.  To use proxies,
           ``proxy_host`` and ``proxy_port`` must be set; ``proxy_username`` and
           ``proxy_pass`` are optional.  Proxies are currently only supported
           with ``curl_httpclient``.
        :arg int proxy_port: HTTP proxy port
        :arg string proxy_username: HTTP proxy username
        :arg string proxy_password: HTTP proxy password
        :arg bool allow_nonstandard_methods: Allow unknown values for ``method``
           argument?
        :arg bool validate_cert: For HTTPS requests, validate the server's
           certificate?
        :arg string ca_certs: filename of CA certificates in PEM format,
           or None to use defaults.  See note below when used with
           ``curl_httpclient``.
        :arg bool allow_ipv6: Use IPv6 when available?  Default is false in
           ``simple_httpclient`` and true in ``curl_httpclient``
        :arg string client_key: Filename for client SSL key, if any.  See
           note below when used with ``curl_httpclient``.
        :arg string client_cert: Filename for client SSL certificate, if any.
           See note below when used with ``curl_httpclient``.
        :arg bool expect_100_continue: If true, send the
           ``Expect: 100-continue`` header and wait for a continue response
           before sending the request body.  Only supported with
           simple_httpclient.


        .. note::

            When using ``curl_httpclient`` certain options may be
            inherited by subsequent fetches because ``pycurl`` does
            not allow them to be cleanly reset.  This applies to the
            ``ca_certs``, ``client_key``, ``client_cert``, and
            ``network_interface`` arguments.  If you use these
            options, you should pass them on every request (you don't
            have to always use the same values, but it's not possible
            to mix requests that specify these options with ones that
            use the defaults).

        .. versionadded:: 3.1
           The ``auth_mode`` argument.

        .. versionadded:: 4.0
           The ``body_producer`` and ``expect_100_continue`` arguments.
        """
        # Note that some of these attributes go through property setters
        # defined below.
        self.headers = headers
        if if_modified_since:
            self.headers["If-Modified-Since"] = httputil.format_timestamp(
                if_modified_since)
        self.proxy_host = proxy_host
        self.proxy_port = proxy_port
        self.proxy_username = proxy_username
        self.proxy_password = proxy_password
        self.url = url
        self.method = method
        self.body = body
        self.body_producer = body_producer
        self.auth_username = auth_username
        self.auth_password = auth_password
        self.auth_mode = auth_mode
        self.connect_timeout = connect_timeout
        self.request_timeout = request_timeout
        self.follow_redirects = follow_redirects
        self.max_redirects = max_redirects
        self.user_agent = user_agent
        self.use_gzip = use_gzip
        self.network_interface = network_interface
        self.streaming_callback = streaming_callback
        self.header_callback = header_callback
        self.prepare_curl_callback = prepare_curl_callback
        self.allow_nonstandard_methods = allow_nonstandard_methods
        self.validate_cert = validate_cert
        self.ca_certs = ca_certs
        self.allow_ipv6 = allow_ipv6
        self.client_key = client_key
        self.client_cert = client_cert
        self.expect_100_continue = expect_100_continue
        self.start_time = time.time()
开发者ID:BingQiangChen,项目名称:tornado,代码行数:101,代码来源:httpclient.py


示例17: set_default_headers

 def set_default_headers(self):
   self._headers = httputil.HTTPHeaders({
     "Date": httputil.format_timestamp(time.time())
   })
开发者ID:pombredanne,项目名称:compactor,代码行数:4,代码来源:httpd.py


示例18: __init__

    def __init__(self, url, method="GET", headers=None, body=None,
                 auth_username=None, auth_password=None,
                 connect_timeout=None, request_timeout=None,
                 if_modified_since=None, follow_redirects=None,
                 max_redirects=None, user_agent=None, use_gzip=None,
                 network_interface=None, streaming_callback=None,
                 header_callback=None, prepare_curl_callback=None,
                 proxy_host=None, proxy_port=None, proxy_username=None,
                 proxy_password=None, allow_nonstandard_methods=None,
                 validate_cert=None, ca_certs=None,
                 allow_ipv6=None,
                 client_key=None, client_cert=None):
        r"""All parameters except ``url`` are optional.

        :arg string url: URL to fetch
        :arg string method: HTTP method, e.g. "GET" or "POST"
        :arg headers: Additional HTTP headers to pass on the request
        :type headers: `~tornado.httputil.HTTPHeaders` or `dict`
        :arg string auth_username: Username for HTTP "Basic" authentication
        :arg string auth_password: Password for HTTP "Basic" authentication
        :arg float connect_timeout: Timeout for initial connection in seconds
        :arg float request_timeout: Timeout for entire request in seconds
        :arg if_modified_since: Timestamp for ``If-Modified-Since`` header
        :type if_modified_since: `datetime` or `float`
        :arg bool follow_redirects: Should redirects be followed automatically
           or return the 3xx response?
        :arg int max_redirects: Limit for ``follow_redirects``
        :arg string user_agent: String to send as ``User-Agent`` header
        :arg bool use_gzip: Request gzip encoding from the server
        :arg string network_interface: Network interface to use for request
        :arg callable streaming_callback: If set, ``streaming_callback`` will
           be run with each chunk of data as it is received, and
           ``HTTPResponse.body`` and ``HTTPResponse.buffer`` will be empty in
           the final response.
        :arg callable header_callback: If set, ``header_callback`` will
           be run with each header line as it is received (including the
           first line, e.g. ``HTTP/1.0 200 OK\r\n``, and a final line
           containing only ``\r\n``.  All lines include the trailing newline
           characters).  ``HTTPResponse.headers`` will be empty in the final
           response.  This is most useful in conjunction with
           ``streaming_callback``, because it's the only way to get access to
           header data while the request is in progress.
        :arg callable prepare_curl_callback: If set, will be called with
           a ``pycurl.Curl`` object to allow the application to make additional
           ``setopt`` calls.
        :arg string proxy_host: HTTP proxy hostname.  To use proxies,
           ``proxy_host`` and ``proxy_port`` must be set; ``proxy_username`` and
           ``proxy_pass`` are optional.  Proxies are currently only supported
           with ``curl_httpclient``.
        :arg int proxy_port: HTTP proxy port
        :arg string proxy_username: HTTP proxy username
        :arg string proxy_password: HTTP proxy password
        :arg bool allow_nonstandard_methods: Allow unknown values for ``method``
           argument?
        :arg bool validate_cert: For HTTPS requests, validate the server's
           certificate?
        :arg string ca_certs: filename of CA certificates in PEM format,
           or None to use defaults.  Note that in ``curl_httpclient``, if
           any request uses a custom ``ca_certs`` file, they all must (they
           don't have to all use the same ``ca_certs``, but it's not possible
           to mix requests with ``ca_certs`` and requests that use the defaults.
        :arg bool allow_ipv6: Use IPv6 when available?  Default is false in
           ``simple_httpclient`` and true in ``curl_httpclient``
        :arg string client_key: Filename for client SSL key, if any
        :arg string client_cert: Filename for client SSL certificate, if any
        """
        if headers is None:
            headers = httputil.HTTPHeaders()
        if if_modified_since:
            headers["If-Modified-Since"] = httputil.format_timestamp(
                if_modified_since)
        self.proxy_host = proxy_host
        self.proxy_port = proxy_port
        self.proxy_username = proxy_username
        self.proxy_password = proxy_password
        self.url = url
        self.method = method
        self.headers = headers
        self.body = utf8(body)
        self.auth_username = auth_username
        self.auth_password = auth_password
        self.connect_timeout = connect_timeout
        self.request_timeout = request_timeout
        self.follow_redirects = follow_redirects
        self.max_redirects = max_redirects
        self.user_agent = user_agent
        self.use_gzip = use_gzip
        self.network_interface = network_interface
        self.streaming_callback = stack_context.wrap(streaming_callback)
        self.header_callback = stack_context.wrap(header_callback)
        self.prepare_curl_callback = stack_context.wrap(prepare_curl_callback)
        self.allow_nonstandard_methods = allow_nonstandard_methods
        self.validate_cert = validate_cert
        self.ca_certs = ca_certs
        self.allow_ipv6 = allow_ipv6
        self.client_key = client_key
        self.client_cert = client_cert
        self.start_time = time.time()
开发者ID:08opt,项目名称:tornado,代码行数:98,代码来源:httpclient.py


示例19: test_if_modified_since

 def test_if_modified_since(self):
     http_date = datetime.datetime.utcnow()
     request = HTTPRequest('http://example.com', if_modified_since=http_date)
     self.assertEqual(request.headers,
                      {'If-Modified-Since': format_timestamp(http_date)})
开发者ID:437049211,项目名称:PyQYT,代码行数:5,代码来源:httpclient_test.py


示例20: __init__

    def __init__(self, url, method="GET", headers=None, body=None,
                 auth_username=None, auth_password=None, auth_mode=None,
                 connect_timeout=None, request_timeout=None,
                 if_modified_since=None, follow_redirects=None,
                 max_redirects=None, user_agent=None, use_gzip=None,
                 network_interface=None, streaming_callback=None,
                 header_callback=None, prepare_curl_callback=None,
                 proxy_host=None, proxy_port=None, proxy_username=None,
                 proxy_password=None, allow_nonstandard_methods=None,
                 validate_cert=None, ca_certs=None,
                 allow_ipv6=None,
                 client_key=None, client_cert=None,
                 parent_trace=None, endpoint=None):
        r"""All parameters except ``url`` are optional.

        :arg string url: URL to fetch
        :arg string method: HTTP method, e.g. "GET" or "POST"
        :arg headers: Additional HTTP headers to pass on the request
        :arg body: HTTP body to pass on the request
        :type headers: `~tornado.httputil.HTTPHeaders` or `dict`
        :arg string auth_username: Username for HTTP authentication
        :arg string auth_password: Password for HTTP authentication
        :arg string auth_mode: Authentication mode; default is "basic".
           Allowed values are implementation-defined; ``curl_httpclient``
           supports "basic" and "digest"; ``simple_httpclient`` only supports
           "basic"
        :arg float connect_timeout: Timeout for initial connection in seconds
        :arg float request_timeout: Timeout for entire request in seconds
        :arg if_modified_since: Timestamp for ``If-Modified-Since`` header
        :type if_modified_since: `datetime` or `float`
        :arg bool follow_redirects: Should redirects be followed automatically
           or return the 3xx response?
        :arg int max_redirects: Limit for ``follow_redirects``
        :arg string user_agent: String to send as ``User-Agent`` header
        :arg bool use_gzip: Request gzip encoding from the server
        :arg string network_interface: Network interface to use for request.
           ``curl_httpclient`` only; see note below.
        :arg callable streaming_callback: If set, ``streaming_callback`` will
           be run with each chunk of data as it is received, and
           ``HTTPResponse.body`` and ``HTTPResponse.buffer`` will be empty in
           the final response.
        :arg callable header_callback: If set, ``header_callback`` will
           be run with each header line as it is received (including the
           first line, e.g. ``HTTP/1.0 200 OK\r\n``, and a final line
           containing only ``\r\n``.  All lines include the trailing newline
           characters).  ``HTTPResponse.headers`` will be empty in the final
           response.  This is most useful in conjunction with
           ``streaming_callback``, because it's the only way to get access to
           header data while the request is in progress.
        :arg callable prepare_curl_callback: If set, will be called with
           a ``pycurl.Curl`` object to allow the application to make additional
           ``setopt`` calls.
        :arg string proxy_host: HTTP proxy hostname.  To use proxies,
           ``proxy_host`` and ``proxy_port`` must be set; ``proxy_username`` and
           ``proxy_pass`` are optional.  Proxies are currently only supported
           with ``curl_httpclient``.
        :arg int proxy_port: HTTP proxy port
        :arg string proxy_username: HTTP proxy username
        :arg string proxy_password: HTTP proxy password
        :arg bool allow_nonstandard_methods: Allow unknown values for ``method``
           argument?
        :arg bool validate_cert: For HTTPS requests, validate the server's
           certificate?
        :arg string ca_certs: filename of CA certificates in PEM format,
           or None to use defaults.  See note below when used with
           ``curl_httpclient``.
        :arg bool allow_ipv6: Use IPv6 when available?  Default is false in
           ``simple_httpclient`` and true in ``curl_httpclient``
        :arg string client_key: Filename for client SSL key, if any.  See
           note below when used with ``curl_httpclient``.
        :arg string client_cert: Filename for client SSL certificate, if any.
           See note below when used with ``curl_httpclient``.
        :arg string parent_trace: parent trace id.
        :arg string endpoint: request endpoint.

        .. note::

            When using ``curl_httpclient`` certain options may be
            inherited by subsequent fetches because ``pycurl`` does
            not allow them to be cleanly reset.  This applies to the
            ``ca_certs``, ``client_key``, ``client_cert``, and
            ``network_interface`` arguments.  If you use these
            options, you should pass them on every request (you don't
            have to always use the same values, but it's not possible
            to mix requests that specify these options with ones that
            use the defaults).

        .. versionadded:: 3.1
           The ``auth_mode`` argument.
        """
        # Note that some of these attributes go through property setters
        # defined below.
        self.headers = headers
        if if_modified_since:
            self.headers["If-Modified-Since"] = httputil.format_timestamp(
                if_modified_since)
        self.proxy_host = proxy_host
        self.proxy_port = proxy_port
        self.proxy_username = proxy_username
        self.proxy_password = proxy_password
#.........这里部分代码省略.........
开发者ID:iambocai,项目名称:tornado,代码行数:101,代码来源:httpclient.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python httputil.parse_body_arguments函数代码示例发布时间:2022-05-27
下一篇:
Python httpserver.HTTPServer类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap