Python cherrypy.url() Examples

The following are 30 code examples of cherrypy.url(). 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: cptools.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def do_check(self):
        """Assert username. Raise redirect, or return True if request handled.
        """
        sess = cherrypy.session
        request = cherrypy.serving.request
        response = cherrypy.serving.response

        username = sess.get(self.session_key)
        if not username:
            sess[self.session_key] = username = self.anonymous()
            self._debug_message('No session[username], trying anonymous')
        if not username:
            url = cherrypy.url(qs=request.query_string)
            self._debug_message(
                'No username, routing to login_screen with from_page %(url)r',
                locals(),
            )
            response.body = self.login_screen(url)
            if 'Content-Length' in response.headers:
                # Delete Content-Length header so finalize() recalcs it.
                del response.headers['Content-Length']
            return True
        self._debug_message('Setting request.login to %(username)r', locals())
        request.login = username
        self.on_check(username) 
Example #3
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 #4
Source File: cptools.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def log_hooks(debug=False):
    """Write request.hooks to the cherrypy error log."""
    request = cherrypy.serving.request

    msg = []
    # Sort by the standard points if possible.
    from cherrypy import _cprequest
    points = _cprequest.hookpoints
    for k in request.hooks.keys():
        if k not in points:
            points.append(k)

    for k in points:
        msg.append('    %s:' % k)
        v = request.hooks.get(k, [])
        v.sort()
        for h in v:
            msg.append('        %r' % h)
    cherrypy.log('\nRequest Hooks for ' + cherrypy.url() +
                 ':\n' + '\n'.join(msg), 'HTTP') 
Example #5
Source File: auth_web.py    From AlexaPiDEPRECATED with MIT License 6 votes vote down vote up
def index(self):
		scope="alexa_all"
		sd = json.dumps({
		    "alexa:all": {
		        "productID": ProductID,
		        "productInstanceAttributes": {
		            "deviceSerialNumber": "001"
		        }
		    }
		})
		url = "https://www.amazon.com/ap/oa"
		callback = cherrypy.url()  + "code" 
		payload = {"client_id" : Client_ID, "scope" : "alexa:all", "scope_data" : sd, "response_type" : "code", "redirect_uri" : callback }
		req = requests.Request('GET', url, params=payload)
		p = req.prepare()
		raise cherrypy.HTTPRedirect(p.url) 
Example #6
Source File: auth_web.py    From AlexaChipDEPRECATED with MIT License 6 votes vote down vote up
def index(self):
		scope="alexa_all"
		sd = json.dumps({
		    "alexa:all": {
		        "productID": ProductID,
		        "productInstanceAttributes": {
		            "deviceSerialNumber": "001"
		        }
		    }
		})
		url = "https://www.amazon.com/ap/oa"
		callback = cherrypy.url()  + "code" 
		payload = {"client_id" : Client_ID, "scope" : "alexa:all", "scope_data" : sd, "response_type" : "code", "redirect_uri" : callback }
		req = requests.Request('GET', url, params=payload)
		p = req.prepare()
		raise cherrypy.HTTPRedirect(p.url) 
Example #7
Source File: auth_web.py    From AlexaPi with MIT License 6 votes vote down vote up
def index(self):
		scope="alexa_all"
		sd = json.dumps({
		    "alexa:all": {
		        "productID": ProductID,
		        "productInstanceAttributes": {
		            "deviceSerialNumber": "001"
		        }
		    }
		})
		url = "https://www.amazon.com/ap/oa"
		callback = cherrypy.url()  + "code" 
		payload = {"client_id" : Client_ID, "scope" : "alexa:all", "scope_data" : sd, "response_type" : "code", "redirect_uri" : callback }
		req = requests.Request('GET', url, params=payload)
		p = req.prepare()
		raise cherrypy.HTTPRedirect(p.url) 
