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


Python Response.headers['Content-Length']方法代码示例

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


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

示例1: build_response

# 需要导入模块: from requests import Response [as 别名]
# 或者: from requests.Response import headers['Content-Length'] [as 别名]
def build_response(request, data, code, encoding):
    '''Builds a response object from the data returned by ftplib, using the
    specified encoding.'''
    response = Response()

    response.encoding = encoding

    # Fill in some useful fields.
    response.raw = data
    response.url = request.url
    response.request = request
    response.status_code = int(code.split()[0])
    if hasattr(data, "content_len"):
        response.headers['Content-Length'] = str(data.content_len)

    # Make sure to seek the file-like raw object back to the start.
    response.raw.seek(0)

    # Run the response hook.
    response = dispatch_hook('response', request.hooks, response)
    return response
开发者ID:Forever-Young,项目名称:requests-ftp,代码行数:23,代码来源:ftp.py

示例2: send

# 需要导入模块: from requests import Response [as 别名]
# 或者: from requests.Response import headers['Content-Length'] [as 别名]
    def send(self, request, stream=False, verify=None, cert=None, proxies=None,
            timeout=None):
        """issue request"""

        data = url_unquote(request.url[len('data:'):])

        if ',' not in data:
            raise InvalidURL('data URL missing comma')

        mime, content = data.split(',', 1)
        content = content.strip()

        base64 = False
        charset = None

        while ';' in mime:
            mime, encoding_spec = mime.rsplit(';', 1)
            encoding_spec = encoding_spec.strip()
            if encoding_spec == 'base64':
                base64 = True
            elif not encoding_spec.startswith('charset='):
                raise InvalidURL(
                    'unrecognized encoding parameter: %r' % encoding_spec
                )
            else:
                charset = encoding_spec[len('charset='):]

        try:
            if base64:
                content = a2b_base64(content)

            content_type = mime.strip()
            if charset:
                content_type += "; charset=" + charset

            response = Response()
            response.url = request.url
            response.headers['Date'] = formatdate(timeval=None, localtime=True)

            if request.method in ('GET', 'HEAD'):
                response.status_code = 200
                response.headers['Content-Length'] = len(content)
                response.headers['Last-Modified'] = formatdate()
                response.headers['Content-Type'] = content_type
                if charset:
                    response.encoding = charset
                response.raw = StringIO(str(content))
            else:
                response.status_code = 405
                response.headers['Status'] = '405 Method Not Allowed'
        except Exception:
            response.status_code = 500
            response.headers['Status'] = '500 Internal Server Error'
            response.raw = StringIO(format_exc())

        # context
        response.request = request
        response.connection = self

        # hooks
        response = dispatch_hook('response', request.hooks, response)

        # streaming
        if not stream:
            response.content

        return response
开发者ID:jvantuyl,项目名称:requests-data,代码行数:69,代码来源:adapters.py

示例3: send

