Python cherrypy.request() Examples

The following are 30 code examples of cherrypy.request(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cherrypy , or try the search function .
Example #1
Source File: _cperror.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def __init__(self, path, query_string=''):
        self.request = cherrypy.serving.request

        self.query_string = query_string
        if '?' in path:
            # Separate any params included in the path
            path, self.query_string = path.split('?', 1)

        # Note that urljoin will "do the right thing" whether url is:
        #  1. a URL relative to root (e.g. "/dummy")
        #  2. a URL relative to the current path
        # Note that any query string will be discarded.
        path = urllib.parse.urljoin(self.request.path_info, path)

        # Set a 'path' member attribute so that code which traps this
        # error can have access to it.
        self.path = path

        CherryPyException.__init__(self, path, self.query_string) 
Example #2
Source File: _cperror.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, urls, status=None, encoding=None):
        self.urls = abs_urls = [
            # Note that urljoin will "do the right thing" whether url is:
            #  1. a complete URL with host (e.g. "http://www.example.com/test")
            #  2. a URL relative to root (e.g. "/dummy")
            #  3. a URL relative to the current path
            # Note that any query string in cherrypy.request is discarded.
            urllib.parse.urljoin(
                cherrypy.url(),
                tonative(url, encoding or self.encoding),
            )
            for url in always_iterable(urls)
        ]

        status = (
            int(status)
            if status is not None
            else self.default_status
        )
        if not 300 <= status <= 399:
            raise ValueError('status must be between 300 and 399.')

        CherryPyException.__init__(self, abs_urls, status) 
Example #3
Source File: _cplogging.py    From opsbro with MIT License 6 votes vote down vote up
def emit(self, record):
        """Emit a record."""
        try:
            stream = cherrypy.serving.request.wsgi_environ.get('wsgi.errors')
        except (AttributeError, KeyError):
            pass
        else:
            try:
                msg = self.format(record)
                fs = "%s\n"
                import types
                # if no unicode support...
                if not hasattr(types, "UnicodeType"):
                    stream.write(fs % msg)
                else:
                    try:
                        stream.write(fs % msg)
                    except UnicodeError:
                        stream.write(fs % msg.encode("UTF-8"))
                self.flush()
            except:
                self.handleError(record) 
Example #4
Source File: alarmdata.py    From SecPi with GNU General Public License v3.0 6 votes vote down vote up
def extract(self):
		if(hasattr(cherrypy.request, 'json')):
			if('dir' in cherrypy.request.json and cherrypy.request.json['dir']!='' and 'name' in cherrypy.request.json and cherrypy.request.json['name']!=''):
				dir = cherrypy.request.json['dir']
				name = cherrypy.request.json['name']
				
				fdir = path.join(self.datapath, dir)
				fp = path.join(fdir, name)
				if(path.exists(fp)):
					with zipfile.ZipFile(fp, "r") as z:
						z.extractall(fdir)
						return {'status': 'success', 'message': "File %s/%s extracted!"%(dir, name)}
				else:
					return {'status': 'error', 'message': "File doesn't exist!"}
			else:
				return {'status': 'error', 'message': "Invalid filename!"}
		else:
			return {'status': 'error', 'message': "No filename given!"} 
Example #5
Source File: main.py    From SecPi with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
		cherrypy.log("Initializing Webserver")
		
		cherrypy.config.update({'request.error_response': self.handle_error})
		cherrypy.config.update({'error_page.404': self.error_404})
		cherrypy.config.update({'error_page.401': self.error_401})
		
		self.sensors = SensorsPage()
		self.zones = ZonesPage()
		self.setups = SetupsPage()
		self.alarms = AlarmsPage()
		self.workers = WorkersPage()
		self.actions = ActionsPage()
		self.notifiers = NotifiersPage()
		self.sensorparams = SensorParamsPage()
		self.actionparams = ActionParamsPage()
		self.notifierparams = NotifierParamsPage()
		self.logs = LogEntriesPage()
		self.setupszones = SetupsZonesPage()
		self.workersactions = WorkersActionsPage()
		
		self.alarmdata = AlarmDataPage()
		
		self.connect()
		cherrypy.log("Finished initialization") 
