コード例 #1
0
def test_decode_content_with_deflate():
    res = Response()
    b = 'Hey Hey Hey'
    # Simulate inflate by chopping the headers off
    # the gzip encoded data
    res.body = zlib.compress(b)[2:-4]
    res.content_encoding = 'deflate'
    res.decode_content()
    eq_(res.body, b)
    eq_(res.content_encoding, None)
コード例 #2
0
def test_decode_content_gzip():
    from gzip import GzipFile
    io = StringIO()
    gzip_f = GzipFile(filename='', mode='w', fileobj=io)
    gzip_f.write('abc')
    gzip_f.close()
    body = io.getvalue()
    res = Response()
    res.content_encoding = 'gzip'
    res.body = body
    res.decode_content()
    eq_(res.body, 'abc')
コード例 #3
0
ファイル: backend.py プロジェクト: Black-Blaze/HTHS
    def handle_request(wrapper, request):
        #user_agent = request.environ.get('HTTP_USER_AGENT')
        response = Response()
        response.status_code = 200
        response.text = "Empty Response"

        handler, kwargs = wrapper.find_handler(request)
        compress = True
        if handler is not None:
            if (inspect.isclass(handler)):
                handler = getattr(handler(), request.method.lower(), None)
                if handler is not None:
                    handler(request, response, **kwargs)
                else:
                    wrapper.err503(response)
            else:
                handler(request, response, **kwargs)
            if compress:
                response.body = brotli.compress(response.text.encode())
                response.content_encoding = "br"
        else:
            try:
                try:
                    FileType, noText = wrapper.getFileType(request.path)
                    print(FileType, noText)
                    response.content_type = FileType
                    if (noText):
                        print("\n\n****************\n\n")
                        print("loc:", wrapper.root + "/static" + request.path)

                        response.body = open(
                            wrapper.root + "/static" + request.path,
                            "rb").read()
                    else:
                        print("\n\n****************\n\n")
                        print("loc:", wrapper.root + "/static" + request.path)

                        response.text = open(wrapper.root + "/static" +
                                             request.path).read()

                    response.cache_control = "max-age=" + str(
                        wrapper.staticCache)
                except Exception as e:
                    print(e)
                    wrapper.err404(response)
            except Exception as e:
                print(e)
                response.text = "Well My Work Was Not Clean Enough, but...<br><b>Thats A Server Problem</b>"
                response.status_code = 500
        return response
コード例 #4
0
ファイル: actions.py プロジェクト: mtpi/daffydav
def navigator():
    open_folders = json.loads(request.POST.get('open_folders', '[]'))
    # filer DirectoryAlone folders
    open_folders = [folder for folder in open_folders if not isdir_alone(folder)]
    log.debug('open_folders: ' + repr(open_folders))
    xml_tree = ET.TreeBuilder()
    xml_tree.start('span', {})
    helpers.folder_div(request.path_info, xml_tree, open_folders=open_folders)
    xml_tree.end('span')
    xml = xml_tree.close()
    resp = Response(ET.tostring(xml, encoding='utf-8').replace('&apos;', "'"))
    resp.content_type = 'text/html'
    resp.content_encoding = 'utf-8'
    return resp
コード例 #5
0
ファイル: wsgi.py プロジェクト: jvlomax/mancify
    def do_index(self, req):
        resp = Response()
        resp.content_type = b'text/html'
        resp.content_encoding = b'utf-8'
        resp.text = """\
<html>
<head><title>Mancify</title></head>
<body>
<h1>Mancify</h1>
<p>Probably the silliest webapp in the world...</p>
</body>
</html>
"""
        return resp
コード例 #6
0
ファイル: properties.py プロジェクト: mtpi/daffydav
    def __call__(self):
        "Generate the response"
        if self.xmlreq.find("{DAV:}prop"):
            # save only the tag of requested properties
            props = [prop.tag for prop in self.xmlreq.find("{DAV:}prop").getchildren()]
            resp_xml = self.gen_prop_tree(props)
        elif self.xmlreq.find("{DAV:}allprop") is not None:
            resp_xml = self.gen_prop_tree(self.ALLPROPS)
        elif self.xmlreq.find("{DAV:}propname") is not None:
            resp_xml = self.gen_prop_tree(self.ALLPROPS, only_names=True)
        else:
            raise exc.HTTPBadRequest(explanation="Unknown PROPFIND request body.")

        ## FIXME: fix unicode
        resp_body = '<?xml version="1.0" encoding="utf-8" ?>'
        resp_body += ET.tostring(resp_xml, encoding="utf-8")
        resp = Response(resp_body)
        resp.content_type = "application/xml"
        resp.content_encoding = "utf-8"
        resp.status_int = 207  # Multi Status
        return resp