# 需要导入模块: from requests import Response [as 别名]
# 或者: from requests.Response import headers['Content-Length'] [as 别名]
    def send(self, request, **kwargs):
        """ Wraps a file, described in request, in a Response object.

            :param request: The PreparedRequest` being "sent".
            :returns: a Response object containing the file
        """

        # Check that the method makes sense. Only support GET
        if request.method not in ("GET", "HEAD"):
            raise ValueError("Invalid request method %s" % request.method)

        # Parse the URL
        url_parts = urlparse(request.url)

        # Reject URLs with a hostname component
        if url_parts.netloc and url_parts.netloc != "localhost":
            raise ValueError("file: URLs with hostname components are not permitted")

        resp = Response()

        # Open the file, translate certain errors into HTTP responses
        # Use urllib's unquote to translate percent escapes into whatever
        # they actually need to be
        try:
            # Split the path on / (the URL directory separator) and decode any
            # % escapes in the parts
            path_parts = [unquote(p) for p in url_parts.path.split('/')]

            # Strip out the leading empty parts created from the leading /'s
            while path_parts and not path_parts[0]:
                path_parts.pop(0)

            # If os.sep is in any of the parts, someone fed us some shenanigans.
            # Treat is like a missing file.
            if any(os.sep in p for p in path_parts):
                raise IOError(errno.ENOENT, os.strerror(errno.ENOENT))

            # Look for a drive component. If one is present, store it separately
            # so that a directory separator can correctly be added to the real
            # path, and remove any empty path parts between the drive and the path.
            # Assume that a part ending with : or | (legacy) is a drive.
            if path_parts and (path_parts[0].endswith('|') or
                               path_parts[0].endswith(':')):
                path_drive = path_parts.pop(0)
                if path_drive.endswith('|'):
                    path_drive = path_drive[:-1] + ':'

                while path_parts and not path_parts[0]:
                    path_parts.pop(0)
            else:
                path_drive = ''

            # Try to put the path back together
            # Join the drive back in, and stick os.sep in front of the path to
            # make it absolute.
            path = path_drive + os.sep + os.path.join(*path_parts)

            # Check if the drive assumptions above were correct. If path_drive
            # is set, and os.path.splitdrive does not return a drive, it wasn't
            # reall a drive. Put the path together again treating path_drive
            # as a normal path component.
            if path_drive and not os.path.splitdrive(path):
                path = os.sep + os.path.join(path_drive, *path_parts)

            # Use io.open since we need to add a release_conn method, and
            # methods can't be added to file objects in python 2.
            resp.raw = io.open(path, "rb")
            resp.raw.release_conn = resp.raw.close
        except IOError as e:
            if e.errno == errno.EACCES:
                resp.status_code = codes.forbidden
            elif e.errno == errno.ENOENT:
                resp.status_code = codes.not_found
            else:
                resp.status_code = codes.bad_request

            # Wrap the error message in a file-like object
            # The error message will be localized, try to convert the string
            # representation of the exception into a byte stream
            resp_str = str(e).encode(locale.getpreferredencoding(False))
            resp.raw = BytesIO(resp_str)
            resp.headers['Content-Length'] = len(resp_str)

            # Add release_conn to the BytesIO object
            resp.raw.release_conn = resp.raw.close
        else:
            resp.status_code = codes.ok

            # If it's a regular file, set the Content-Length
            resp_stat = os.fstat(resp.raw.fileno())
            if stat.S_ISREG(resp_stat.st_mode):
                resp.headers['Content-Length'] = resp_stat.st_size

        return resp
开发者ID:lheston,项目名称:lab1,代码行数:96,代码来源:requests_file.py

示例4: send

# 需要导入模块: from requests import Response [as 别名]
# 或者: from requests.Response import headers['Content-Length'] [as 别名]
    def send(self, request, **kwargs):
        """ Wraps a file, described in request, in a Response object.

            :param request: The PreparedRequest` being "sent".
            :returns: a Response object containing the file
        """

        # Check that the method makes sense. Only support GET
        if request.method != "GET":
            raise ValueError("Invalid request method %s" % request.method)

        # Parse the URL
        url_parts = urlparse(request.url)

        # Reject URLs with a hostname component
        if url_parts.netloc and url_parts.netloc != "localhost":
            raise ValueError("file: URLs with hostname components are not permitted")

        resp = Response()

        # Open the file, translate certain errors into HTTP responses
        # Use urllib's unquote to translate percent escapes into whatever
        # they actually need to be
        try:
            # Split the path on / (the URL directory separator) and decode any
            # % escapes in the parts
            path_parts = [unquote(p) for p in url_parts.path.split('/')]

            # If os.sep is in any of the parts, someone fed us some shenanigans.
            # Treat is like a missing file.
            if any(os.sep in p for p in path_parts):
                raise IOError(errno.ENOENT, os.strerror(errno.ENOENT))

            # Put it the path back together
            # [0] will be an empty string, so stick os.sep in there to make
            # the path absolute
            path_parts[0] = os.sep
            path = os.path.join(*path_parts)

            resp.raw = open(path, "rb")
        except IOError as e:
            if e.errno == errno.EACCES:
                resp.status_code = 403
            elif e.errno == errno.ENOENT:
                resp.status_code = 404
            else:
                resp.status_code = 400

            # Wrap the error message in a file-like object
            # The error message will be localized, try to convert the string
            # representation of the exception into a byte stream
            resp_str = str(e).encode(locale.nl_langinfo(locale.CODESET))
            resp.raw = BytesIO(resp_str)
            resp.headers['Content-Length'] = len(resp_str)
        else:
            resp.status_code = 200

            # If it's a regular file, set the Content-Length
            resp_stat = os.fstat(resp.raw.fileno())
            if stat.S_ISREG(resp_stat.st_mode):
                resp.headers['Content-Length'] = resp_stat.st_size

        return resp