Example #6
Source File: _cpchecker.py    From opsbro with MIT License 6 votes vote down vote up
def _populate_known_types(self):
        b = [x for x in vars(builtins).values()
             if type(x) is type(str)]

        def traverse(obj, namespace):
            for name in dir(obj):
                # Hack for 3.2's warning about body_params
                if name == 'body_params':
                    continue
                vtype = type(getattr(obj, name, None))
                if vtype in b:
                    self.known_config_types[namespace + "." + name] = vtype

        traverse(cherrypy.request, "request")
        traverse(cherrypy.response, "response")
        traverse(cherrypy.server, "server")
        traverse(cherrypy.engine, "engine")
        traverse(cherrypy.log, "log") 
Example #7
Source File: base_webpage.py    From SecPi with GNU General Public License v3.0 6 votes vote down vote up
def update(self):
		if(hasattr(cherrypy.request, 'json')):
			data = cherrypy.request.json
			
			id = data['id']
			
			# check for valid id
			if(id and id > 0):
				
				if(data and len(data)>0):
					cherrypy.log("update something %s"%data)
					obj = self.db.query(self.baseclass).get(id)
					
					for k, v in data.iteritems():
						if(not k == "id"): # and v is not None --> can be null!?
							setattr(obj, k, utils.str_to_value(v))
					
					self.db.commit()
					
					return {'status': 'success', 'message': "Updated object with id %i"%obj.id}
					
			else:
				return {'status':'error', 'message': "Invalid ID!" }
		
		return {'status': 'error', 'message': 'No data recieved!'} 
Example #8
Source File: test_request_obj.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_CONNECT_method(self):
        self.persistent = True
        try:
            conn = self.HTTP_CONN
            conn.request('CONNECT', 'created.example.com:3128')
            response = conn.response_class(conn.sock, method='CONNECT')
            response.begin()
            self.assertEqual(response.status, 204)
        finally:
            self.persistent = False

        self.persistent = True
        try:
            conn = self.HTTP_CONN
            conn.request('CONNECT', 'body.example.com:3128')
            response = conn.response_class(conn.sock, method='CONNECT')
            response.begin()
            self.assertEqual(response.status, 200)
            self.body = response.read()
            self.assertBody(b'CONNECTed to /body.example.com:3128')
        finally:
            self.persistent = False 
Example #9
Source File: _cpchecker.py    From bazarr with GNU General Public License v3.0 6 votes vote down vote up
def _populate_known_types(self):
        b = [x for x in vars(builtins).values()
             if type(x) is type(str)]

        def traverse(obj, namespace):
            for name in dir(obj):
                # Hack for 3.2's warning about body_params
                if name == 'body_params':
                    continue
                vtype = type(getattr(obj, name, None))
                if vtype in b:
                    self.known_config_types[namespace + '.' + name] = vtype

        traverse(cherrypy.request, 'request')
        traverse(cherrypy.response, 'response')
        traverse(cherrypy.server, 'server')
        traverse(cherrypy.engine, 'engine')
        traverse(cherrypy.log, 'log') 
Example #10
Source File: _cperror.py    From bazarr with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, path, query_string=''):
        import cherrypy
        self.request = cherrypy.serving.request

        self.query_string = query_string
        if '?' in path:
            # Separate any params included in the path
            path, self.query_string = path.split('?', 1)

        # Note that urljoin will "do the right thing" whether url is:
        #  1. a URL relative to root (e.g. "/dummy")
        #  2. a URL relative to the current path
        # Note that any query string will be discarded.
        path = _urljoin(self.request.path_info, path)

        # Set a 'path' member attribute so that code which traps this
        # error can have access to it.
        self.path = path

        CherryPyException.__init__(self, path, self.query_string) 
Example #11
Source File: base_webpage.py    From SecPi with GNU General Public License v3.0 6 votes vote down vote up
def list(self):
		if(hasattr(cherrypy.request, 'json')):
			qry = self.db.query(self.baseclass)
			
			if('filter' in cherrypy.request.json and cherrypy.request.json['filter']!=''):
				qry = qry.filter(text(cherrypy.request.json['filter']))
			
			if('sort' in cherrypy.request.json and cherrypy.request.json['sort']!=''):
				qry = qry.order_by(text(cherrypy.request.json['sort']))
			
			objects = qry.all()
			
		else:	
			objects = self.db.query(self.baseclass).all()
		
		return {'status': 'success', 'data': self.objectsToList(objects)} 