Example #8
Source File: caching.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def put(self, variant, size):
        """Store the current variant in the cache."""
        request = cherrypy.serving.request
        response = cherrypy.serving.response

        uri = cherrypy.url(qs=request.query_string)
        uricache = self.store.get(uri)
        if uricache is None:
            uricache = AntiStampedeCache()
            uricache.selecting_headers = [
                e.value for e in response.headers.elements('Vary')]
            self.store[uri] = uricache

        if len(self.store) < self.maxobjects:
            total_size = self.cursize + size

            # checks if there's space for the object
            if (size < self.maxobj_size and total_size < self.maxsize):
                # add to the expirations list
                expiration_time = response.time + self.delay
                bucket = self.expirations.setdefault(expiration_time, [])
                bucket.append((size, uri, uricache.selecting_headers))

                # add to the cache
                header_values = [request.headers.get(h, '')
                                 for h in uricache.selecting_headers]
                uricache[tuple(sorted(header_values))] = variant
                self.tot_puts += 1
                self.cursize = total_size 
Example #9
Source File: cptools.py    From opsbro with MIT License 6 votes vote down vote up
def log_hooks(debug=False):
    """Write request.hooks to the cherrypy error log."""
    request = cherrypy.serving.request

    msg = []
    # Sort by the standard points if possible.
    from cherrypy import _cprequest
    points = _cprequest.hookpoints
    for k in request.hooks.keys():
        if k not in points:
            points.append(k)

    for k in points:
        msg.append("    %s:" % k)
        v = request.hooks.get(k, [])
        v.sort()
        for h in v:
            msg.append("        %r" % h)
    cherrypy.log('\nRequest Hooks for ' + cherrypy.url() +
                 ':\n' + '\n'.join(msg), "HTTP") 
Example #10
Source File: caching.py    From opsbro with MIT License 6 votes vote down vote up
def get(self):
        """Return the current variant if in the cache, else None."""
        request = cherrypy.serving.request
        self.tot_gets += 1

        uri = cherrypy.url(qs=request.query_string)
        uricache = self.store.get(uri)
        if uricache is None:
            return None

        header_values = [request.headers.get(h, '')
                         for h in uricache.selecting_headers]
        variant = uricache.wait(key=tuple(sorted(header_values)),
                                timeout=self.antistampede_timeout,
                                debug=self.debug)
        if variant is not None:
            self.tot_hist += 1
        return variant 
Example #11
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 #12
Source File: cptools.py    From bazarr with GNU General Public License v3.0 6 votes vote down vote up
def do_check(self):
        """Assert username. Raise redirect, or return True if request handled.
        """
        sess = cherrypy.session
        request = cherrypy.serving.request
        response = cherrypy.serving.response

        username = sess.get(self.session_key)
        if not username:
            sess[self.session_key] = username = self.anonymous()
            self._debug_message('No session[username], trying anonymous')
        if not username:
            url = cherrypy.url(qs=request.query_string)
            self._debug_message(
                'No username, routing to login_screen with from_page %(url)r',
                locals(),
            )
            response.body = self.login_screen(url)
            if 'Content-Length' in response.headers:
                # Delete Content-Length header so finalize() recalcs it.
                del response.headers['Content-Length']
            return True
        self._debug_message('Setting request.login to %(username)r', locals())
        request.login = username
        self.on_check(username) 
Example #13
Source File: cptools.py    From bazarr with GNU General Public License v3.0 6 votes vote down vote up
def log_hooks(debug=False):
    """Write request.hooks to the cherrypy error log."""
    request = cherrypy.serving.request

    msg = []
    # Sort by the standard points if possible.
    from cherrypy import _cprequest
    points = _cprequest.hookpoints
    for k in request.hooks.keys():
        if k not in points:
            points.append(k)

    for k in points:
        msg.append('    %s:' % k)
        v = request.hooks.get(k, [])
        v.sort()
        for h in v:
            msg.append('        %r' % h)
    cherrypy.log('\nRequest Hooks for ' + cherrypy.url() +
                 ':\n' + '\n'.join(msg), 'HTTP') 