コード例 #7
0
 def do_template(self, req, page, image=None):
     """
     Serve a Chameleon template-based page
     """
     resp = Response()
     resp.content_type = 'text/html'
     resp.content_encoding = 'utf-8'
     try:
         template = self.templates[page]
     except ValueError:
         self.not_found(req)
     resp.text = template(req=req,
                          page=page,
                          image=image,
                          helpers=self.helpers,
                          layout=self.layout,
                          flashes=self.flashes,
                          library=self.library,
                          camera=self.library.camera,
                          router=self.router)
     del self.flashes[:]
     return resp
コード例 #8
0
    def getResponse(self):
        rspD = self.__getD()
        #
        #  Build the WebOb response -
        #
        myResponse = Response()
        myResponse.status = rspD["STATUS_CODE"]
        myResponse.content_type = rspD["CONTENT_TYPE"]

        if isinstance(rspD["RETURN_STRING"], text_type):
            myResponse.text = rspD["RETURN_STRING"]
        else:
            myResponse.body = rspD["RETURN_STRING"]

        if "ENCODING" in rspD:
            myResponse.content_encoding = rspD["ENCODING"]
        if "DISPOSITION" in rspD:
            myResponse.content_disposition = rspD["DISPOSITION"]
        if "CHECKSUM_MD5" in rspD:
            myResponse.headers.add("CHECKSUM_MD5", rspD["CHECKSUM_MD5"])
        #
        return myResponse
コード例 #9
0
ファイル: wsgi.py プロジェクト: EaSonic/picroscopy
 def do_template(self, req, page, image=None):
     """
     Serve a Chameleon template-based page
     """
     resp = Response()
     resp.content_type = 'text/html'
     resp.content_encoding = 'utf-8'
     try:
         template = self.templates[page]
     except ValueError:
         self.not_found(req)
     resp.text = template(
         req=req,
         page=page,
         image=image,
         helpers=self.helpers,
         layout=self.layout,
         flashes=self.flashes,
         library=self.library,
         camera=self.library.camera,
         router=self.router)
     del self.flashes[:]
     return resp
コード例 #10
0
ファイル: server.py プロジェクト: Nupta/swift
                        request=request, conditional_response=True)
        response.headers['Content-Type'] = file.metadata.get('Content-Type',
                'application/octet-stream')
        for key, value in file.metadata.iteritems():
            if key.lower().startswith('x-object-meta-') or \
                    key.lower() in self.allowed_headers:
                response.headers[key] = value
        response.etag = file.metadata['ETag']
        response.last_modified = float(file.metadata['X-Timestamp'])
        response.content_length = file_size
        if response.content_length < KEEP_CACHE_SIZE and \
                'X-Auth-Token' not in request.headers and \
                'X-Storage-Token' not in request.headers:
            file.keep_cache = True
        if 'Content-Encoding' in file.metadata:
            response.content_encoding = file.metadata['Content-Encoding']
        response.headers['X-Timestamp'] = file.metadata['X-Timestamp']
        return request.get_response(response)

    def HEAD(self, request):
        """Handle HTTP HEAD requests for the Swift Object Server."""
        try:
            device, partition, account, container, obj = \
                split_path(unquote(request.path), 5, 5, True)
        except ValueError, err:
            resp = HTTPBadRequest(request=request)
            resp.content_type = 'text/plain'
            resp.body = str(err)
            return resp
        if self.mount_check and not check_mount(self.devices, device):
            return HTTPInsufficientStorage(drive=device, request=request)