Example #12
Source File: _cperror.py    From opsbro with MIT License 6 votes vote down vote up
def __init__(self, path, query_string=""):
        import cherrypy
        self.request = cherrypy.serving.request

        self.query_string = query_string
        if "?" in path:
            # Separate any params included in the path
            path, self.query_string = path.split("?", 1)

        # Note that urljoin will "do the right thing" whether url is:
        #  1. a URL relative to root (e.g. "/dummy")
        #  2. a URL relative to the current path
        # Note that any query string will be discarded.
        path = _urljoin(self.request.path_info, path)

        # Set a 'path' member attribute so that code which traps this
        # error can have access to it.
        self.path = path

        CherryPyException.__init__(self, path, self.query_string) 
Example #13
Source File: _cpchecker.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _populate_known_types(self):
        b = [x for x in vars(builtins).values()
             if type(x) is type(str)]

        def traverse(obj, namespace):
            for name in dir(obj):
                # Hack for 3.2's warning about body_params
                if name == 'body_params':
                    continue
                vtype = type(getattr(obj, name, None))
                if vtype in b:
                    self.known_config_types[namespace + '.' + name] = vtype

        traverse(cherrypy.request, 'request')
        traverse(cherrypy.response, 'response')
        traverse(cherrypy.server, 'server')
        traverse(cherrypy.engine, 'engine')
        traverse(cherrypy.log, 'log') 
Example #14
Source File: _cptree.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def script_name(self, path=None):
        """Return the script_name of the app at the given path, or None.

        If path is None, cherrypy.request is used.
        """
        if path is None:
            try:
                request = cherrypy.serving.request
                path = httputil.urljoin(request.script_name,
                                        request.path_info)
            except AttributeError:
                return None

        while True:
            if path in self.apps:
                return path

            if path == '':
                return None

            # Move one node up the tree and try again.
            path = path[:path.rfind('/')] 
Example #15
Source File: _cplogging.py    From bazarr with GNU General Public License v3.0 6 votes vote down vote up
def emit(self, record):
        """Emit a record."""
        try:
            stream = cherrypy.serving.request.wsgi_environ.get('wsgi.errors')
        except (AttributeError, KeyError):
            pass
        else:
            try:
                msg = self.format(record)
                fs = '%s\n'
                import types
                # if no unicode support...
                if not hasattr(types, 'UnicodeType'):
                    stream.write(fs % msg)
                else:
                    try:
                        stream.write(fs % msg)
                    except UnicodeError:
                        stream.write(fs % msg.encode('UTF-8'))
                self.flush()
            except:
                self.handleError(record) 
Example #16
Source File: _cptree.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def script_name(self):  # noqa: D401; irrelevant for properties
        """The URI "mount point" for this app.

        A mount point is that portion of the URI which is constant for all URIs
        that are serviced by this application; it does not include scheme,
        host, or proxy ("virtual host") portions of the URI.

        For example, if script_name is "/my/cool/app", then the URL
        "http://www.example.com/my/cool/app/page1" might be handled by a
        "page1" method on the root object.

        The value of script_name MUST NOT end in a slash. If the script_name
        refers to the root of the URI, it MUST be an empty string (not "/").

        If script_name is explicitly set to None, then the script_name will be
        provided for each call from request.wsgi_environ['SCRIPT_NAME'].
        """
        if self._script_name is not None:
            return self._script_name

        # A `_script_name` with a value of None signals that the script name
        # should be pulled from WSGI environ.
        return cherrypy.serving.request.wsgi_environ['SCRIPT_NAME'].rstrip('/') 
Example #17
Source File: _cperror.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, path, query_string=''):
        self.request = cherrypy.serving.request

        self.query_string = query_string
        if '?' in path:
            # Separate any params included in the path
            path, self.query_string = path.split('?', 1)

        # Note that urljoin will "do the right thing" whether url is:
        #  1. a URL relative to root (e.g. "/dummy")
        #  2. a URL relative to the current path
        # Note that any query string will be discarded.
        path = urllib.parse.urljoin(self.request.path_info, path)

        # Set a 'path' member attribute so that code which traps this
        # error can have access to it.
        self.path = path

        CherryPyException.__init__(self, path, self.query_string) 