Example #14
Source File: caching.py    From bazarr with GNU General Public License v3.0 6 votes vote down vote up
def get(self):
        """Return the current variant if in the cache, else None."""
        request = cherrypy.serving.request
        self.tot_gets += 1

        uri = cherrypy.url(qs=request.query_string)
        uricache = self.store.get(uri)
        if uricache is None:
            return None

        header_values = [request.headers.get(h, '')
                         for h in uricache.selecting_headers]
        variant = uricache.wait(key=tuple(sorted(header_values)),
                                timeout=self.antistampede_timeout,
                                debug=self.debug)
        if variant is not None:
            self.tot_hist += 1
        return variant 
Example #15
Source File: test_objectmapping.py    From bazarr with GNU General Public License v3.0 6 votes vote down vote up
def test_redir_using_url(self):
        for url in script_names:
            prefix = self.script_name = url

            # Test the absolute path to the parent (leading slash)
            self.getPage('/redirect_via_url?path=./')
            self.assertStatus(('302 Found', '303 See Other'))
            self.assertHeader('Location', '%s/' % self.base())

            # Test the relative path to the parent (no leading slash)
            self.getPage('/redirect_via_url?path=./')
            self.assertStatus(('302 Found', '303 See Other'))
            self.assertHeader('Location', '%s/' % self.base())

            # Test the absolute path to the parent (leading slash)
            self.getPage('/redirect_via_url/?path=./')
            self.assertStatus(('302 Found', '303 See Other'))
            self.assertHeader('Location', '%s/' % self.base())

            # Test the relative path to the parent (no leading slash)
            self.getPage('/redirect_via_url/?path=./')
            self.assertStatus(('302 Found', '303 See Other'))
            self.assertHeader('Location', '%s/' % self.base()) 
Example #16
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 #17
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 #18
Source File: cptools.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def do_check(self):
        """Assert username. Raise redirect, or return True if request handled.
        """
        sess = cherrypy.session
        request = cherrypy.serving.request
        response = cherrypy.serving.response

        username = sess.get(self.session_key)
        if not username:
            sess[self.session_key] = username = self.anonymous()
            self._debug_message('No session[username], trying anonymous')
        if not username:
            url = cherrypy.url(qs=request.query_string)
            self._debug_message(
                'No username, routing to login_screen with from_page %(url)r',
                locals(),
            )
            response.body = self.login_screen(url)
            if 'Content-Length' in response.headers:
                # Delete Content-Length header so finalize() recalcs it.
                del response.headers['Content-Length']
            return True
        self._debug_message('Setting request.login to %(username)r', locals())
        request.login = username
        self.on_check(username) 
Example #19
Source File: cptools.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def log_hooks(debug=False):
    """Write request.hooks to the cherrypy error log."""
    request = cherrypy.serving.request

    msg = []
    # Sort by the standard points if possible.
    from cherrypy import _cprequest
    points = _cprequest.hookpoints
    for k in request.hooks.keys():
        if k not in points:
            points.append(k)

    for k in points:
        msg.append('    %s:' % k)
        v = request.hooks.get(k, [])
        v.sort()
        for h in v:
            msg.append('        %r' % h)
    cherrypy.log('\nRequest Hooks for ' + cherrypy.url() +
                 ':\n' + '\n'.join(msg), 'HTTP') 
Example #20
Source File: caching.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def get(self):
        """Return the current variant if in the cache, else None."""
        request = cherrypy.serving.request
        self.tot_gets += 1

        uri = cherrypy.url(qs=request.query_string)
        uricache = self.store.get(uri)
        if uricache is None:
            return None

        header_values = [request.headers.get(h, '')
                         for h in uricache.selecting_headers]
        variant = uricache.wait(key=tuple(sorted(header_values)),
                                timeout=self.antistampede_timeout,
                                debug=self.debug)
        if variant is not None:
            self.tot_hist += 1
        return variant 
