def merge_url_qs(url, **kw): """ Merge the query string elements of a URL with the ones in ``kw``. If any query string element exists in ``url`` that also exists in ``kw``, replace it.""" segments = urlsplit(url) extra_qs = [ (k, v) for (k, v) in parse_qsl(segments.query, keep_blank_values=1) if k not in kw ] qs = urlencode(sorted(kw.items())) if extra_qs: qs += '&' + urlencode(extra_qs) return urlunsplit( (segments.scheme, segments.netloc, segments.path, qs, segments.fragment) )
def parse_url_overrides(request, kw): """ Parse special arguments passed when generating urls. The supplied dictionary is mutated when we pop arguments. Returns a 3-tuple of the format: ``(app_url, qs, anchor)``. """ app_url = kw.pop('_app_url', None) scheme = kw.pop('_scheme', None) host = kw.pop('_host', None) port = kw.pop('_port', None) query = kw.pop('_query', '') anchor = kw.pop('_anchor', '') if app_url is None: if (scheme is not None or host is not None or port is not None): app_url = request._partial_application_url(scheme, host, port) else: app_url = request.application_url qs = '' if query: if isinstance(query, string_types): qs = '?' + url_quote(query, QUERY_SAFE) else: qs = '?' + urlencode(query, doseq=True) frag = '' if anchor: frag = '#' + url_quote(anchor, ANCHOR_SAFE) return app_url, qs, frag
def render_as_html_by_public(self): author_id = RequestGetUserId(self.request) if not is_authorized_id(author_id): raise Exception('Unauthorized') internal_link = urlencode(self.request.params) try: problems = self._get_monitor(internal_link).get('data') except Exception as e: # TODO: как это будет рендерится? мы ведь рендерим шаблон. # Надо разграничить рендеринг шаблона и возвращение джейсона return { "result": "error", "message": str(e), "stack": traceback.format_exc() } if problems is None: return {"result": "error", "message": 'Something was wrong'} data = {} data['problems'] = problems # Get extra info for problems' contests data['contests'] = self._get_contests_info(problems) return self._make_template_values(data)
def _init_navigation(self): nav = Navigation(self) # left side url = self.url_for(self.name + '.html') fmt = '%s?year=%d&month=%d&day=%d%s' if self.nav_params: extra = '&%s' % urlencode(self.nav_params) else: extra = '' nav.prev_url = fmt % (url, self.prev_datetime.year, self.prev_datetime.month, self.prev_datetime.day, extra) nav.next_url = fmt % (url, self.next_datetime.year, self.next_datetime.month, self.next_datetime.day, extra) if not self._is_today_shown(): nav.today_url = fmt % (url, self.now_datetime.year, self.now_datetime.month, self.now_datetime.day, extra) self.navigation = nav
def _init_navigation(self): nav = Navigation(self) base_url = '%s?year=%d&month=%d&day=%d&per_page=%d' % ( self.url_for(self.name + '.html'), self.focus_datetime.year, self.focus_datetime.month, self.focus_datetime.day, self.per_page) if self.nav_params: base_url += '&%s' % urlencode(self.nav_params) # today_url if self.page == 1: nav.today_url = None else: nav.today_url = base_url + "&page=1" # prev_url if self.page == 1: nav.prev_url = None else: prev_page = self.page - 1 nav.prev_url = base_url + ("&page=%d" % prev_page) # next_url if not self.has_more: nav.next_url = None else: next_page = self.page + 1 nav.next_url = base_url + ("&page=%d" % next_page) self.navigation = nav
def forbidden_redirect(context, request): if authenticated_userid(request): location = request.application_url + '/@@forbidden' else: location = request.application_url + '/@@login?' + urlencode( {'came_from': request.url}) return HTTPFound(location=location)
def render_batch_link(self, batch, css_class=None): """Render batch link""" args = self.get_query_string_args() args[self.table.prefix + "-batch-start"] = batch.start args[self.table.prefix + "-batch-size"] = batch.size query = urlencode(sorted(args.items())) table_url = absolute_url(self.table, self.request) idx = batch.index + 1 css = ' class="%s"' % css_class css_class = css if css_class else '' return '<a href="%s?%s"%s>%s</a>' % (table_url, query, css_class, idx)
def forbidden_redirect(context, request): """ Forbidden redirect view. Redirects to the login form for anonymous users or to the forbidden view for authenticated users. :result: Redirect to one of the above. :rtype: pyramid.httpexceptions.HTTPFound """ if request.authenticated_userid: location = request.application_url + "/@@forbidden" else: location = request.application_url + "/@@login?" + urlencode({"came_from": request.url}) return HTTPFound(location=location)
def loginPageRedirect(self, request): # append direct information redirect = request.path if redirect in ["", "/"] or redirect.startswith("/login"): # don't do a redirect in these cases return HTTPFound("/login/") if redirect[0] == "/": redirect = redirect[1:] return HTTPFound("/login/?%s" % urlencode({"redir": request.path}), request=request)
def forbidden_redirect(context, request): """ Forbidden redirect view. Redirects to the login form for anonymous users or to the forbidden view for authenticated users. :result: Redirect to one of the above. :rtype: pyramid.httpexceptions.HTTPFound """ if request.authenticated_userid: location = request.application_url + '/@@forbidden' else: location = request.application_url + '/@@login?' + urlencode( {'came_from': request.url}) return HTTPFound(location=location)
def _app_method( self, method_name, url, params=None, exception=None, headers=None, content_type=None, upload_files=None, status=None, check_response=True, **kwargs ) -> TestResponse: if not url.startswith(('/', 'http://', 'https://')): url = f"/{self.url_prefix}/{url.lstrip('/')}" headers = headers or {} kwargs['headers'] = headers if content_type and method_name not in {'get', 'head', 'options'}: kwargs['content_type'] = content_type if upload_files: kwargs['upload_files'] = upload_files try: url.encode('ascii') except UnicodeEncodeError: split_result = list(urlsplit(url)) split_result[2] = quote(split_result[2]) url = urlunsplit(split_result) if isinstance(params, dict) and not method_name.endswith('_json'): params = { key: '' if value is None else value for key, value in params.items() } http_method = getattr(self.test_app, method_name, None) assert http_method is not None, 'Unknown HTTP method: %s' % method_name if method_name == 'head': head_url = url if params: # TastApp.head() is not support `params` argument if isinstance(params, dict): params = urlencode(params) head_url += '?' + params response = http_method(head_url, status='*', **kwargs) kwargs['params'] = params else: if method_name != 'options': kwargs['params'] = params response = http_method(url, status='*', **kwargs) if check_response: if exception: status = exception.code self._check_status(response, method_name, url, status, **kwargs) self._check_error_code(response, method_name, url, exception, **kwargs) return response
def search(self, expression, offset=0, limit=None): limit = limit or self.pagesize logger.info( "Google: searching documents, expression='{0}', offset={1}, limit={2}" .format(expression, offset, limit)) # 1. compute url parameter parameters = { 'start': offset, 'num': limit, } # expression might be fulltext or json try: json_params = json.loads(expression) parameters.update(json_params) except ValueError: parameters['q'] = expression if not parameters['q']: parameters['q'] = '' # 2. perform search url = self.baseurl + '&' + urlencode(parameters) logger.info("Google search url: {0}".format(url)) response = requests.get(url, headers={'User-Agent': self.user_agent}) #print "google status:", response.status_code #print "google response:", response.content payload = { 'query': expression, } if response.status_code == 200: payload.update(self.parse_response(response.content)) elif response.status_code == 503 and 'CaptchaRedirect' in response.content: payload['message'] = self.tweak_captcha_response(response.content) else: message = 'Accessing Google Patent Search failed with status={0} for url {1}'.format( str(response.status_code) + ' ' + response.reason, url) logger.error(message + ' body:\n' + response.content) raise ValueError(message) return payload
def _render_example_to_rst(self, method, example_info): """ :type method: str :type example_info: restfw.usage_examples.structs.ExampleInfo :rtype: str """ url = example_info.request_info.url if '_' in url: # Encode for restructuredText url = url.replace('_', '\\_') params = example_info.request_info.params if method in ('GET', 'HEAD') and params: url += '?' + urlencode(params, doseq=True) params = None if params: params = json.dumps(params, indent=2, ensure_ascii=False) response_headers = {} expected_headers = example_info.response_info.expected_headers or {} interested_headers = sorted({'Location' }.union(expected_headers.keys())) for header in interested_headers: value = example_info.response_info.headers.get(header) if value: response_headers[header] = value response_body = json.dumps(example_info.response_info.json_body, indent=2, ensure_ascii=False) title = '{} {}'.format(example_info.response_info.status_code, example_info.response_info.status_name) template = self._get_template('example.rst') text = template.render( title=title, description=example_info.description, method=method, url=url, headers=example_info.request_info.headers, params=params, response_status=example_info.response_info.status_code, response_headers=response_headers, response_body=response_body, ) return text
def get_href(context, *elements, **kw): # Return absolute url: #return context.request.resource_url(context, *elements, **kw) # Return url starting with '/': path = resource_path(context) if elements: if path[-1] != '/': path += '/' path += '/'.join(elements) if 'query' in kw: query = kw['query'] if query: return '%s?%s' % (path, urlencode(query, doseq=True)) return path
def expand_redirect_uri(self, query_data, fragment_data): """Expand a redirect URI with data and return the new URI.""" scheme, netloc, path, query, _old_fragment = urlsplit( self.redirect_uri) fragment = '' if query_data: # Mix query_data into the query string. if self.state is not None: d = {'state': self.state} d.update(query_data) query_data = d q = parse_qsl(query, keep_blank_values=True) q = [(name, value) for (name, value) in q if name not in query_data] q.extend(sorted(query_data.iteritems())) query = urlencode(q) if fragment_data: # Add fragment_data to the fragment. if self.state is not None: d = {'state': self.state} d.update(fragment_data) fragment_data = d fragment = urlencode(sorted(fragment_data.items())) return urlunsplit((scheme, netloc, path, query, fragment))
def create(self): if not RequestCheckUserCapability(self.request, 'moodle/ejudge_submits:comment'): raise Exception("Auth Error") author_id = RequestGetUserId(self.request) random_string = ''.join(random.SystemRandom().choice( string.ascii_lowercase + string.digits) for _ in range(20)) encoded_url = urlencode(self.request.params) monitor = MonitorLink(author_id=author_id, link=random_string, internal_link=encoded_url) with transaction.manager: DBSession.add(monitor) response = { 'link': random_string } return response
def create_secret_link(self): if not RequestCheckUserCapability(self.request, 'moodle/ejudge_submits:comment'): raise Exception("Auth Error") author_id = RequestGetUserId(self.request) random_string = ''.join( random.SystemRandom().choice(string.ascii_lowercase + string.digits) for _ in range(20)) internal_link = urlencode(self.request.params) monitor = MonitorLink(author_id=author_id, link=random_string, internal_link=internal_link) with transaction.manager: DBSession.add(monitor) response = {'link': random_string} return response
def login(root, request): """User started the login process. Redirect to the authorize endpoint, where the user will enter credentials, then WingCash will redirect the browser to login_callback. """ instance_config = get_instance_config() redirect_uri = resource_url(root, request, 'login_callback') # See the OAuth 2 spec, section 4.1.1 q = urlencode([ ('response_type', 'code'), ('client_id', instance_config['client_id']), ('redirect_uri', redirect_uri), ('scope', request_scope), ('state', 'abc123'), ('uuid', 'd4de07e3-d731-441b-81e2-5c2158205935'), ('name', 'MicroBank Device'), # ('force_login', 'true'), ]) url = '%s?%s' % (instance_config['authorize_url'], q) return HTTPFound(location=url)
def parse_url_overrides(kw): """Parse special arguments passed when generating urls. The supplied dictionary is mutated, popping arguments as necessary. Returns a 6-tuple of the format ``(app_url, scheme, host, port, qs, anchor)``. """ anchor = '' qs = '' app_url = None host = None scheme = None port = None if '_query' in kw: query = kw.pop('_query') if isinstance(query, string_types): qs = '?' + url_quote(query, QUERY_SAFE) elif query: qs = '?' + urlencode(query, doseq=True) if '_anchor' in kw: anchor = kw.pop('_anchor') anchor = url_quote(anchor, ANCHOR_SAFE) anchor = '#' + anchor if '_app_url' in kw: app_url = kw.pop('_app_url') if '_host' in kw: host = kw.pop('_host') if '_scheme' in kw: scheme = kw.pop('_scheme') if '_port' in kw: port = kw.pop('_port') return app_url, scheme, host, port, qs, anchor
def get_redirect_query(request, expression=None, query_args=None): query_args = query_args or {} # FIXME: does not work due reverse proxy anomalies, tune it to make it work! #query = '{field}={value}'.format(**locals()) #return HTTPFound(location=request.route_url('patentsearch', _query={'query': query})) # FIXME: this is a hack path = '/' host = request.headers.get('Host') # TODO: at least look this up in development.ini if 'localhost:6543' in host: path = '' redirect_url = path if expression: query_args.update({'query': expression}) if query_args: redirect_url += '?' + urlencode(query_args) return HTTPFound(redirect_url)
def absolute_url(context, request, view_name=None, query=None): """Get resource absolute_url :param object context: the persistent object for which absolute URL is required :param request: the request on which URL is based :param str view_name: an optional view name to add to URL :param str/dict query: an optional URL arguments string or mapping This absolute URL function is based on default Pyramid's :py:func:`resource_url` function, but add checks to remove some double slashes, and add control on view name when it begins with a '#' character which is used by MyAMS.js framework. """ # if we pass a string to absolute_url(), argument is returned as-is! if isinstance(context, str): return context # if we have several parents without name in the lineage, the resource URL contains a double # slash which generates "NotFound" exceptions; so we replace it with a single slash... result = resource_url(context, request).replace('//', '/').replace(':/', '://') if result.endswith('/'): result = result[:-1] if view_name: if view_name.startswith('#'): result += view_name else: result += '/' + view_name if query: qstr = '' if isinstance(query, str): qstr = '?' + url_quote(query, QUERY_SAFE) elif query: qstr = '?' + urlencode(query, doseq=True) result += qstr return result
def resource_url(self, resource, *elements, **kw): """ Generate a string representing the absolute URL of the :term:`resource` object based on the ``wsgi.url_scheme``, ``HTTP_HOST`` or ``SERVER_NAME`` in the request, plus any ``SCRIPT_NAME``. The overall result of this method is always a UTF-8 encoded string. Examples:: request.resource_url(resource) => http://example.com/ request.resource_url(resource, 'a.html') => http://example.com/a.html request.resource_url(resource, 'a.html', query={'q':'1'}) => http://example.com/a.html?q=1 request.resource_url(resource, 'a.html', anchor='abc') => http://example.com/a.html#abc request.resource_url(resource, app_url='') => / Any positional arguments passed in as ``elements`` must be strings Unicode objects, or integer objects. These will be joined by slashes and appended to the generated resource URL. Each of the elements passed in is URL-quoted before being appended; if any element is Unicode, it will converted to a UTF-8 bytestring before being URL-quoted. If any element is an integer, it will be converted to its string representation before being URL-quoted. .. warning:: if no ``elements`` arguments are specified, the resource URL will end with a trailing slash. If any ``elements`` are used, the generated URL will *not* end in trailing a slash. If a keyword argument ``query`` is present, it will be used to compose a query string that will be tacked on to the end of the URL. The value of ``query`` must be a sequence of two-tuples *or* a data structure with an ``.items()`` method that returns a sequence of two-tuples (presumably a dictionary). This data structure will be turned into a query string per the documentation of ``pyramid.url.urlencode`` function. After the query data is turned into a query string, a leading ``?`` is prepended, and the resulting string is appended to the generated URL. .. note:: Python data structures that are passed as ``query`` which are sequences or dictionaries are turned into a string under the same rules as when run through :func:`urllib.urlencode` with the ``doseq`` argument equal to ``True``. This means that sequences can be passed as values, and a k=v pair will be placed into the query string for each value. If a keyword argument ``anchor`` is present, its string representation will be used as a named anchor in the generated URL (e.g. if ``anchor`` is passed as ``foo`` and the resource URL is ``http://example.com/resource/url``, the resulting generated URL will be ``http://example.com/resource/url#foo``). .. note:: If ``anchor`` is passed as a string, it should be UTF-8 encoded. If ``anchor`` is passed as a Unicode object, it will be converted to UTF-8 before being appended to the URL. The anchor value is not quoted in any way before being appended to the generated URL. If both ``anchor`` and ``query`` are specified, the anchor element will always follow the query element, e.g. ``http://example.com?foo=1#bar``. If any of the keyword arguments ``scheme``, ``host``, or ``port`` is passed and is non-``None``, the provided value will replace the named portion in the generated URL. For example, if you pass ``host='foo.com'``, and the URL that would have been generated without the host replacement is ``http://example.com/a``, the result will be ``https://foo.com/a``. If ``scheme`` is passed as ``https``, and an explicit ``port`` is not passed, the ``port`` value is assumed to have been passed as ``443``. Likewise, if ``scheme`` is passed as ``http`` and ``port`` is not passed, the ``port`` value is assumed to have been passed as ``80``. To avoid this behavior, always explicitly pass ``port`` whenever you pass ``scheme``. If a keyword argument ``app_url`` is passed and is not ``None``, it should be a string that will be used as the port/hostname/initial path portion of the generated URL instead of the default request application URL. For example, if ``app_url='http://foo'``, then the resulting url of a resource that has a path of ``/baz/bar`` will be ``http://foo/baz/bar``. If you want to generate completely relative URLs with no leading scheme, host, port, or initial path, you can pass ``app_url=''`. Passing ``app_url=''` when the resource path is ``/baz/bar`` will return ``/baz/bar``. .. note:: ``app_url`` is new as of Pyramid 1.3. If ``app_url`` is passed and any of ``scheme``, ``port``, or ``host`` are also passed, ``app_url`` will take precedence and the values passed for ``scheme``, ``host``, and/or ``port`` will be ignored. If the ``resource`` passed in has a ``__resource_url__`` method, it will be used to generate the URL (scheme, host, port, path) that for the base resource which is operated upon by this function. See also :ref:`overriding_resource_url_generation`. .. note:: If the :term:`resource` used is the result of a :term:`traversal`, it must be :term:`location`-aware. The resource can also be the context of a :term:`URL dispatch`; contexts found this way do not need to be location-aware. .. note:: If a 'virtual root path' is present in the request environment (the value of the WSGI environ key ``HTTP_X_VHM_ROOT``), and the resource was obtained via :term:`traversal`, the URL path will not include the virtual root prefix (it will be stripped off the left hand side of the generated URL). .. note:: For backwards compatibility purposes, this method is also aliased as the ``model_url`` method of request. """ try: reg = self.registry except AttributeError: reg = get_current_registry() # b/c url_adapter = reg.queryMultiAdapter((resource, self), IResourceURL) if url_adapter is None: url_adapter = ResourceURL(resource, self) virtual_path = getattr(url_adapter, 'virtual_path', None) if virtual_path is None: # old-style IContextURL adapter (Pyramid 1.2 and previous) warnings.warn( 'Pyramid is using an IContextURL adapter to generate a ' 'resource URL; any "app_url", "host", "port", or "scheme" ' 'arguments passed to resource_url are being ignored. To ' 'avoid this behavior, as of Pyramid 1.3, register an ' 'IResourceURL adapter instead of an IContextURL ' 'adapter for the resource type(s). IContextURL adapters ' 'will be ignored in a later major release of Pyramid.', DeprecationWarning, 2) resource_url = url_adapter() else: # newer-style IResourceURL adapter (Pyramid 1.3 and after) app_url = None scheme = None host = None port = None if 'app_url' in kw: app_url = kw['app_url'] if 'scheme' in kw: scheme = kw['scheme'] if 'host' in kw: host = kw['host'] if 'port' in kw: port = kw['port'] if app_url is None: if scheme or host or port: app_url = self._partial_application_url(scheme, host, port) else: app_url = self.application_url resource_url = None local_url = getattr(resource, '__resource_url__', None) if local_url is not None: # the resource handles its own url generation d = dict( virtual_path = virtual_path, physical_path = url_adapter.physical_path, app_url = app_url, ) # allow __resource_url__ to punt by returning None resource_url = local_url(self, d) if resource_url is None: # the resource did not handle its own url generation or the # __resource_url__ function returned None resource_url = app_url + virtual_path qs = '' anchor = '' if 'query' in kw: qs = '?' + urlencode(kw['query'], doseq=True) if 'anchor' in kw: anchor = kw['anchor'] if isinstance(anchor, text_type): anchor = native_(anchor, 'utf-8') anchor = '#' + anchor if elements: suffix = _join_elements(elements) else: suffix = '' return resource_url + suffix + qs + anchor
def resource_url(self, resource, *elements, **kw): """ Generate a string representing the absolute URL of the :term:`resource` object based on the ``wsgi.url_scheme``, ``HTTP_HOST`` or ``SERVER_NAME`` in the request, plus any ``SCRIPT_NAME``. The overall result of this method is always a UTF-8 encoded string (never Unicode). Examples:: request.resource_url(resource) => http://example.com/ request.resource_url(resource, 'a.html') => http://example.com/a.html request.resource_url(resource, 'a.html', query={'q':'1'}) => http://example.com/a.html?q=1 request.resource_url(resource, 'a.html', anchor='abc') => http://example.com/a.html#abc Any positional arguments passed in as ``elements`` must be strings Unicode objects, or integer objects. These will be joined by slashes and appended to the generated resource URL. Each of the elements passed in is URL-quoted before being appended; if any element is Unicode, it will converted to a UTF-8 bytestring before being URL-quoted. If any element is an integer, it will be converted to its string representation before being URL-quoted. .. warning:: if no ``elements`` arguments are specified, the resource URL will end with a trailing slash. If any ``elements`` are used, the generated URL will *not* end in trailing a slash. If a keyword argument ``query`` is present, it will be used to compose a query string that will be tacked on to the end of the URL. The value of ``query`` must be a sequence of two-tuples *or* a data structure with an ``.items()`` method that returns a sequence of two-tuples (presumably a dictionary). This data structure will be turned into a query string per the documentation of ``pyramid.url.urlencode`` function. After the query data is turned into a query string, a leading ``?`` is prepended, and the resulting string is appended to the generated URL. .. note:: Python data structures that are passed as ``query`` which are sequences or dictionaries are turned into a string under the same rules as when run through :func:`urllib.urlencode` with the ``doseq`` argument equal to ``True``. This means that sequences can be passed as values, and a k=v pair will be placed into the query string for each value. If a keyword argument ``anchor`` is present, its string representation will be used as a named anchor in the generated URL (e.g. if ``anchor`` is passed as ``foo`` and the resource URL is ``http://example.com/resource/url``, the resulting generated URL will be ``http://example.com/resource/url#foo``). .. note:: If ``anchor`` is passed as a string, it should be UTF-8 encoded. If ``anchor`` is passed as a Unicode object, it will be converted to UTF-8 before being appended to the URL. The anchor value is not quoted in any way before being appended to the generated URL. If both ``anchor`` and ``query`` are specified, the anchor element will always follow the query element, e.g. ``http://example.com?foo=1#bar``. If the ``resource`` passed in has a ``__resource_url__`` method, it will be used to generate the URL (scheme, host, port, path) that for the base resource which is operated upon by this function. See also :ref:`overriding_resource_url_generation`. .. note:: If the :term:`resource` used is the result of a :term:`traversal`, it must be :term:`location`-aware. The resource can also be the context of a :term:`URL dispatch`; contexts found this way do not need to be location-aware. .. note:: If a 'virtual root path' is present in the request environment (the value of the WSGI environ key ``HTTP_X_VHM_ROOT``), and the resource was obtained via :term:`traversal`, the URL path will not include the virtual root prefix (it will be stripped off the left hand side of the generated URL). .. note:: For backwards compatibility purposes, this method is also aliased as the ``model_url`` method of request. """ try: reg = self.registry except AttributeError: reg = get_current_registry() # b/c context_url = reg.queryMultiAdapter((resource, self), IContextURL) if context_url is None: context_url = TraversalContextURL(resource, self) resource_url = context_url() qs = '' anchor = '' if 'query' in kw: qs = '?' + urlencode(kw['query'], doseq=True) if 'anchor' in kw: anchor = kw['anchor'] if isinstance(anchor, unicode): anchor = anchor.encode('utf-8') anchor = '#' + anchor if elements: suffix = _join_elements(elements) else: suffix = '' return resource_url + suffix + qs + anchor
def route_url(route_name, request, *elements, **kw): """Generates a fully qualified URL for a named :app:`Pyramid` :term:`route configuration`. .. note:: Calling :meth:`pyramid.Request.route_url` can be used to achieve the same result as :func:`pyramid.url.route_url`. Use the route's ``name`` as the first positional argument. Use a request object as the second positional argument. Additional positional arguments are appended to the URL as path segments after it is generated. Use keyword arguments to supply values which match any dynamic path elements in the route definition. Raises a :exc:`KeyError` exception if the URL cannot be generated for any reason (not enough arguments, for example). For example, if you've defined a route named "foobar" with the path ``{foo}/{bar}/*traverse``:: route_url('foobar', request, foo='1') => <KeyError exception> route_url('foobar', request, foo='1', bar='2') => <KeyError exception> route_url('foobar', request, foo='1', bar='2', traverse=('a','b')) => http://e.com/1/2/a/b route_url('foobar', request, foo='1', bar='2', traverse='/a/b') => http://e.com/1/2/a/b Values replacing ``:segment`` arguments can be passed as strings or Unicode objects. They will be encoded to UTF-8 and URL-quoted before being placed into the generated URL. Values replacing ``*remainder`` arguments can be passed as strings *or* tuples of Unicode/string values. If a tuple is passed as a ``*remainder`` replacement value, its values are URL-quoted and encoded to UTF-8. The resulting strings are joined with slashes and rendered into the URL. If a string is passed as a ``*remainder`` replacement value, it is tacked on to the URL untouched. If a keyword argument ``_query`` is present, it will be used to compose a query string that will be tacked on to the end of the URL. The value of ``_query`` must be a sequence of two-tuples *or* a data structure with an ``.items()`` method that returns a sequence of two-tuples (presumably a dictionary). This data structure will be turned into a query string per the documentation of :func:`pyramid.encode.urlencode` function. After the query data is turned into a query string, a leading ``?`` is prepended, and the resulting string is appended to the generated URL. .. note:: Python data structures that are passed as ``_query`` which are sequences or dictionaries are turned into a string under the same rules as when run through :func:`urllib.urlencode` with the ``doseq`` argument equal to ``True``. This means that sequences can be passed as values, and a k=v pair will be placed into the query string for each value. If a keyword argument ``_anchor`` is present, its string representation will be used as a named anchor in the generated URL (e.g. if ``_anchor`` is passed as ``foo`` and the route URL is ``http://example.com/route/url``, the resulting generated URL will be ``http://example.com/route/url#foo``). .. note:: If ``_anchor`` is passed as a string, it should be UTF-8 encoded. If ``_anchor`` is passed as a Unicode object, it will be converted to UTF-8 before being appended to the URL. The anchor value is not quoted in any way before being appended to the generated URL. If both ``_anchor`` and ``_query`` are specified, the anchor element will always follow the query element, e.g. ``http://example.com?foo=1#bar``. If a keyword ``_app_url`` is present, it will be used as the protocol/hostname/port/leading path prefix of the generated URL. For example, using an ``_app_url`` of ``http://example.com:8080/foo`` would cause the URL ``http://example.com:8080/foo/fleeb/flub`` to be returned from this function if the expansion of the route pattern associated with the ``route_name`` expanded to ``/fleeb/flub``. If ``_app_url`` is not specified, the result of ``request.application_url`` will be used as the prefix (the default). This function raises a :exc:`KeyError` if the URL cannot be generated due to missing replacement names. Extra replacement names are ignored. If the route object which matches the ``route_name`` argument has a :term:`pregenerator`, the ``*elements`` and ``**kw`` arguments arguments passed to this function might be augmented or changed. """ try: reg = request.registry except AttributeError: reg = get_current_registry() # b/c mapper = reg.getUtility(IRoutesMapper) route = mapper.get_route(route_name) if route is None: raise KeyError('No such route named %s' % route_name) if route.pregenerator is not None: elements, kw = route.pregenerator(request, elements, kw) anchor = '' qs = '' app_url = None if '_query' in kw: qs = '?' + urlencode(kw.pop('_query'), doseq=True) if '_anchor' in kw: anchor = kw.pop('_anchor') if isinstance(anchor, unicode): anchor = anchor.encode('utf-8') anchor = '#' + anchor if '_app_url' in kw: app_url = kw.pop('_app_url') path = route.generate(kw) # raises KeyError if generate fails if elements: suffix = _join_elements(elements) if not path.endswith('/'): suffix = '/' + suffix else: suffix = '' if app_url is None: # we only defer lookup of application_url until here because # it's somewhat expensive; we won't need to do it if we've # been passed _app_url app_url = request.application_url return app_url + path + suffix + qs + anchor
def _callFUT(self, query, doseq=False): from pyramid.encode import urlencode return urlencode(query, doseq)
def page_url(page): params = request.GET.copy() params['batch_start'] = str(page * batch_size) return '%s?%s' % (url, urlencode(params))
def resource_url(self, resource, *elements, **kw): """ Generate a string representing the absolute URL of the :term:`resource` object based on the ``wsgi.url_scheme``, ``HTTP_HOST`` or ``SERVER_NAME`` in the request, plus any ``SCRIPT_NAME``. The overall result of this method is always a UTF-8 encoded string (never Unicode). Examples:: request.resource_url(resource) => http://example.com/ request.resource_url(resource, 'a.html') => http://example.com/a.html request.resource_url(resource, 'a.html', query={'q':'1'}) => http://example.com/a.html?q=1 request.resource_url(resource, 'a.html', anchor='abc') => http://example.com/a.html#abc Any positional arguments passed in as ``elements`` must be strings Unicode objects, or integer objects. These will be joined by slashes and appended to the generated resource URL. Each of the elements passed in is URL-quoted before being appended; if any element is Unicode, it will converted to a UTF-8 bytestring before being URL-quoted. If any element is an integer, it will be converted to its string representation before being URL-quoted. .. warning:: if no ``elements`` arguments are specified, the resource URL will end with a trailing slash. If any ``elements`` are used, the generated URL will *not* end in trailing a slash. If a keyword argument ``query`` is present, it will be used to compose a query string that will be tacked on to the end of the URL. The value of ``query`` must be a sequence of two-tuples *or* a data structure with an ``.items()`` method that returns a sequence of two-tuples (presumably a dictionary). This data structure will be turned into a query string per the documentation of ``pyramid.url.urlencode`` function. After the query data is turned into a query string, a leading ``?`` is prepended, and the resulting string is appended to the generated URL. .. note:: Python data structures that are passed as ``query`` which are sequences or dictionaries are turned into a string under the same rules as when run through :func:`urllib.urlencode` with the ``doseq`` argument equal to ``True``. This means that sequences can be passed as values, and a k=v pair will be placed into the query string for each value. If a keyword argument ``anchor`` is present, its string representation will be used as a named anchor in the generated URL (e.g. if ``anchor`` is passed as ``foo`` and the resource URL is ``http://example.com/resource/url``, the resulting generated URL will be ``http://example.com/resource/url#foo``). .. note:: If ``anchor`` is passed as a string, it should be UTF-8 encoded. If ``anchor`` is passed as a Unicode object, it will be converted to UTF-8 before being appended to the URL. The anchor value is not quoted in any way before being appended to the generated URL. If both ``anchor`` and ``query`` are specified, the anchor element will always follow the query element, e.g. ``http://example.com?foo=1#bar``. If the ``resource`` passed in has a ``__resource_url__`` method, it will be used to generate the URL (scheme, host, port, path) that for the base resource which is operated upon by this function. See also :ref:`overriding_resource_url_generation`. .. note:: If the :term:`resource` used is the result of a :term:`traversal`, it must be :term:`location`-aware. The resource can also be the context of a :term:`URL dispatch`; contexts found this way do not need to be location-aware. .. note:: If a 'virtual root path' is present in the request environment (the value of the WSGI environ key ``HTTP_X_VHM_ROOT``), and the resource was obtained via :term:`traversal`, the URL path will not include the virtual root prefix (it will be stripped off the left hand side of the generated URL). .. note:: For backwards compatibility purposes, this method is also aliased as the ``model_url`` method of request. """ try: reg = self.registry except AttributeError: reg = get_current_registry() # b/c context_url = reg.queryMultiAdapter((resource, self), IContextURL) if context_url is None: context_url = TraversalContextURL(resource, self) resource_url = context_url() qs = '' anchor = '' if 'query' in kw: qs = '?' + urlencode(kw['query'], doseq=True) if 'anchor' in kw: anchor = kw['anchor'] if isinstance(anchor, text_type): anchor = native_(anchor, 'utf-8') anchor = '#' + anchor if elements: suffix = _join_elements(elements) else: suffix = '' return resource_url + suffix + qs + anchor
def resource_url(self, resource, *elements, **kw): """ Generate a string representing the absolute URL of the :term:`resource` object based on the ``wsgi.url_scheme``, ``HTTP_HOST`` or ``SERVER_NAME`` in the request, plus any ``SCRIPT_NAME``. The overall result of this method is always a UTF-8 encoded string. Examples:: request.resource_url(resource) => http://example.com/ request.resource_url(resource, 'a.html') => http://example.com/a.html request.resource_url(resource, 'a.html', query={'q':'1'}) => http://example.com/a.html?q=1 request.resource_url(resource, 'a.html', anchor='abc') => http://example.com/a.html#abc request.resource_url(resource, app_url='') => / Any positional arguments passed in as ``elements`` must be strings Unicode objects, or integer objects. These will be joined by slashes and appended to the generated resource URL. Each of the elements passed in is URL-quoted before being appended; if any element is Unicode, it will converted to a UTF-8 bytestring before being URL-quoted. If any element is an integer, it will be converted to its string representation before being URL-quoted. .. warning:: if no ``elements`` arguments are specified, the resource URL will end with a trailing slash. If any ``elements`` are used, the generated URL will *not* end in a trailing slash. If a keyword argument ``query`` is present, it will be used to compose a query string that will be tacked on to the end of the URL. The value of ``query`` may be a sequence of two-tuples *or* a data structure with an ``.items()`` method that returns a sequence of two-tuples (presumably a dictionary). This data structure will be turned into a query string per the documentation of :func:``pyramid.url.urlencode`` function. This will produce a query string in the ``x-www-form-urlencoded`` encoding. A non-``x-www-form-urlencoded`` query string may be used by passing a *string* value as ``query`` in which case it will be URL-quoted (e.g. query="foo bar" will become "foo%20bar"). However, the result will not need to be in ``k=v`` form as required by ``x-www-form-urlencoded``. After the query data is turned into a query string, a leading ``?`` is prepended, and the resulting string is appended to the generated URL. .. note:: Python data structures that are passed as ``query`` which are sequences or dictionaries are turned into a string under the same rules as when run through :func:`urllib.urlencode` with the ``doseq`` argument equal to ``True``. This means that sequences can be passed as values, and a k=v pair will be placed into the query string for each value. .. versionchanged:: 1.5 Allow the ``query`` option to be a string to enable alternative encodings. If a keyword argument ``anchor`` is present, its string representation will be used as a named anchor in the generated URL (e.g. if ``anchor`` is passed as ``foo`` and the resource URL is ``http://example.com/resource/url``, the resulting generated URL will be ``http://example.com/resource/url#foo``). .. note:: If ``anchor`` is passed as a string, it should be UTF-8 encoded. If ``anchor`` is passed as a Unicode object, it will be converted to UTF-8 before being appended to the URL. .. versionchanged:: 1.5 The ``anchor`` option will be escaped instead of using its raw string representation. If both ``anchor`` and ``query`` are specified, the anchor element will always follow the query element, e.g. ``http://example.com?foo=1#bar``. If any of the keyword arguments ``scheme``, ``host``, or ``port`` is passed and is non-``None``, the provided value will replace the named portion in the generated URL. For example, if you pass ``host='foo.com'``, and the URL that would have been generated without the host replacement is ``http://example.com/a``, the result will be ``http://foo.com/a``. If ``scheme`` is passed as ``https``, and an explicit ``port`` is not passed, the ``port`` value is assumed to have been passed as ``443``. Likewise, if ``scheme`` is passed as ``http`` and ``port`` is not passed, the ``port`` value is assumed to have been passed as ``80``. To avoid this behavior, always explicitly pass ``port`` whenever you pass ``scheme``. If a keyword argument ``app_url`` is passed and is not ``None``, it should be a string that will be used as the port/hostname/initial path portion of the generated URL instead of the default request application URL. For example, if ``app_url='http://foo'``, then the resulting url of a resource that has a path of ``/baz/bar`` will be ``http://foo/baz/bar``. If you want to generate completely relative URLs with no leading scheme, host, port, or initial path, you can pass ``app_url=''``. Passing ``app_url=''`` when the resource path is ``/baz/bar`` will return ``/baz/bar``. .. versionadded:: 1.3 ``app_url`` If ``app_url`` is passed and any of ``scheme``, ``port``, or ``host`` are also passed, ``app_url`` will take precedence and the values passed for ``scheme``, ``host``, and/or ``port`` will be ignored. If the ``resource`` passed in has a ``__resource_url__`` method, it will be used to generate the URL (scheme, host, port, path) for the base resource which is operated upon by this function. .. seealso:: See also :ref:`overriding_resource_url_generation`. .. versionadded:: 1.5 ``route_name``, ``route_kw``, and ``route_remainder_name`` If ``route_name`` is passed, this function will delegate its URL production to the ``route_url`` function. Calling ``resource_url(someresource, 'element1', 'element2', query={'a':1}, route_name='blogentry')`` is roughly equivalent to doing:: remainder_path = request.resource_path(someobject) url = request.route_url( 'blogentry', 'element1', 'element2', _query={'a':'1'}, traverse=traversal_path, ) It is only sensible to pass ``route_name`` if the route being named has a ``*remainder`` stararg value such as ``*traverse``. The remainder value will be ignored in the output otherwise. By default, the resource path value will be passed as the name ``traverse`` when ``route_url`` is called. You can influence this by passing a different ``route_remainder_name`` value if the route has a different ``*stararg`` value at its end. For example if the route pattern you want to replace has a ``*subpath`` stararg ala ``/foo*subpath``:: request.resource_url( resource, route_name='myroute', route_remainder_name='subpath' ) If ``route_name`` is passed, it is also permissible to pass ``route_kw``, which will passed as additional keyword arguments to ``route_url``. Saying ``resource_url(someresource, 'element1', 'element2', route_name='blogentry', route_kw={'id':'4'}, _query={'a':'1'})`` is roughly equivalent to:: remainder_path = request.resource_path_tuple(someobject) kw = {'id':'4', '_query':{'a':'1'}, 'traverse':traversal_path} url = request.route_url( 'blogentry', 'element1', 'element2', **kw, ) If ``route_kw`` or ``route_remainder_name`` is passed, but ``route_name`` is not passed, both ``route_kw`` and ``route_remainder_name`` will be ignored. If ``route_name`` is passed, the ``__resource_url__`` method of the resource passed is ignored unconditionally. This feature is incompatible with resources which generate their own URLs. .. note:: If the :term:`resource` used is the result of a :term:`traversal`, it must be :term:`location`-aware. The resource can also be the context of a :term:`URL dispatch`; contexts found this way do not need to be location-aware. .. note:: If a 'virtual root path' is present in the request environment (the value of the WSGI environ key ``HTTP_X_VHM_ROOT``), and the resource was obtained via :term:`traversal`, the URL path will not include the virtual root prefix (it will be stripped off the left hand side of the generated URL). .. note:: For backwards compatibility purposes, this method is also aliased as the ``model_url`` method of request. """ try: reg = self.registry except AttributeError: reg = get_current_registry() # b/c url_adapter = reg.queryMultiAdapter((resource, self), IResourceURL) if url_adapter is None: url_adapter = ResourceURL(resource, self) virtual_path = getattr(url_adapter, 'virtual_path', None) if virtual_path is None: # old-style IContextURL adapter (Pyramid 1.2 and previous) warnings.warn( 'Pyramid is using an IContextURL adapter to generate a ' 'resource URL; any "app_url", "host", "port", or "scheme" ' 'arguments passed to resource_url are being ignored. To ' 'avoid this behavior, as of Pyramid 1.3, register an ' 'IResourceURL adapter instead of an IContextURL ' 'adapter for the resource type(s). IContextURL adapters ' 'will be ignored in a later major release of Pyramid.', DeprecationWarning, 2) resource_url = url_adapter() else: # IResourceURL adapter (Pyramid 1.3 and after) app_url = None scheme = None host = None port = None if 'route_name' in kw: newkw = {} route_name = kw['route_name'] remainder = getattr(url_adapter, 'virtual_path_tuple', None) if remainder is None: # older user-supplied IResourceURL adapter without 1.5 # virtual_path_tuple remainder = tuple(url_adapter.virtual_path.split('/')) remainder_name = kw.get('route_remainder_name', 'traverse') newkw[remainder_name] = remainder for name in ( 'app_url', 'scheme', 'host', 'port', 'query', 'anchor' ): val = kw.get(name, None) if val is not None: newkw['_' + name] = val if 'route_kw' in kw: route_kw = kw.get('route_kw') if route_kw is not None: newkw.update(route_kw) return self.route_url(route_name, *elements, **newkw) if 'app_url' in kw: app_url = kw['app_url'] if 'scheme' in kw: scheme = kw['scheme'] if 'host' in kw: host = kw['host'] if 'port' in kw: port = kw['port'] if app_url is None: if scheme or host or port: app_url = self._partial_application_url(scheme, host, port) else: app_url = self.application_url resource_url = None local_url = getattr(resource, '__resource_url__', None) if local_url is not None: # the resource handles its own url generation d = dict( virtual_path = virtual_path, physical_path = url_adapter.physical_path, app_url = app_url, ) # allow __resource_url__ to punt by returning None resource_url = local_url(self, d) if resource_url is None: # the resource did not handle its own url generation or the # __resource_url__ function returned None resource_url = app_url + virtual_path qs = '' anchor = '' if 'query' in kw: query = kw['query'] if isinstance(query, string_types): qs = '?' + url_quote(query, QUERY_SAFE) elif query: qs = '?' + urlencode(query, doseq=True) if 'anchor' in kw: anchor = kw['anchor'] anchor = url_quote(anchor, ANCHOR_SAFE) anchor = '#' + anchor if elements: suffix = _join_elements(elements) else: suffix = '' return resource_url + suffix + qs + anchor
def route_url(self, route_name, *elements, **kw): """Generates a fully qualified URL for a named :app:`Pyramid` :term:`route configuration`. Use the route's ``name`` as the first positional argument. Additional positional arguments (``*elements``) are appended to the URL as path segments after it is generated. Use keyword arguments to supply values which match any dynamic path elements in the route definition. Raises a :exc:`KeyError` exception if the URL cannot be generated for any reason (not enough arguments, for example). For example, if you've defined a route named "foobar" with the path ``{foo}/{bar}/*traverse``:: request.route_url('foobar', foo='1') => <KeyError exception> request.route_url('foobar', foo='1', bar='2') => <KeyError exception> request.route_url('foobar', foo='1', bar='2', traverse=('a','b')) => http://e.com/1/2/a/b request.route_url('foobar', foo='1', bar='2', traverse='/a/b') => http://e.com/1/2/a/b Values replacing ``:segment`` arguments can be passed as strings or Unicode objects. They will be encoded to UTF-8 and URL-quoted before being placed into the generated URL. Values replacing ``*remainder`` arguments can be passed as strings *or* tuples of Unicode/string values. If a tuple is passed as a ``*remainder`` replacement value, its values are URL-quoted and encoded to UTF-8. The resulting strings are joined with slashes and rendered into the URL. If a string is passed as a ``*remainder`` replacement value, it is tacked on to the URL after being URL-quoted-except-for-embedded-slashes. If a keyword argument ``_query`` is present, it will be used to compose a query string that will be tacked on to the end of the URL. The value of ``_query`` must be a sequence of two-tuples *or* a data structure with an ``.items()`` method that returns a sequence of two-tuples (presumably a dictionary). This data structure will be turned into a query string per the documentation of :func:`pyramid.encode.urlencode` function. After the query data is turned into a query string, a leading ``?`` is prepended, and the resulting string is appended to the generated URL. .. note:: Python data structures that are passed as ``_query`` which are sequences or dictionaries are turned into a string under the same rules as when run through :func:`urllib.urlencode` with the ``doseq`` argument equal to ``True``. This means that sequences can be passed as values, and a k=v pair will be placed into the query string for each value. If a keyword argument ``_anchor`` is present, its string representation will be used as a named anchor in the generated URL (e.g. if ``_anchor`` is passed as ``foo`` and the route URL is ``http://example.com/route/url``, the resulting generated URL will be ``http://example.com/route/url#foo``). .. note:: If ``_anchor`` is passed as a string, it should be UTF-8 encoded. If ``_anchor`` is passed as a Unicode object, it will be converted to UTF-8 before being appended to the URL. The anchor value is not quoted in any way before being appended to the generated URL. If both ``_anchor`` and ``_query`` are specified, the anchor element will always follow the query element, e.g. ``http://example.com?foo=1#bar``. If any of the keyword arguments ``_scheme``, ``_host``, or ``_port`` is passed and is non-``None``, the provided value will replace the named portion in the generated URL. For example, if you pass ``_host='foo.com'``, and the URL that would have been generated without the host replacement is ``http://example.com/a``, the result will be ``https://foo.com/a``. Note that if ``_scheme`` is passed as ``https``, and ``_port`` is not passed, the ``_port`` value is assumed to have been passed as ``443``. Likewise, if ``_scheme`` is passed as ``http`` and ``_port`` is not passed, the ``_port`` value is assumed to have been passed as ``80``. To avoid this behavior, always explicitly pass ``_port`` whenever you pass ``_scheme``. If a keyword ``_app_url`` is present, it will be used as the protocol/hostname/port/leading path prefix of the generated URL. For example, using an ``_app_url`` of ``http://example.com:8080/foo`` would cause the URL ``http://example.com:8080/foo/fleeb/flub`` to be returned from this function if the expansion of the route pattern associated with the ``route_name`` expanded to ``/fleeb/flub``. If ``_app_url`` is not specified, the result of ``request.application_url`` will be used as the prefix (the default). If both ``_app_url`` and any of ``_scheme``, ``_host``, or ``_port`` are passed, ``_app_url`` takes precedence and any values passed for ``_scheme``, ``_host``, and ``_port`` will be ignored. This function raises a :exc:`KeyError` if the URL cannot be generated due to missing replacement names. Extra replacement names are ignored. If the route object which matches the ``route_name`` argument has a :term:`pregenerator`, the ``*elements`` and ``**kw`` arguments arguments passed to this function might be augmented or changed. """ try: reg = self.registry except AttributeError: reg = get_current_registry() # b/c mapper = reg.getUtility(IRoutesMapper) route = mapper.get_route(route_name) if route is None: raise KeyError('No such route named %s' % route_name) if route.pregenerator is not None: elements, kw = route.pregenerator(self, elements, kw) anchor = '' qs = '' app_url = None host = None scheme = None port = None if '_query' in kw: qs = '?' + urlencode(kw.pop('_query'), doseq=True) if '_anchor' in kw: anchor = kw.pop('_anchor') anchor = native_(anchor, 'utf-8') anchor = '#' + anchor if '_app_url' in kw: app_url = kw.pop('_app_url') if '_host' in kw: host = kw.pop('_host') if '_scheme' in kw: scheme = kw.pop('_scheme') if '_port' in kw: port = kw.pop('_port') if app_url is None: if (scheme is not None or host is not None or port is not None): app_url = self._partial_application_url(scheme, host, port) else: app_url = self.application_url path = route.generate(kw) # raises KeyError if generate fails if elements: suffix = _join_elements(elements) if not path.endswith('/'): suffix = '/' + suffix else: suffix = '' return app_url + path + suffix + qs + anchor
def resource_url(self, resource, *elements, **kw): """ Generate a string representing the absolute URL of the :term:`resource` object based on the ``wsgi.url_scheme``, ``HTTP_HOST`` or ``SERVER_NAME`` in the request, plus any ``SCRIPT_NAME``. The overall result of this method is always a UTF-8 encoded string. Examples:: request.resource_url(resource) => http://example.com/ request.resource_url(resource, 'a.html') => http://example.com/a.html request.resource_url(resource, 'a.html', query={'q':'1'}) => http://example.com/a.html?q=1 request.resource_url(resource, 'a.html', anchor='abc') => http://example.com/a.html#abc request.resource_url(resource, app_url='') => / Any positional arguments passed in as ``elements`` must be strings Unicode objects, or integer objects. These will be joined by slashes and appended to the generated resource URL. Each of the elements passed in is URL-quoted before being appended; if any element is Unicode, it will converted to a UTF-8 bytestring before being URL-quoted. If any element is an integer, it will be converted to its string representation before being URL-quoted. .. warning:: if no ``elements`` arguments are specified, the resource URL will end with a trailing slash. If any ``elements`` are used, the generated URL will *not* end in a trailing slash. If a keyword argument ``query`` is present, it will be used to compose a query string that will be tacked on to the end of the URL. The value of ``query`` may be a sequence of two-tuples *or* a data structure with an ``.items()`` method that returns a sequence of two-tuples (presumably a dictionary). This data structure will be turned into a query string per the documentation of :func:``pyramid.url.urlencode`` function. This will produce a query string in the ``x-www-form-urlencoded`` encoding. A non-``x-www-form-urlencoded`` query string may be used by passing a *string* value as ``query`` in which case it will be URL-quoted (e.g. query="foo bar" will become "foo%20bar"). However, the result will not need to be in ``k=v`` form as required by ``x-www-form-urlencoded``. After the query data is turned into a query string, a leading ``?`` is prepended, and the resulting string is appended to the generated URL. .. note:: Python data structures that are passed as ``query`` which are sequences or dictionaries are turned into a string under the same rules as when run through :func:`urllib.urlencode` with the ``doseq`` argument equal to ``True``. This means that sequences can be passed as values, and a k=v pair will be placed into the query string for each value. .. versionchanged:: 1.5 Allow the ``query`` option to be a string to enable alternative encodings. If a keyword argument ``anchor`` is present, its string representation will be used as a named anchor in the generated URL (e.g. if ``anchor`` is passed as ``foo`` and the resource URL is ``http://example.com/resource/url``, the resulting generated URL will be ``http://example.com/resource/url#foo``). .. note:: If ``anchor`` is passed as a string, it should be UTF-8 encoded. If ``anchor`` is passed as a Unicode object, it will be converted to UTF-8 before being appended to the URL. .. versionchanged:: 1.5 The ``anchor`` option will be escaped instead of using its raw string representation. If both ``anchor`` and ``query`` are specified, the anchor element will always follow the query element, e.g. ``http://example.com?foo=1#bar``. If any of the keyword arguments ``scheme``, ``host``, or ``port`` is passed and is non-``None``, the provided value will replace the named portion in the generated URL. For example, if you pass ``host='foo.com'``, and the URL that would have been generated without the host replacement is ``http://example.com/a``, the result will be ``http://foo.com/a``. If ``scheme`` is passed as ``https``, and an explicit ``port`` is not passed, the ``port`` value is assumed to have been passed as ``443``. Likewise, if ``scheme`` is passed as ``http`` and ``port`` is not passed, the ``port`` value is assumed to have been passed as ``80``. To avoid this behavior, always explicitly pass ``port`` whenever you pass ``scheme``. If a keyword argument ``app_url`` is passed and is not ``None``, it should be a string that will be used as the port/hostname/initial path portion of the generated URL instead of the default request application URL. For example, if ``app_url='http://foo'``, then the resulting url of a resource that has a path of ``/baz/bar`` will be ``http://foo/baz/bar``. If you want to generate completely relative URLs with no leading scheme, host, port, or initial path, you can pass ``app_url=''``. Passing ``app_url=''`` when the resource path is ``/baz/bar`` will return ``/baz/bar``. .. versionadded:: 1.3 ``app_url`` If ``app_url`` is passed and any of ``scheme``, ``port``, or ``host`` are also passed, ``app_url`` will take precedence and the values passed for ``scheme``, ``host``, and/or ``port`` will be ignored. If the ``resource`` passed in has a ``__resource_url__`` method, it will be used to generate the URL (scheme, host, port, path) for the base resource which is operated upon by this function. .. seealso:: See also :ref:`overriding_resource_url_generation`. .. versionadded:: 1.5 ``route_name``, ``route_kw``, and ``route_remainder_name`` If ``route_name`` is passed, this function will delegate its URL production to the ``route_url`` function. Calling ``resource_url(someresource, 'element1', 'element2', query={'a':1}, route_name='blogentry')`` is roughly equivalent to doing:: remainder_path = request.resource_path(someobject) url = request.route_url( 'blogentry', 'element1', 'element2', _query={'a':'1'}, traverse=traversal_path, ) It is only sensible to pass ``route_name`` if the route being named has a ``*remainder`` stararg value such as ``*traverse``. The remainder value will be ignored in the output otherwise. By default, the resource path value will be passed as the name ``traverse`` when ``route_url`` is called. You can influence this by passing a different ``route_remainder_name`` value if the route has a different ``*stararg`` value at its end. For example if the route pattern you want to replace has a ``*subpath`` stararg ala ``/foo*subpath``:: request.resource_url( resource, route_name='myroute', route_remainder_name='subpath' ) If ``route_name`` is passed, it is also permissible to pass ``route_kw``, which will passed as additional keyword arguments to ``route_url``. Saying ``resource_url(someresource, 'element1', 'element2', route_name='blogentry', route_kw={'id':'4'}, _query={'a':'1'})`` is roughly equivalent to:: remainder_path = request.resource_path_tuple(someobject) kw = {'id':'4', '_query':{'a':'1'}, 'traverse':traversal_path} url = request.route_url( 'blogentry', 'element1', 'element2', **kw, ) If ``route_kw`` or ``route_remainder_name`` is passed, but ``route_name`` is not passed, both ``route_kw`` and ``route_remainder_name`` will be ignored. If ``route_name`` is passed, the ``__resource_url__`` method of the resource passed is ignored unconditionally. This feature is incompatible with resources which generate their own URLs. .. note:: If the :term:`resource` used is the result of a :term:`traversal`, it must be :term:`location`-aware. The resource can also be the context of a :term:`URL dispatch`; contexts found this way do not need to be location-aware. .. note:: If a 'virtual root path' is present in the request environment (the value of the WSGI environ key ``HTTP_X_VHM_ROOT``), and the resource was obtained via :term:`traversal`, the URL path will not include the virtual root prefix (it will be stripped off the left hand side of the generated URL). .. note:: For backwards compatibility purposes, this method is also aliased as the ``model_url`` method of request. """ try: reg = self.registry except AttributeError: reg = get_current_registry() # b/c url_adapter = reg.queryMultiAdapter((resource, self), IResourceURL) if url_adapter is None: url_adapter = ResourceURL(resource, self) virtual_path = getattr(url_adapter, 'virtual_path', None) if virtual_path is None: # old-style IContextURL adapter (Pyramid 1.2 and previous) warnings.warn( 'Pyramid is using an IContextURL adapter to generate a ' 'resource URL; any "app_url", "host", "port", or "scheme" ' 'arguments passed to resource_url are being ignored. To ' 'avoid this behavior, as of Pyramid 1.3, register an ' 'IResourceURL adapter instead of an IContextURL ' 'adapter for the resource type(s). IContextURL adapters ' 'will be ignored in a later major release of Pyramid.', DeprecationWarning, 2) resource_url = url_adapter() else: # IResourceURL adapter (Pyramid 1.3 and after) app_url = None scheme = None host = None port = None if 'route_name' in kw: newkw = {} route_name = kw['route_name'] remainder = getattr(url_adapter, 'virtual_path_tuple', None) if remainder is None: # older user-supplied IResourceURL adapter without 1.5 # virtual_path_tuple remainder = tuple(url_adapter.virtual_path.split('/')) remainder_name = kw.get('route_remainder_name', 'traverse') newkw[remainder_name] = remainder for name in ('app_url', 'scheme', 'host', 'port', 'query', 'anchor'): val = kw.get(name, None) if val is not None: newkw['_' + name] = val if 'route_kw' in kw: route_kw = kw.get('route_kw') if route_kw is not None: newkw.update(route_kw) return self.route_url(route_name, *elements, **newkw) if 'app_url' in kw: app_url = kw['app_url'] if 'scheme' in kw: scheme = kw['scheme'] if 'host' in kw: host = kw['host'] if 'port' in kw: port = kw['port'] if app_url is None: if scheme or host or port: app_url = self._partial_application_url(scheme, host, port) else: app_url = self.application_url resource_url = None local_url = getattr(resource, '__resource_url__', None) if local_url is not None: # the resource handles its own url generation d = dict( virtual_path=virtual_path, physical_path=url_adapter.physical_path, app_url=app_url, ) # allow __resource_url__ to punt by returning None resource_url = local_url(self, d) if resource_url is None: # the resource did not handle its own url generation or the # __resource_url__ function returned None resource_url = app_url + virtual_path qs = '' anchor = '' if 'query' in kw: query = kw['query'] if isinstance(query, string_types): qs = '?' + url_quote(query, QUERY_SAFE) elif query: qs = '?' + urlencode(query, doseq=True) if 'anchor' in kw: anchor = kw['anchor'] anchor = url_quote(anchor, ANCHOR_SAFE) anchor = '#' + anchor if elements: suffix = _join_elements(elements) else: suffix = '' return resource_url + suffix + qs + anchor
def resource_url(self, resource, *elements, **kw): """ Generate a string representing the absolute URL of the :term:`resource` object based on the ``wsgi.url_scheme``, ``HTTP_HOST`` or ``SERVER_NAME`` in the request, plus any ``SCRIPT_NAME``. The overall result of this method is always a UTF-8 encoded string. Examples:: request.resource_url(resource) => http://example.com/ request.resource_url(resource, 'a.html') => http://example.com/a.html request.resource_url(resource, 'a.html', query={'q':'1'}) => http://example.com/a.html?q=1 request.resource_url(resource, 'a.html', anchor='abc') => http://example.com/a.html#abc request.resource_url(resource, app_url='') => / Any positional arguments passed in as ``elements`` must be strings Unicode objects, or integer objects. These will be joined by slashes and appended to the generated resource URL. Each of the elements passed in is URL-quoted before being appended; if any element is Unicode, it will converted to a UTF-8 bytestring before being URL-quoted. If any element is an integer, it will be converted to its string representation before being URL-quoted. .. warning:: if no ``elements`` arguments are specified, the resource URL will end with a trailing slash. If any ``elements`` are used, the generated URL will *not* end in trailing a slash. If a keyword argument ``query`` is present, it will be used to compose a query string that will be tacked on to the end of the URL. The value of ``query`` must be a sequence of two-tuples *or* a data structure with an ``.items()`` method that returns a sequence of two-tuples (presumably a dictionary). This data structure will be turned into a query string per the documentation of ``pyramid.url.urlencode`` function. After the query data is turned into a query string, a leading ``?`` is prepended, and the resulting string is appended to the generated URL. .. note:: Python data structures that are passed as ``query`` which are sequences or dictionaries are turned into a string under the same rules as when run through :func:`urllib.urlencode` with the ``doseq`` argument equal to ``True``. This means that sequences can be passed as values, and a k=v pair will be placed into the query string for each value. If a keyword argument ``anchor`` is present, its string representation will be used as a named anchor in the generated URL (e.g. if ``anchor`` is passed as ``foo`` and the resource URL is ``http://example.com/resource/url``, the resulting generated URL will be ``http://example.com/resource/url#foo``). .. note:: If ``anchor`` is passed as a string, it should be UTF-8 encoded. If ``anchor`` is passed as a Unicode object, it will be converted to UTF-8 before being appended to the URL. The anchor value is not quoted in any way before being appended to the generated URL. If both ``anchor`` and ``query`` are specified, the anchor element will always follow the query element, e.g. ``http://example.com?foo=1#bar``. If any of the keyword arguments ``scheme``, ``host``, or ``port`` is passed and is non-``None``, the provided value will replace the named portion in the generated URL. For example, if you pass ``host='foo.com'``, and the URL that would have been generated without the host replacement is ``http://example.com/a``, the result will be ``https://foo.com/a``. If ``scheme`` is passed as ``https``, and an explicit ``port`` is not passed, the ``port`` value is assumed to have been passed as ``443``. Likewise, if ``scheme`` is passed as ``http`` and ``port`` is not passed, the ``port`` value is assumed to have been passed as ``80``. To avoid this behavior, always explicitly pass ``port`` whenever you pass ``scheme``. If a keyword argument ``app_url`` is passed and is not ``None``, it should be a string that will be used as the port/hostname/initial path portion of the generated URL instead of the default request application URL. For example, if ``app_url='http://foo'``, then the resulting url of a resource that has a path of ``/baz/bar`` will be ``http://foo/baz/bar``. If you want to generate completely relative URLs with no leading scheme, host, port, or initial path, you can pass ``app_url=''`. Passing ``app_url=''` when the resource path is ``/baz/bar`` will return ``/baz/bar``. .. note:: ``app_url`` is new as of Pyramid 1.3. If ``app_url`` is passed and any of ``scheme``, ``port``, or ``host`` are also passed, ``app_url`` will take precedence and the values passed for ``scheme``, ``host``, and/or ``port`` will be ignored. If the ``resource`` passed in has a ``__resource_url__`` method, it will be used to generate the URL (scheme, host, port, path) that for the base resource which is operated upon by this function. See also :ref:`overriding_resource_url_generation`. .. note:: If the :term:`resource` used is the result of a :term:`traversal`, it must be :term:`location`-aware. The resource can also be the context of a :term:`URL dispatch`; contexts found this way do not need to be location-aware. .. note:: If a 'virtual root path' is present in the request environment (the value of the WSGI environ key ``HTTP_X_VHM_ROOT``), and the resource was obtained via :term:`traversal`, the URL path will not include the virtual root prefix (it will be stripped off the left hand side of the generated URL). .. note:: For backwards compatibility purposes, this method is also aliased as the ``model_url`` method of request. """ try: reg = self.registry except AttributeError: reg = get_current_registry() # b/c url_adapter = reg.queryMultiAdapter((resource, self), IResourceURL) if url_adapter is None: url_adapter = ResourceURL(resource, self) virtual_path = getattr(url_adapter, 'virtual_path', None) if virtual_path is None: # old-style IContextURL adapter (Pyramid 1.2 and previous) warnings.warn( 'Pyramid is using an IContextURL adapter to generate a ' 'resource URL; any "app_url", "host", "port", or "scheme" ' 'arguments passed to resource_url are being ignored. To ' 'avoid this behavior, as of Pyramid 1.3, register an ' 'IResourceURL adapter instead of an IContextURL ' 'adapter for the resource type(s). IContextURL adapters ' 'will be ignored in a later major release of Pyramid.', DeprecationWarning, 2) resource_url = url_adapter() else: # newer-style IResourceURL adapter (Pyramid 1.3 and after) app_url = None scheme = None host = None port = None if 'app_url' in kw: app_url = kw['app_url'] if 'scheme' in kw: scheme = kw['scheme'] if 'host' in kw: host = kw['host'] if 'port' in kw: port = kw['port'] if app_url is None: if scheme or host or port: app_url = self._partial_application_url(scheme, host, port) else: app_url = self.application_url resource_url = None local_url = getattr(resource, '__resource_url__', None) if local_url is not None: # the resource handles its own url generation d = dict( virtual_path = virtual_path, physical_path = url_adapter.physical_path, app_url = app_url, ) # allow __resource_url__ to punt by returning None resource_url = local_url(self, d) if resource_url is None: # the resource did not handle its own url generation or the # __resource_url__ function returned None resource_url = app_url + virtual_path qs = '' anchor = '' if 'query' in kw: query = kw['query'] if query: qs = '?' + urlencode(query, doseq=True) if 'anchor' in kw: anchor = kw['anchor'] if isinstance(anchor, text_type): anchor = native_(anchor, 'utf-8') anchor = '#' + anchor if elements: suffix = _join_elements(elements) else: suffix = '' return resource_url + suffix + qs + anchor
def route_url(self, route_name, *elements, **kw): """Generates a fully qualified URL for a named :app:`Pyramid` :term:`route configuration`. Use the route's ``name`` as the first positional argument. Additional positional arguments (``*elements``) are appended to the URL as path segments after it is generated. Use keyword arguments to supply values which match any dynamic path elements in the route definition. Raises a :exc:`KeyError` exception if the URL cannot be generated for any reason (not enough arguments, for example). For example, if you've defined a route named "foobar" with the path ``{foo}/{bar}/*traverse``:: request.route_url('foobar', foo='1') => <KeyError exception> request.route_url('foobar', foo='1', bar='2') => <KeyError exception> request.route_url('foobar', foo='1', bar='2', traverse=('a','b')) => http://e.com/1/2/a/b request.route_url('foobar', foo='1', bar='2', traverse='/a/b') => http://e.com/1/2/a/b Values replacing ``:segment`` arguments can be passed as strings or Unicode objects. They will be encoded to UTF-8 and URL-quoted before being placed into the generated URL. Values replacing ``*remainder`` arguments can be passed as strings *or* tuples of Unicode/string values. If a tuple is passed as a ``*remainder`` replacement value, its values are URL-quoted and encoded to UTF-8. The resulting strings are joined with slashes and rendered into the URL. If a string is passed as a ``*remainder`` replacement value, it is tacked on to the URL after being URL-quoted-except-for-embedded-slashes. If a keyword argument ``_query`` is present, it will be used to compose a query string that will be tacked on to the end of the URL. The value of ``_query`` must be a sequence of two-tuples *or* a data structure with an ``.items()`` method that returns a sequence of two-tuples (presumably a dictionary). This data structure will be turned into a query string per the documentation of :func:`pyramid.encode.urlencode` function. After the query data is turned into a query string, a leading ``?`` is prepended, and the resulting string is appended to the generated URL. .. note:: Python data structures that are passed as ``_query`` which are sequences or dictionaries are turned into a string under the same rules as when run through :func:`urllib.urlencode` with the ``doseq`` argument equal to ``True``. This means that sequences can be passed as values, and a k=v pair will be placed into the query string for each value. If a keyword argument ``_anchor`` is present, its string representation will be used as a named anchor in the generated URL (e.g. if ``_anchor`` is passed as ``foo`` and the route URL is ``http://example.com/route/url``, the resulting generated URL will be ``http://example.com/route/url#foo``). .. note:: If ``_anchor`` is passed as a string, it should be UTF-8 encoded. If ``_anchor`` is passed as a Unicode object, it will be converted to UTF-8 before being appended to the URL. The anchor value is not quoted in any way before being appended to the generated URL. If both ``_anchor`` and ``_query`` are specified, the anchor element will always follow the query element, e.g. ``http://example.com?foo=1#bar``. If any of the keyword arguments ``_scheme``, ``_host``, or ``_port`` is passed and is non-``None``, the provided value will replace the named portion in the generated URL. For example, if you pass ``_host='foo.com'``, and the URL that would have been generated without the host replacement is ``http://example.com/a``, the result will be ``https://foo.com/a``. Note that if ``_scheme`` is passed as ``https``, and ``_port`` is not passed, the ``_port`` value is assumed to have been passed as ``443``. Likewise, if ``_scheme`` is passed as ``http`` and ``_port`` is not passed, the ``_port`` value is assumed to have been passed as ``80``. To avoid this behavior, always explicitly pass ``_port`` whenever you pass ``_scheme``. If a keyword ``_app_url`` is present, it will be used as the protocol/hostname/port/leading path prefix of the generated URL. For example, using an ``_app_url`` of ``http://example.com:8080/foo`` would cause the URL ``http://example.com:8080/foo/fleeb/flub`` to be returned from this function if the expansion of the route pattern associated with the ``route_name`` expanded to ``/fleeb/flub``. If ``_app_url`` is not specified, the result of ``request.application_url`` will be used as the prefix (the default). If both ``_app_url`` and any of ``_scheme``, ``_host``, or ``_port`` are passed, ``_app_url`` takes precedence and any values passed for ``_scheme``, ``_host``, and ``_port`` will be ignored. This function raises a :exc:`KeyError` if the URL cannot be generated due to missing replacement names. Extra replacement names are ignored. If the route object which matches the ``route_name`` argument has a :term:`pregenerator`, the ``*elements`` and ``**kw`` arguments passed to this function might be augmented or changed. """ try: reg = self.registry except AttributeError: reg = get_current_registry() # b/c mapper = reg.getUtility(IRoutesMapper) route = mapper.get_route(route_name) if route is None: raise KeyError('No such route named %s' % route_name) if route.pregenerator is not None: elements, kw = route.pregenerator(self, elements, kw) anchor = '' qs = '' app_url = None host = None scheme = None port = None if '_query' in kw: query = kw.pop('_query') if query: qs = '?' + urlencode(query, doseq=True) if '_anchor' in kw: anchor = kw.pop('_anchor') anchor = native_(anchor, 'utf-8') anchor = '#' + anchor if '_app_url' in kw: app_url = kw.pop('_app_url') if '_host' in kw: host = kw.pop('_host') if '_scheme' in kw: scheme = kw.pop('_scheme') if '_port' in kw: port = kw.pop('_port') if app_url is None: if (scheme is not None or host is not None or port is not None): app_url = self._partial_application_url(scheme, host, port) else: app_url = self.application_url path = route.generate(kw) # raises KeyError if generate fails if elements: suffix = _join_elements(elements) if not path.endswith('/'): suffix = '/' + suffix else: suffix = '' return app_url + path + suffix + qs + anchor