Example #18
Source File: _cperror.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, urls, status=None, encoding=None):
        self.urls = abs_urls = [
            # Note that urljoin will "do the right thing" whether url is:
            #  1. a complete URL with host (e.g. "http://www.example.com/test")
            #  2. a URL relative to root (e.g. "/dummy")
            #  3. a URL relative to the current path
            # Note that any query string in cherrypy.request is discarded.
            urllib.parse.urljoin(
                cherrypy.url(),
                tonative(url, encoding or self.encoding),
            )
            for url in always_iterable(urls)
        ]

        status = (
            int(status)
            if status is not None
            else self.default_status
        )
        if not 300 <= status <= 399:
            raise ValueError('status must be between 300 and 399.')

        CherryPyException.__init__(self, abs_urls, status) 
Example #19
Source File: _cperror.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def set_response(self):
        """Modify cherrypy.response status, headers, and body to represent
        self.

        CherryPy uses this internally, but you can also use it to create an
        HTTPError object and set its output without *raising* the exception.
        """
        response = cherrypy.serving.response

        clean_headers(self.code)

        # In all cases, finalize will be called after this method,
        # so don't bother cleaning up response values here.
        response.status = self.status
        tb = None
        if cherrypy.serving.request.show_tracebacks:
            tb = format_exc()

        response.headers.pop('Content-Length', None)

        content = self.get_error_page(self.status, traceback=tb,
                                      message=self._message)
        response.body = content

        _be_ie_unfriendly(self.code) 
Example #20
Source File: test_request_obj.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def test_repeated_headers(self):
        # Test that two request headers are collapsed into one.
        # See https://github.com/cherrypy/cherrypy/issues/542.
        self.getPage('/headers/Accept-Charset',
                     headers=[('Accept-Charset', 'iso-8859-5'),
                              ('Accept-Charset', 'unicode-1-1;q=0.8')])
        self.assertBody('iso-8859-5, unicode-1-1;q=0.8')

        # Tests that each header only appears once, regardless of case.
        self.getPage('/headers/doubledheaders')
        self.assertBody('double header test')
        hnames = [name.title() for name, val in self.headers]
        for key in ['Content-Length', 'Content-Type', 'Date',
                    'Expires', 'Location', 'Server']:
            self.assertEqual(hnames.count(key), 1, self.headers) 
Example #21
Source File: cherrypy.py    From scout_apm_python with MIT License 5 votes vote down vote up
def before_request(self):
        if self._do_nothing:
            return
        request = cherrypy.request
        tracked_request = TrackedRequest.instance()
        tracked_request.is_real_request = True
        request._scout_tracked_request = tracked_request

        # Can't name operation until after request, when routing has been done
        request._scout_controller_span = tracked_request.start_span(
            "Controller/Unknown"
        ) 
Example #22
Source File: _cperror.py    From opsbro with MIT License 5 votes vote down vote up
def __call__(self):
        """Use this exception as a request.handler (raise self)."""
        raise self 
Example #23
Source File: test_request_obj.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def test_encoded_headers(self):
        # First, make sure the innards work like expected.
        self.assertEqual(
            httputil.decode_TEXT(ntou('=?utf-8?q?f=C3=BCr?=')), ntou('f\xfcr'))

        if cherrypy.server.protocol_version == 'HTTP/1.1':
            # Test RFC-2047-encoded request and response header values
            u = ntou('\u212bngstr\xf6m', 'escape')
            c = ntou('=E2=84=ABngstr=C3=B6m')
            self.getPage('/headers/ifmatch',
                         [('If-Match', ntou('=?utf-8?q?%s?=') % c)])
            # The body should be utf-8 encoded.
            self.assertBody(ntob('\xe2\x84\xabngstr\xc3\xb6m'))
            # But the Etag header should be RFC-2047 encoded (binary)
            self.assertHeader('ETag', ntou('=?utf-8?b?4oSrbmdzdHLDtm0=?='))

            # Test a *LONG* RFC-2047-encoded request and response header value
            self.getPage('/headers/ifmatch',
                         [('If-Match', ntou('=?utf-8?q?%s?=') % (c * 10))])
            self.assertBody(ntob('\xe2\x84\xabngstr\xc3\xb6m') * 10)
            # Note: this is different output for Python3, but it decodes fine.
            etag = self.assertHeader(
                'ETag',
                '=?utf-8?b?4oSrbmdzdHLDtm3ihKtuZ3N0csO2beKEq25nc3Ryw7Zt'
                '4oSrbmdzdHLDtm3ihKtuZ3N0csO2beKEq25nc3Ryw7Zt'
                '4oSrbmdzdHLDtm3ihKtuZ3N0csO2beKEq25nc3Ryw7Zt'
                '4oSrbmdzdHLDtm0=?=')
            self.assertEqual(httputil.decode_TEXT(etag), u * 10) 
