我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用cherrypy.url()。
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)
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)
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>"
def index(self): scope="alexa_all" sd = json.dumps({ "alexa:all": { "productID": ProductID, "productInstanceAttributes": { "deviceSerialNumber": "001" } } }) url = "https://www.amazon.com/ap/oa" # Establish AMZN callback URL 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)
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)
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
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)
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')
def trailing_slash(missing=True, extra=False, status=None, debug=False): """Redirect if path_info has (missing|extra) trailing slash.""" request = cherrypy.serving.request pi = request.path_info if debug: cherrypy.log('is_index: %r, missing: %r, extra: %r, path_info: %r' % (request.is_index, missing, extra, pi), 'TOOLS.TRAILING_SLASH') if request.is_index is True: if missing: if not pi.endswith('/'): new_url = cherrypy.url(pi + '/', request.query_string) raise cherrypy.HTTPRedirect(new_url, status=status or 301) elif request.is_index is False: if extra: # If pi == '/', don't redirect to ''! if pi.endswith('/') and pi != '/': new_url = cherrypy.url(pi[:-1], request.query_string) raise cherrypy.HTTPRedirect(new_url, status=status or 301)
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)
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() + "authresponse" 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)
def index(self): sd = json.dumps({ "alexa:all": { "productID": PRODUCT_ID, "productInstanceAttributes": { "deviceSerialNumber": uuid.getnode() } } }) url = "https://www.amazon.com/ap/oa" callback = cherrypy.url() + "authresponse" 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)
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)
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")
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())
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)
def code(self, var=None, **params): code = urllib.quote(cherrypy.request.params['code']) callback = cherrypy.url() payload = {"client_id" : Client_ID, "client_secret" : 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() line = 'refresh_token = "{}"'.format(resp['refresh_token']) with open("creds.py", 'a') as f: f.write(line) return "Success!, refresh token has been added to your creds file, you may now reboot the Pi <br>{}".format(resp['refresh_token'])
def index(self): """ The main page """ product_id = Config.get_config(Config.FIELD_PRODUCT_ID) client_id = Config.get_config(Config.FIELD_CLIENT_ID) scope_data = json.dumps( {"alexa:all": { "productID": product_id, "productInstanceAttributes": { "deviceSerialNumber": "001"} }} ) callback = cherrypy.url() + "code" payload = { "client_id": client_id, "scope": "alexa:all", "scope_data": scope_data, "response_type": "code", "redirect_uri": callback } req = requests.Request( 'GET', AlexaService.AMAZON_BASE_URL, params=payload ) raise cherrypy.HTTPRedirect(req.prepare().url)
def code(self, var=None, **params): """ The code page """ client_id = Config.get_config(Config.FIELD_CLIENT_ID) client_secret = Config.get_config(Config.FIELD_CLIENT_SECRET) code = urllib.quote(cherrypy.request.params['code']) callback = cherrypy.url() payload = { "client_id" : client_id, "client_secret" : client_secret, "code" : code, "grant_type" : "authorization_code", "redirect_uri" : callback } result = requests.post(AlexaService.AMAZON_TOKEN_URL, data=payload) result = result.json() # Save the refresh token and reset access token Config.save_config( Config.FIELD_REFRESH_TOKEN, format(result['refresh_token']) ) Config.save_config(Config.FIELD_ACCESS_TOKEN, "") html = "<b>Success!</b><br/>" html += "Refresh token has been added to your credentials file.<br/>" html += "You may now reboot the Pi or restart the service.<br/>" html += "Your token: %s" % result['refresh_token'] return html
def code(self, var=None, **params): code = quote(cherrypy.request.params['code']) callback = cherrypy.url() payload = {"client_id" : Client_ID, "client_secret" : 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() # write refresh_token line from AMZN response line = 'refresh_token = "{}"'.format(resp['refresh_token']) with open("creds.py", 'a') as f: f.write(line) # sent to provisioning browser success_msg = "<H1>Success!</H1>" success_msg +="<p>{} has been provisioned</p>".format(ProductID) success_msg +="<p>The refresh token has been added to your creds file</p>" if debug is True: success_msg +="<H2>Debug</H2>" success_msg +="<p>refresh_token:<br>" success_msg +="{}</p>".format(resp['refresh_token']) return success_msg
def code(self, var=None, **params): code = urllib.quote(cherrypy.request.params['code']) callback = cherrypy.url() payload = {"client_id": Client_ID, "client_secret": 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() line = 'refresh_token = "' + resp['refresh_token'] + '"' with open("creds.py", 'a') as f: f.write(line) return "Success!, refresh token has been added to your creds file, you may now reboot the Pi <br>{}".format(resp['refresh_token'])
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
def delete(self): """Remove ALL cached variants of the current resource.""" uri = cherrypy.url(qs=cherrypy.serving.request.query_string) self.store.pop(uri, None)
def __init__(self, urls, status=None, encoding=None): import cherrypy request = cherrypy.serving.request if isinstance(urls, text_or_bytes): urls = [urls] abs_urls = [] for url in urls: url = tonative(url, encoding or self.encoding) # 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. url = _urljoin(cherrypy.url(), url) abs_urls.append(url) self.urls = abs_urls # RFC 2616 indicates a 301 response code fits our goal; however, # browser support for 301 is quite messy. Do 302/303 instead. See # http://www.alanflavell.org.uk/www/post-redirect.html if status is None: if request.protocol >= (1, 1): status = 303 else: status = 302 else: status = int(status) if status < 300 or status > 399: raise ValueError('status must be between 300 and 399.') self.status = status CherryPyException.__init__(self, abs_urls, status)
def authresponse(self, var=None, **params): code = urllib.quote(cherrypy.request.params['code']) callback = cherrypy.url() payload = {"client_id": Client_ID, "client_secret": 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() line = '\nrefresh_token = "{}"'.format(resp['refresh_token']) with open("creds.py", 'a') as f: f.write(line) return "Success!, refresh token has been added to your creds file, you may now run <code>python alexa.py</code> <br>{}".format( resp['refresh_token'])
def logged_in(f: callable, *args, **kwargs): if cmd_args.no_anonymous_access: if not cherrypy.session.get('logged_in'): url = cherrypy.url() # http://0.0.0.0:8080/dbs splits = url.split('/') # ['https:', '', '0.0.0.0:8080', 'dbs'] if len(splits) > 3 and splits[3] in ['dbs', 'metrics', 'logs']: raise cherrypy.HTTPRedirect('/login' + ('?returl=/' + '/'.join(splits[3:]))) else: raise cherrypy.HTTPRedirect('/login') return f(*args, **kwargs)
def code(self, var=None, **params): code = urllib.quote(cherrypy.request.params['code']) callback = cherrypy.url() payload = {"client_id" : Client_ID, "client_secret" : 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() return "Done, add the following line to your creds file:<br><br>refresh_token ='%s'" % resp['refresh_token']
def authresponse(self, var=None, **params): code = urllib.quote(cherrypy.request.params['code']) callback = cherrypy.url() payload = { "client_id": CLIENT_ID, "client_secret": 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() return "Success! Here is your refresh token:<br>{}".format( resp['refresh_token'])
def index(self): return """<html> <body>Try some <a href='%s?a=7'>other</a> path, or a <a href='%s?n=14'>default</a> path.<br /> Or, just look at the pretty picture:<br /> <img src='%s' /> </body></html>""" % (url("other"), url("else"), url("files/made_with_cherrypy_small.png"))
def testSlashes(self): # Test that requests for index methods without a trailing slash # get redirected to the same URI path with a trailing slash. # Make sure GET params are preserved. self.getPage("/redirect?id=3") self.assertStatus(301) self.assertMatchesBody('<a href=([\'"])%s/redirect/[?]id=3\\1>' "%s/redirect/[?]id=3</a>" % (self.base(), self.base())) if self.prefix(): # Corner case: the "trailing slash" redirect could be tricky if # we're using a virtual root and the URI is "/vroot" (no slash). self.getPage("") self.assertStatus(301) self.assertMatchesBody("<a href=(['\"])%s/\\1>%s/</a>" % (self.base(), self.base())) # Test that requests for NON-index methods WITH a trailing slash # get redirected to the same URI path WITHOUT a trailing slash. # Make sure GET params are preserved. self.getPage("/redirect/by_code/?code=307") self.assertStatus(301) self.assertMatchesBody("<a href=(['\"])%s/redirect/by_code[?]code=307\\1>" "%s/redirect/by_code[?]code=307</a>" % (self.base(), self.base())) # If the trailing_slash tool is off, CP should just continue # as if the slashes were correct. But it needs some help # inside cherrypy.url to form correct output. self.getPage('/url?path_info=page1') self.assertBody('%s/url/page1' % self.base()) self.getPage('/url/leaf/?path_info=page1') self.assertBody('%s/url/page1' % self.base())
def testFlatten(self): for url in ["/flatten/as_string", "/flatten/as_list", "/flatten/as_yield", "/flatten/as_dblyield", "/flatten/as_refyield"]: self.getPage(url) self.assertBody('content')
def __init__(self, urls, status=None, encoding=None): import cherrypy request = cherrypy.serving.request if isinstance(urls, text_or_bytes): urls = [urls] abs_urls = [] for url in urls: url = tonative(url, encoding or self.encoding) # 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. url = _urljoin(cherrypy.url(), url) abs_urls.append(url) self.urls = abs_urls # RFC 2616 indicates a 301 response code fits our goal; however, # browser support for 301 is quite messy. Do 302/303 instead. See # http://www.alanflavell.org.uk/www/post-redirect.html if status is None: if request.protocol >= (1, 1): status = 303 else: status = 302 else: status = int(status) if status < 300 or status > 399: raise ValueError("status must be between 300 and 399.") self.status = status CherryPyException.__init__(self, abs_urls, status)
def url(self, path="", qs="", script_name=None, relative=None): """Create an absolute URL for the given path. If 'path' starts with a slash ('/'), this will return (base + script_name + path + qs). If it does not start with a slash, this returns (base url + script_name [+ request.path_info] + path + qs). If script_name is None, an appropriate value will be automatically determined from the current request path. If no parameters are specified, an absolute URL for the current request path (minus the querystring) by passing no args. If url(qs=request.query_string), is called, the original client URL (assuming no internal redirections) should be returned. If relative is None or not provided, an appropriate value will be automatically determined. If False, the output will be an absolute URL (including the scheme, host, vhost, and script_name). If True, the output will instead be a URL that is relative to the current request path, perhaps including '..' atoms. If relative is the string 'server', the output will instead be a URL that is relative to the server root; i.e., it will start with a slash. """ return cherrypy.url(path=path, qs=qs, script_name=script_name, relative=relative)