Example #21
Source File: test_objectmapping.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def test_redir_using_url(self):
        for url in script_names:
            self.script_name = url

            # Test the absolute path to the parent (leading slash)
            self.getPage('/redirect_via_url?path=./')
            self.assertStatus(('302 Found', '303 See Other'))
            self.assertHeader('Location', '%s/' % self.base())

            # Test the relative path to the parent (no leading slash)
            self.getPage('/redirect_via_url?path=./')
            self.assertStatus(('302 Found', '303 See Other'))
            self.assertHeader('Location', '%s/' % self.base())

            # Test the absolute path to the parent (leading slash)
            self.getPage('/redirect_via_url/?path=./')
            self.assertStatus(('302 Found', '303 See Other'))
            self.assertHeader('Location', '%s/' % self.base())

            # Test the relative path to the parent (no leading slash)
            self.getPage('/redirect_via_url/?path=./')
            self.assertStatus(('302 Found', '303 See Other'))
            self.assertHeader('Location', '%s/' % self.base()) 
Example #22
Source File: authorization.py    From python-alexa-voice-service with MIT License 6 votes vote down vote up
def index(self):
        sd = json.dumps({
            "alexa:all": {
                "productID": self.config['ProductID'],
                "productInstanceAttributes": {
                    "deviceSerialNumber": "123456"
                }
            }
        })
        callback = cherrypy.url() + "code"
        payload = {
            "client_id": self.config['Client_ID'],
            "scope": "alexa:all",
            "scope_data": sd,
            "response_type": "code",
            "redirect_uri": callback
        }
        req = requests.Request('GET', "https://www.amazon.com/ap/oa", params=payload)
        p = req.prepare()
        raise cherrypy.HTTPRedirect(p.url) 
Example #23
Source File: authorization.py    From python-alexa-voice-service with MIT License 6 votes vote down vote up
def code(self, var=None, **params):
        code = urllib.parse.quote(cherrypy.request.params['code'])
        callback = cherrypy.url()
        payload = {
            "client_id": self.config['Client_ID'],
            "client_secret": self.config['Client_Secret'],
            "code": code,
            "grant_type": "authorization_code",
            "redirect_uri": callback
        }
        url = "https://api.amazon.com/auth/o2/token"
        r = requests.post(url, data=payload)
        resp = r.json()

        self.config['refresh_token'] = resp['refresh_token']
        helper.write_dict('config.dict',self.config)

        threading.Timer(1, lambda: cherrypy.engine.exit()).start()

        return "Authentication successful! Please return to the program." 
Example #24
Source File: _cperror.py    From moviegrabber 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 #25
Source File: cptools.py    From moviegrabber with GNU General Public License v3.0 6 votes vote down vote up
def do_check(self):
        """Assert username. May raise redirect, or return True if request handled."""
        sess = cherrypy.session
        request = cherrypy.serving.request
        response = cherrypy.serving.response
        
        username = sess.get(self.session_key)
        if not username:
            sess[self.session_key] = username = self.anonymous()
            if self.debug:
                cherrypy.log('No session[username], trying anonymous', 'TOOLS.SESSAUTH')
        if not username:
            url = cherrypy.url(qs=request.query_string)
            if self.debug:
                cherrypy.log('No username, routing to login_screen with '
                             'from_page %r' % url, 'TOOLS.SESSAUTH')
            response.body = self.login_screen(url)
            if "Content-Length" in response.headers:
                # Delete Content-Length header so finalize() recalcs it.
                del response.headers["Content-Length"]
            return True
        if self.debug:
            cherrypy.log('Setting request.login to %r' % username, 'TOOLS.SESSAUTH')
        request.login = username
        self.on_check(username) 
Example #26
Source File: cptools.py    From moviegrabber with GNU General Public License v3.0 6 votes vote down vote up
def log_hooks(debug=False):
    """Write request.hooks to the cherrypy error log."""
    request = cherrypy.serving.request
    
    msg = []
    # Sort by the standard points if possible.
    from cherrypy import _cprequest
    points = _cprequest.hookpoints
    for k in request.hooks.keys():
        if k not in points:
            points.append(k)
    
    for k in points:
        msg.append("    %s:" % k)
        v = request.hooks.get(k, [])
        v.sort()
        for h in v:
            msg.append("        %r" % h)
    cherrypy.log('\nRequest Hooks for ' + cherrypy.url() +
                 ':\n' + '\n'.join(msg), "HTTP") 