Example #24
Source File: _cplogging.py    From opsbro with MIT License 5 votes vote down vote up
def flush(self):
        """Flushes the stream."""
        try:
            stream = cherrypy.serving.request.wsgi_environ.get('wsgi.errors')
        except (AttributeError, KeyError):
            pass
        else:
            stream.flush() 
Example #25
Source File: _cptree.py    From opsbro with MIT License 5 votes vote down vote up
def release_serving(self):
        """Release the current serving (request and response)."""
        req = cherrypy.serving.request

        cherrypy.engine.publish('after_request')

        try:
            req.close()
        except:
            cherrypy.log(traceback=True, severity=40)

        cherrypy.serving.clear() 
Example #26
Source File: _cptree.py    From opsbro with MIT License 5 votes vote down vote up
def _get_script_name(self):
        if self._script_name is not None:
            return self._script_name

        # A `_script_name` with a value of None signals that the script name
        # should be pulled from WSGI environ.
        return cherrypy.serving.request.wsgi_environ['SCRIPT_NAME'].rstrip("/") 
Example #27
Source File: _cperror.py    From opsbro with MIT License 5 votes vote down vote up
def bare_error(extrabody=None):
    """Produce status, headers, body for a critical error.

    Returns a triple without calling any other questionable functions,
    so it should be as error-free as possible. Call it from an HTTP server
    if you get errors outside of the request.

    If extrabody is None, a friendly but rather unhelpful error message
    is set in the body. If extrabody is a string, it will be appended
    as-is to the body.
    """

    # The whole point of this function is to be a last line-of-defense
    # in handling errors. That is, it must not raise any errors itself;
    # it cannot be allowed to fail. Therefore, don't add to it!
    # In particular, don't call any other CP functions.

    body = ntob("Unrecoverable error in the server.")
    if extrabody is not None:
        if not isinstance(extrabody, bytestr):
            extrabody = extrabody.encode('utf-8')
        body += ntob("\n") + extrabody

    return (ntob("500 Internal Server Error"),
            [(ntob('Content-Type'), ntob('text/plain')),
             (ntob('Content-Length'), ntob(str(len(body)), 'ISO-8859-1'))],
            [body]) 
Example #28
Source File: _cperror.py    From opsbro with MIT License 5 votes vote down vote up
def __init__(self, path=None):
        if path is None:
            import cherrypy
            request = cherrypy.serving.request
            path = request.script_name + request.path_info
        self.args = (path,)
        HTTPError.__init__(self, 404, "The path '%s' was not found." % path) 
Example #29
Source File: _cperror.py    From opsbro with MIT License 5 votes vote down vote up
def set_response(self):
        """Modify cherrypy.response status, headers, and body to represent
        self.

        CherryPy uses this internally, but you can also use it to create an
        HTTPError object and set its output without *raising* the exception.
        """
        import cherrypy

        response = cherrypy.serving.response

        clean_headers(self.code)

        # In all cases, finalize will be called after this method,
        # so don't bother cleaning up response values here.
        response.status = self.status
        tb = None
        if cherrypy.serving.request.show_tracebacks:
            tb = format_exc()

        response.headers.pop('Content-Length', None)

        content = self.get_error_page(self.status, traceback=tb,
                                      message=self._message)
        response.body = content

        _be_ie_unfriendly(self.code) 
Example #30
Source File: _cperror.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def __call__(self):
        """Use this exception as a request.handler (raise self)."""
        raise self