开发者ID:MartinLidy,项目名称:LSTM-GA-StockTrader,代码行数:65,代码来源:requests_file.py

示例5: send

# 需要导入模块: from requests import Response [as 别名]
# 或者: from requests.Response import headers['Content-Length'] [as 别名]
    def send(
            self, request, stream=False, verify=None, cert=None, proxies=None,
            timeout=None
        ):
        """issue request"""

        fname = url_unquote(request.url[len('file://'):])
        if not fname:
            raise InvalidURL('missing file name')
        if '/' not in fname:
            raise InvalidURL(
                'hostname without filename (perhaps missing a /?)'
            )
        host, fname = fname.split('/', 1)
        fname = self.resolve_host(host, fname)

        response = Response()
        response.url = request.url
        response.headers['Date'] = formatdate(timeval=None, localtime=True)

        try:
            if request.method in ('GET', 'HEAD'):
                statdata = stat(fname)
                etag = '"%s/%s/%s' \
                    % (statdata.st_dev, statdata.st_ino, statdata.st_mtime)
                if S_ISLNK(statdata.st_mode):
                    # handle relative symlinks!
                    target_file = abspath(readlink(fname))
                    response.status_code = 302
                    response.headers['Status'] = '302 Found'
                    response.headers['Location'] = \
                        url_quote('file://' + target_file)
                elif S_ISDIR(statdata.st_mode):
                    response.status_code = 200
                    response.headers['Status'] = '200 Ok'
                    body = \
                        """<html><head><title>%s</title></head><body><ul>""" \
                        % fname
                    for subfname in sorted(listdir(fname)):
                        body += '<li><a href="file://' + \
                                url_quote(subfname) + '">' + \
                                html_escape(fname) + '</a></li>'
                    body += '</body></html>'
                    response.headers['ETag'] = 'W/' + etag
                    response.raw = StringIO(body)
                elif S_ISREG(statdata.st_mode):
                    response.status_code = 200
                    response.headers['Content-Length'] = statdata.st_size
                    response.headers['Last-Modified'] = formatdate(
                        timeval=statdata.st_mtime,
                        localtime=True
                    )
                    mt, enc = guess_mime_type(request.url, strict=False)
                    if mt is None:
                        mt = 'application/octet-stream'
                    if enc is not None:
                        response.headers['Content-Encoding'] = enc
                    response.headers['Content-Type'] = mt
                    response.headers['ETag'] = etag
                    if request.method == 'GET':
                        response.raw = open(fname, 'r')
                else:
                    response.status_code = 500
                    response.headers['Status'] = '500 Internal Server Error'
            elif request.method == 'PUT':
                open(fname, 'w').write(request.body)  # FIXME: Is this right?
                response.status_code = 200
                response.headers['Status'] = '200 Ok'
            elif request.method == 'POST':
                if exists(fname):  # FIXME: Is this right?
                    response.status_code = 409
                    response.headers['Status'] = '409 Conflict'
                else:
                    open(fname, 'w').write(request.body)
            elif request.method == 'DELETE':
                unlink(fname)
                response.status_code = 200
                response.headers['Status'] = '200 Ok'
            else:
                response.status_code = 405
                response.headers['Status'] = '405 Method Not Allowed'
        except OSError as e:
            if e.errno == errno.ENOENT:
                if request.method == 'DELETE':
                    response.status_code = 410
                    response.headers['Status'] = '410 Gone'
                else:
                    response.status_code = 404
                    response.headers['Status'] = '404 Not Found'
            elif e.errno == errno.EISDIR:
                response.status_code = 405
                response.headers['Status'] = '405 Method Not Allowed'
                response.raw = StringIO('Cannot %r a directory...'
                    % request.method)
            elif e.errno == errno.EACCES:
                response.status_code = 403
                response.headers['Status'] = '403 Forbidden'
            else:
                response.status_code = 500
                response.headers['Status'] = '500 Internal Server Error'
#.........这里部分代码省略.........
开发者ID:dougluce,项目名称:requests-file,代码行数:103,代码来源:adapters.py


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