Example #27
Source File: caching.py    From moviegrabber with GNU General Public License v3.0 6 votes vote down vote up
def get(self):
        """Return the current variant if in the cache, else None."""
        request = cherrypy.serving.request
        self.tot_gets += 1
        
        uri = cherrypy.url(qs=request.query_string)
        uricache = self.store.get(uri)
        if uricache is None:
            return None
        
        header_values = [request.headers.get(h, '')
                         for h in uricache.selecting_headers]
        variant = uricache.wait(key=tuple(sorted(header_values)),
                                timeout=self.antistampede_timeout,
                                debug=self.debug)
        if variant is not None:
            self.tot_hist += 1
        return variant 
Example #28
Source File: test_objectmapping.py    From moviegrabber with GNU General Public License v3.0 6 votes vote down vote up
def test_redir_using_url(self):
        for url in script_names:
            prefix = self.script_name = url
            
            # Test the absolute path to the parent (leading slash)
            self.getPage('/redirect_via_url?path=./')
            self.assertStatus(('302 Found', '303 See Other'))
            self.assertHeader('Location', '%s/' % self.base())
            
            # Test the relative path to the parent (no leading slash)
            self.getPage('/redirect_via_url?path=./')
            self.assertStatus(('302 Found', '303 See Other'))
            self.assertHeader('Location', '%s/' % self.base())
            
            # Test the absolute path to the parent (leading slash)
            self.getPage('/redirect_via_url/?path=./')
            self.assertStatus(('302 Found', '303 See Other'))
            self.assertHeader('Location', '%s/' % self.base())
            
            # Test the relative path to the parent (no leading slash)
            self.getPage('/redirect_via_url/?path=./')
            self.assertStatus(('302 Found', '303 See Other'))
            self.assertHeader('Location', '%s/' % self.base()) 
Example #29
Source File: auth_web.py    From AlexaPi with MIT License 6 votes vote down vote up
def index(self):
		sd = json.dumps({
			"alexa:all": {
				"productID": config['alexa']['Device_Type_ID'],
				"productInstanceAttributes": {
					"deviceSerialNumber": hashlib.sha256(str(uuid.getnode()).encode()).hexdigest()
				}
			}
		})

		url = "https://www.amazon.com/ap/oa"
		callback = cherrypy.url() + "code"
		payload = {
			"client_id": config['alexa']['Client_ID'],
			"scope": "alexa:all",
			"scope_data": sd,
			"response_type": "code",
			"redirect_uri": callback
		}
		req = requests.Request('GET', url, params=payload)
		prepared_req = req.prepare()
		raise cherrypy.HTTPRedirect(prepared_req.url) 
Example #30
Source File: auth_web.py    From AlexaPi with MIT License 6 votes vote down vote up
def code(self, var=None, **params):		# pylint: disable=unused-argument
		code = quote(cherrypy.request.params['code'])
		callback = cherrypy.url()
		payload = {
			"client_id": config['alexa']['Client_ID'],
			"client_secret": config['alexa']['Client_Secret'],
			"code": code,
			"grant_type": "authorization_code",
			"redirect_uri": callback
		}
		url = "https://api.amazon.com/auth/o2/token"
		response = requests.post(url, data=payload)
		resp = response.json()

		alexapi.config.set_variable(['alexa', 'refresh_token'], resp['refresh_token'])

		return "<h2>Success!</h2>" \
				"<p>The refresh token has been added to your config file.</p>" \
				"<p>Now:</p>" \
				"<ul>" \
				"<li>close your this browser window,</li>" \
				"<li>exit the setup script as indicated,</li>" \
				"<li>and follow the Post-installation steps.</li>" \
				"</ul>"