コード例 #11
0
                                      retriever.total_file_size)
            content_length = slice_size
        else:
            status_int = httplib.OK

        # 2012-09-06 dougfort Ticket #44 (temporary Connection: close)
        response.headers["Connection"] = "close"
        response.last_modified = last_modified
        response.content_length = content_length

        if content_type is None:
            response.content_type = "application/octet-stream"
        else:
            response.content_type = content_type
        if content_encoding is not None:
            response.content_encoding = content_encoding

        response.status_int = status_int
        response.app_iter = retrieve_generator

        return response

    def _retrieve_meta(self, req, match_object, user_request_id):
        collection_name = match_object.group("collection_name")
        key = match_object.group("key")
        self._log.debug("request {0}: _retrieve_meta".format(user_request_id))

        try:
            collection_row = \
                self._authenticator.authenticate(collection_name,
                                                 None,
コード例 #12
0
ファイル: server.py プロジェクト: wendy-king/x7_venv
                            conditional_response=True)
        response.headers['Content-Type'] = file.metadata.get(
            'Content-Type', 'application/octet-stream')
        for key, value in file.metadata.iteritems():
            if key.lower().startswith('x-object-meta-') or \
                    key.lower() in self.allowed_headers:
                response.headers[key] = value
        response.etag = file.metadata['ETag']
        response.last_modified = float(file.metadata['X-Timestamp'])
        response.content_length = file_size
        if response.content_length < KEEP_CACHE_SIZE and \
                'X-Auth-Token' not in request.headers and \
                'X-Storage-Token' not in request.headers:
            file.keep_cache = True
        if 'Content-Encoding' in file.metadata:
            response.content_encoding = file.metadata['Content-Encoding']
        response.headers['X-Timestamp'] = file.metadata['X-Timestamp']
        return request.get_response(response)

    def HEAD(self, request):
        """Handle HTTP HEAD requests for the Chase Object Server."""
        try:
            device, partition, account, container, obj = \
                split_path(unquote(request.path), 5, 5, True)
        except ValueError, err:
            resp = HTTPBadRequest(request=request)
            resp.content_type = 'text/plain'
            resp.body = str(err)
            return resp
        if self.mount_check and not check_mount(self.devices, device):
            return Response(status='507 %s is not mounted' % device)
コード例 #13
0
ファイル: application.py プロジェクト: pombredanne/nimbus.io
            )
            content_length = slice_size
        else:
            status_int = httplib.OK

        # 2012-09-06 dougfort Ticket #44 (temporary Connection: close)
        response.headers["Connection"] = "close"
        response.last_modified = last_modified
        response.content_length = content_length

        if content_type is None:
            response.content_type = "application/octet-stream"
        else:
            response.content_type = content_type
        if content_encoding is not None:
            response.content_encoding = content_encoding

        response.status_int = status_int
        response.app_iter = retrieve_generator

        return response

    def _retrieve_meta(self, req, match_object, user_request_id):
        collection_name = match_object.group("collection_name")
        key = match_object.group("key")
        self._log.debug("request {0}: _retrieve_meta".format(user_request_id))

        try:
            collection_row = self._authenticator.authenticate(collection_name, None, req)
        except AccessForbidden, instance:
            self._log.error("request {0}: forbidden {1}".format(user_request_id, instance))
コード例 #14
0
def test__abs_headerlist_location_with_scheme():
    res = Response()
    res.content_encoding = 'gzip'
    res.headerlist = [('Location', 'http:')]
    result = res._abs_headerlist({})
    eq_(result, [('Location', 'http:')])
コード例 #15
0
def test_decode_content_weird():
    res = Response()
    res.content_encoding = 'weird'
    assert_raises(ValueError, res.decode_content)
コード例 #16
0
def test_decode_content_identity():
    res = Response()
    res.content_encoding = 'identity'
    result = res.decode_content()
    eq_(result, None)
コード例 #17
0
def test_encode_content_gzip_already_gzipped():
    res = Response()
    res.content_encoding = 'gzip'
    result = res.encode_content('gzip')
    eq_(result, None)
コード例 #18
0
def invalid_content_encoding_server(environ, start_response):
    response = Response("this is regular text that is lying about it's encoding")
    response.content_encoding = "UTF-8" # UTF-8 is invalid, but found in the wild
    return response(environ, start_response)
コード例 #19
0
ファイル: server.py プロジェクト: andrewgaul/swift
            return HTTPNotModified(request=request)
        response = Response(app_iter=file, request=request, conditional_response=True)
        response.headers["Content-Type"] = file.metadata.get("Content-Type", "application/octet-stream")
        for key, value in file.metadata.iteritems():
            if key.lower().startswith("x-object-meta-") or key.lower() in self.allowed_headers:
                response.headers[key] = value
        response.etag = file.metadata["ETag"]
        response.last_modified = float(file.metadata["X-Timestamp"])
        response.content_length = file_size
        if response.content_length < self.keep_cache_size and (
            self.keep_cache_private
            or ("X-Auth-Token" not in request.headers and "X-Storage-Token" not in request.headers)
        ):
            file.keep_cache = True
        if "Content-Encoding" in file.metadata:
            response.content_encoding = file.metadata["Content-Encoding"]
        response.headers["X-Timestamp"] = file.metadata["X-Timestamp"]
        self.logger.timing_since("GET.timing", start_time)
        return request.get_response(response)

    @public
    def HEAD(self, request):
        """Handle HTTP HEAD requests for the Swift Object Server."""
        start_time = time.time()
        try:
            device, partition, account, container, obj = split_path(unquote(request.path), 5, 5, True)
            validate_device_partition(device, partition)
        except ValueError, err:
            self.logger.increment("HEAD.errors")
            resp = HTTPBadRequest(request=request)
            resp.content_type = "text/plain"