def route_url(self, *args, **kw): url = super(self.__class__, self).route_url(*args, **kw) # Unquote plus signs in path segment. The settings in pyramid for # the urllib quoting function are a bit too much on the safe side url = urlparse.urlparse(url) url = url._replace(path=url.path.replace('%2B', '+')) return url.geturl()
def url_to_resource(self, url): """ Returns the resource that is addressed by the given URL. :param str url: URL to convert :return: member or collection resource :note: If the query string in the URL has multiple values for a query parameter, the last definition in the query string wins. """ parsed = urlparse.urlparse(url) parsed_path = parsed.path # namedtupble problem pylint: disable=E1101 rc = find_resource(self.__request.root, traversal_path(parsed_path)) if ICollectionResource in provided_by(rc): # In case we found a collection, we have to filter, order, slice. parsed_query = parsed.query # namedtuple problem pylint: disable=E1101 params = dict(parse_qsl(parsed_query)) filter_string = params.get('q') if not filter_string is None: rc.filter = \ UrlPartsConverter.make_filter_specification(filter_string) order_string = params.get('sort') if not order_string is None: rc.order = \ UrlPartsConverter.make_order_specification(order_string) start_string = params.get('start') size_string = params.get('size') if not (start_string is None or size_string is None): rc.slice = \ UrlPartsConverter.make_slice_key(start_string, size_string) elif not IMemberResource in provided_by(rc): raise ValueError('Traversal found non-resource object "%s".' % rc) return rc
def get_resource_url(resource): """ Returns the URL for the given resource. """ path = model_path(resource) parsed = list(urlparse.urlparse(path)) parsed[1] = "" return urlparse.urlunparse(parsed)
def is_resource_url(url_string): """ Checks if the given URL string is a resource URL. Currently, this check only looks if the URL scheme is either "http" or "https". """ return isinstance(url_string, string_types) \ and urlparse.urlparse(url_string).scheme in ('http', 'https') # pylint: disable=E1101
def route_url(self, *args, **kw): xom = self.registry['xom'] outside_url = get_outside_url(self, xom.config.args.outside_url) url = super(self.__class__, self).route_url( _app_url=outside_url, *args, **kw) # Unquote plus signs in path segment. The settings in pyramid for # the urllib quoting function are a bit too much on the safe side url = urlparse.urlparse(url) url = url._replace(path=url.path.replace('%2B', '+')) return url.geturl()
def route_url(self, *args, **kw): xom = self.registry['xom'] outside_url = get_outside_url(self, xom.config.args.outside_url) url = super(self.__class__, self).route_url(_app_url=outside_url, *args, **kw) # Unquote plus signs in path segment. The settings in pyramid for # the urllib quoting function are a bit too much on the safe side url = urlparse.urlparse(url) url = url._replace(path=url.path.replace('%2B', '+')) return url.geturl()
def __call__(self, node, value): try: parsed_url = urlparse.urlparse(value) except Exception: raise colander.Invalid(node, "Invalid URL.") else: if parsed_url.scheme not in self.allowed_schemes: raise colander.Invalid(node, "URL scheme {} is not allowed.".format(parsed_url.scheme)) if not parsed_url.netloc: raise colander.Invalid(node, "Invalid URL.") if '..' in parsed_url.path: raise colander.Invalid(node, "Invalid URL.")
def __call__(self, environ, start_response): outside_url = self.xom.config.args.outside_url if not outside_url: outside_url = environ.get('HTTP_X_OUTSIDE_URL') if outside_url: # XXX memoize it for later access from replica thread # self.xom.current_outside_url = outside_url outside_url = urlparse.urlparse(outside_url) environ['wsgi.url_scheme'] = outside_url.scheme environ['HTTP_HOST'] = outside_url.netloc if outside_url.path: environ['SCRIPT_NAME'] = outside_url.path return self.app(environ, start_response)
def __check_url(self, url, schema=None, path=None, params=None, query=None): urlp = urlparse.urlparse(url) if not schema is None: assert urlp.scheme == schema # pylint: disable=E1101 if not path is None: assert urlp.path == path # pylint: disable=E1101 if not params is None: assert urlp.params == params # pylint: disable=E1101 if not query is None: # We can not rely on the order of query parameters returned by # urlparse, so we compare the sets of parameters. assert set(urlp.query.split('&')) == \ set(query.split('&')) # pylint: disable=E1101
def load_into_collection_from_url(collection, url, content_type=None): """ Loads resources from the representation contained in the given URL into the given collection resource. :returns: collection resource """ parsed = urlparse.urlparse(url) scheme = parsed.scheme # pylint: disable=E1101 if scheme == 'file': # Assume a local path. load_into_collection_from_file(collection, parsed.path, # pylint: disable=E1101 content_type=content_type) else: raise ValueError('Unsupported URL scheme "%s".' % scheme)
def setstandin(request, allowed_users=None): """Setting members in the default usergroup of the current user. Technically this is adding a standin for this user.""" # Check authentification # As this view has now security configured it is # generally callable by all users. For this reason we first check if # the user is authenticated. If the user is not authenticated the # raise an 401 (unauthorized) exception. if not request.user: raise HTTPUnauthorized # Check authorisation # For normal users users shall only be allowed to set the standin # for their own usergroup. So check this and otherwise raise an exception. usergroup = get_item_from_request(request) if (usergroup.id != request.user.default_gid and not has_permission("update", usergroup, request)): raise HTTPForbidden() clazz = Usergroup request.session['%s.form' % clazz] = "membersonly" request.session.save() values = {} if allowed_users: values['_allowedusers'] = [u.login for u in allowed_users] # Result may be a HTTPFOUND object. result = update(request, values=values) if isinstance(result, dict): # If the standing is set by an administrational user then the id # of the usergroup´s user is stored in the the backurl. if request.GET.get('backurl'): user_id = urlparse.urlparse( request.GET.get('backurl')).path.split('/')[-1] user = request.db.query(User).get(user_id) if not user: raise HTTPBadRequest() # Otherwise the user sets the standin of his own group. In this # case the user is already in the request. else: user = request.user result['user'] = user # Reset form value in session handle_caching(request) return result
def load_into_collection_from_url(collection, url, content_type=None): """ Loads resources from the representation contained in the given URL into the given collection resource. :returns: collection resource """ parsed = urlparse.urlparse(url) scheme = parsed.scheme # pylint: disable=E1101 if scheme == 'file': # Assume a local path. load_into_collection_from_file( collection, parsed.path, # pylint: disable=E1101 content_type=content_type) else: raise ValueError('Unsupported URL scheme "%s".' % scheme)
def setstandin(request, allowed_users=None): """Setting members in the default usergroup of the current user. Technically this is adding a standin for this user.""" # Check authentification # As this view has now security configured it is # generally callable by all users. For this reason we first check if # the user is authenticated. If the user is not authenticated the # raise an 401 (unauthorized) exception. if not request.user: raise HTTPUnauthorized # Check authorisation # For normal users users shall only be allowed to set the standin # for their own usergroup. So check this and otherwise raise an exception. usergroup = get_item_from_request(request) if (usergroup.id != request.user.default_gid and not has_permission("update", usergroup, request)): raise HTTPForbidden() clazz = Usergroup request.session['%s.form' % clazz] = "membersonly" request.session['%s.backurl' % clazz] = request.current_route_path() request.session.save() values = {} if allowed_users: values['_allowedusers'] = [u.login for u in allowed_users] # Result may be a HTTPFOUND object. result = update(request, values=values) if isinstance(result, dict): # If the standing is set by an administrational user then the id # of the usergroup´s user is stored in the the backurl. if request.GET.get('backurl'): user_id = urlparse.urlparse( request.GET.get('backurl')).path.split('/')[-1] user = request.db.query(User).filter(User.id == user_id).one() # Otherwise the user sets the standin of his own group. In this # case the user is already in the request. else: user = request.user result['user'] = user # Reset form value in session handle_caching(request) return result
def to_escaped_host_path(url): r"""Take the netloc of a url and escape it:: >>> url = 'http://www.cwi.nl:80/%7Eguido/Python.html' >>> to_escaped_host_path(url) 'www\\.cwi\\.nl\\:80\\/\\%7Eguido\\/Python\\.html' Strips off any query string:: >>> url = 'http://localhost:5100/?foo=bar' >>> to_escaped_host_path(url) 'localhost\\:5100\\/' Works for urls that are actually just hosts:: >>> url = 'google.com/foo' >>> to_escaped_host_path(url) 'google\\.com\\/foo' """ o = urlparse.urlparse(url) return re.escape(o.netloc) + re.escape(o.path)
def includeme(cfg): from pyramid.settings import asbool, aslist from pyramid.interfaces import IStaticURLInfo from pyramid.compat import urlparse from pyramid_amdjs import amd from pyramid_amdjs.pstatic import StaticURLInfo # amdjs tween cfg.add_tween('pyramid_amdjs.require.amdjs_tween_factory') def get_amdjs_data(request): return {'js': [], 'css': [], 'spec': '', 'fn': [], 'init': False} cfg.add_request_method(get_amdjs_data, 'amdjs_data', True, True) # static cfg.registry.registerUtility(StaticURLInfo(), IStaticURLInfo) # settings settings = cfg.get_settings() settings['amd.debug'] = asbool(settings.get('amd.debug', 't')) settings['amd.enabled'] = asbool(settings.get('amd.enabled', 't')) settings['amd.spec-dir'] = settings.get('amd.spec-dir', '').strip() settings['amd.tmpl-cache'] = settings.get('amd.tmpl-cache', '').strip() settings['amd.tmpl-langs'] = [ s.strip() for s in aslist(settings.get('amd.tmpl-langs', ''))] settings['amd.node'] = settings.get('amd.node', '').strip() settings['static.url'] = settings.get('static.url', '').strip() settings['static.rewrite'] = asbool(settings.get('static.rewrite', 'f')) if not urlparse.urlparse(settings['static.url'])[0]: settings['static.rewrite'] = False else: if not settings['static.url'].endswith('/'): settings['static.url'] = '%s/' % settings['static.url'] # spec settings specs = [] for key, val in sorted(settings.items()): if key.startswith('amd.spec.'): specs.append((key[9:].strip(), val.strip())) settings['amd.spec'] = specs cfg.registry[amd.ID_AMD_SPEC] = {} # request methods cfg.add_request_method(amd.request_amd_init, 'init_amd') cfg.add_request_method(amd.request_includes, 'include_js') cfg.add_request_method(amd.request_css_includes, 'include_css') cfg.add_request_method(require.require_js, 'require') cfg.add_request_method(require.require_js, 'require_js') cfg.add_request_method(require.require_fn, 'require_fn') cfg.add_request_method(require.require_css, 'require_css') cfg.add_request_method(require.require_spec, 'require_spec') # config directives cfg.add_directive('add_amd_js', amd.add_js_module) cfg.add_directive('add_amd_css', amd.add_css_module) if settings['amd.debug']: from pyramid_amdjs import amddebug settings['amd.debug.data'] = { 'paths': [], 'cache': {}, 'mods': {}} cfg.registry[amd.ID_AMD_BUILD] = amddebug.build_init cfg.registry[amd.ID_AMD_BUILD_MD5] = amddebug.build_md5 cfg.add_directive('add_amd_dir', amddebug.add_amd_dir) else: cfg.registry[amd.ID_AMD_BUILD] = amd.build_init cfg.registry[amd.ID_AMD_BUILD_MD5] = amd.build_md5 cfg.add_directive('add_amd_dir', amd.add_amd_dir) cfg.registry[amd.ID_AMD_MD5] = {} # amd init route cfg.add_route('pyramid-amd-init', '/_amd_{specname}.js') # static assets cfg.add_static_view('_amdjs/static', 'pyramid_amdjs:static/') # handlebars bundle from .handlebars import register_handlebars_bundle cfg.add_directive( 'add_hb_bundle', register_handlebars_bundle) cfg.add_directive( 'add_handlebars_bundle', register_handlebars_bundle) cfg.add_route( 'pyramid-hb-bundle', '/_handlebars/{name}.js') # less bundle from .less import register_less_bundle, less_bundle_url cfg.add_directive( 'add_less_bundle', register_less_bundle) cfg.add_route( 'pyramid-less-bundle', '/_amd_less/{name}') cfg.add_request_method(less_bundle_url, 'less_bundle_url') # scan cfg.scan('pyramid_amdjs') cfg.include('pyramid_amdjs.static') # init amd specs amd.init_amd_spec(cfg)
def add_route(self, name, pattern=None, view=None, view_for=None, permission=None, factory=None, for_=None, header=None, xhr=None, accept=None, path_info=None, request_method=None, request_param=None, traverse=None, custom_predicates=(), view_permission=None, renderer=None, view_renderer=None, view_context=None, view_attr=None, use_global_views=False, path=None, pregenerator=None, static=False, **predicates): """ Add a :term:`route configuration` to the current configuration state, as well as possibly a :term:`view configuration` to be used to specify a :term:`view callable` that will be invoked when this route matches. The arguments to this method are divided into *predicate*, *non-predicate*, and *view-related* types. :term:`Route predicate` arguments narrow the circumstances in which a route will be match a request; non-predicate arguments are informational. Non-Predicate Arguments name The name of the route, e.g. ``myroute``. This attribute is required. It must be unique among all defined routes in a given application. factory A Python object (often a function or a class) or a :term:`dotted Python name` which refers to the same object that will generate a :app:`Pyramid` root resource object when this route matches. For example, ``mypackage.resources.MyFactory``. If this argument is not specified, a default root factory will be used. See :ref:`the_resource_tree` for more information about root factories. traverse If you would like to cause the :term:`context` to be something other than the :term:`root` object when this route matches, you can spell a traversal pattern as the ``traverse`` argument. This traversal pattern will be used as the traversal path: traversal will begin at the root object implied by this route (either the global root, or the object returned by the ``factory`` associated with this route). The syntax of the ``traverse`` argument is the same as it is for ``pattern``. For example, if the ``pattern`` provided to ``add_route`` is ``articles/{article}/edit``, and the ``traverse`` argument provided to ``add_route`` is ``/{article}``, when a request comes in that causes the route to match in such a way that the ``article`` match value is ``'1'`` (when the request URI is ``/articles/1/edit``), the traversal path will be generated as ``/1``. This means that the root object's ``__getitem__`` will be called with the name ``'1'`` during the traversal phase. If the ``'1'`` object exists, it will become the :term:`context` of the request. :ref:`traversal_chapter` has more information about traversal. If the traversal path contains segment marker names which are not present in the ``pattern`` argument, a runtime error will occur. The ``traverse`` pattern should not contain segment markers that do not exist in the ``pattern`` argument. A similar combining of routing and traversal is available when a route is matched which contains a ``*traverse`` remainder marker in its pattern (see :ref:`using_traverse_in_a_route_pattern`). The ``traverse`` argument to add_route allows you to associate route patterns with an arbitrary traversal path without using a ``*traverse`` remainder marker; instead you can use other match information. Note that the ``traverse`` argument to ``add_route`` is ignored when attached to a route that has a ``*traverse`` remainder marker in its pattern. pregenerator This option should be a callable object that implements the :class:`pyramid.interfaces.IRoutePregenerator` interface. A :term:`pregenerator` is a callable called by the :meth:`pyramid.request.Request.route_url` function to augment or replace the arguments it is passed when generating a URL for the route. This is a feature not often used directly by applications, it is meant to be hooked by frameworks that use :app:`Pyramid` as a base. use_global_views When a request matches this route, and view lookup cannot find a view which has a ``route_name`` predicate argument that matches the route, try to fall back to using a view that otherwise matches the context, request, and view name (but which does not match the route_name predicate). static If ``static`` is ``True``, this route will never match an incoming request; it will only be useful for URL generation. By default, ``static`` is ``False``. See :ref:`static_route_narr`. .. versionadded:: 1.1 Predicate Arguments pattern The pattern of the route e.g. ``ideas/{idea}``. This argument is required. See :ref:`route_pattern_syntax` for information about the syntax of route patterns. If the pattern doesn't match the current URL, route matching continues. .. note:: For backwards compatibility purposes (as of :app:`Pyramid` 1.0), a ``path`` keyword argument passed to this function will be used to represent the pattern value if the ``pattern`` argument is ``None``. If both ``path`` and ``pattern`` are passed, ``pattern`` wins. xhr This value should be either ``True`` or ``False``. If this value is specified and is ``True``, the :term:`request` must possess an ``HTTP_X_REQUESTED_WITH`` (aka ``X-Requested-With``) header for this route to match. This is useful for detecting AJAX requests issued from jQuery, Prototype and other Javascript libraries. If this predicate returns ``False``, route matching continues. request_method A string representing an HTTP method name, e.g. ``GET``, ``POST``, ``HEAD``, ``DELETE``, ``PUT`` or a tuple of elements containing HTTP method names. If this argument is not specified, this route will match if the request has *any* request method. If this predicate returns ``False``, route matching continues. .. versionchanged:: 1.2 The ability to pass a tuple of items as ``request_method``. Previous versions allowed only a string. path_info This value represents a regular expression pattern that will be tested against the ``PATH_INFO`` WSGI environment variable. If the regex matches, this predicate will return ``True``. If this predicate returns ``False``, route matching continues. request_param This value can be any string. A view declaration with this argument ensures that the associated route will only match when the request has a key in the ``request.params`` dictionary (an HTTP ``GET`` or ``POST`` variable) that has a name which matches the supplied value. If the value supplied as the argument has a ``=`` sign in it, e.g. ``request_param="foo=123"``, then the key (``foo``) must both exist in the ``request.params`` dictionary, and the value must match the right hand side of the expression (``123``) for the route to "match" the current request. If this predicate returns ``False``, route matching continues. header This argument represents an HTTP header name or a header name/value pair. If the argument contains a ``:`` (colon), it will be considered a name/value pair (e.g. ``User-Agent:Mozilla/.*`` or ``Host:localhost``). If the value contains a colon, the value portion should be a regular expression. If the value does not contain a colon, the entire value will be considered to be the header name (e.g. ``If-Modified-Since``). If the value evaluates to a header name only without a value, the header specified by the name must be present in the request for this predicate to be true. If the value evaluates to a header name/value pair, the header specified by the name must be present in the request *and* the regular expression specified as the value must match the header value. Whether or not the value represents a header name or a header name/value pair, the case of the header name is not significant. If this predicate returns ``False``, route matching continues. accept This value represents a match query for one or more mimetypes in the ``Accept`` HTTP request header. If this value is specified, it must be in one of the following forms: a mimetype match token in the form ``text/plain``, a wildcard mimetype match token in the form ``text/*`` or a match-all wildcard mimetype match token in the form ``*/*``. If any of the forms matches the ``Accept`` header of the request, or if the ``Accept`` header isn't set at all in the request, this predicate will be true. If this predicate returns ``False``, route matching continues. effective_principals If specified, this value should be a :term:`principal` identifier or a sequence of principal identifiers. If the :func:`pyramid.security.effective_principals` method indicates that every principal named in the argument list is present in the current request, this predicate will return True; otherwise it will return False. For example: ``effective_principals=pyramid.security.Authenticated`` or ``effective_principals=('fred', 'group:admins')``. .. versionadded:: 1.4a4 custom_predicates This value should be a sequence of references to custom predicate callables. Use custom predicates when no set of predefined predicates does what you need. Custom predicates can be combined with predefined predicates as necessary. Each custom predicate callable should accept two arguments: ``info`` and ``request`` and should return either ``True`` or ``False`` after doing arbitrary evaluation of the info and/or the request. If all custom and non-custom predicate callables return ``True`` the associated route will be considered viable for a given request. If any predicate callable returns ``False``, route matching continues. Note that the value ``info`` passed to a custom route predicate is a dictionary containing matching information; see :ref:`custom_route_predicates` for more information about ``info``. predicates Pass a key/value pair here to use a third-party predicate registered via :meth:`pyramid.config.Configurator.add_view_predicate`. More than one key/value pair can be used at the same time. See :ref:`view_and_route_predicates` for more information about third-party predicates. .. versionadded:: 1.4 View-Related Arguments .. warning:: The arguments described below have been deprecated as of :app:`Pyramid` 1.1. *Do not use these for new development; they should only be used to support older code bases which depend upon them.* Use a separate call to :meth:`pyramid.config.Configurator.add_view` to associate a view with a route using the ``route_name`` argument. view .. deprecated:: 1.1 A Python object or :term:`dotted Python name` to the same object that will be used as a view callable when this route matches. e.g. ``mypackage.views.my_view``. view_context .. deprecated:: 1.1 A class or an :term:`interface` or :term:`dotted Python name` to the same object which the :term:`context` of the view should match for the view named by the route to be used. This argument is only useful if the ``view`` attribute is used. If this attribute is not specified, the default (``None``) will be used. If the ``view`` argument is not provided, this argument has no effect. This attribute can also be spelled as ``for_`` or ``view_for``. view_permission .. deprecated:: 1.1 The permission name required to invoke the view associated with this route. e.g. ``edit``. (see :ref:`using_security_with_urldispatch` for more information about permissions). If the ``view`` attribute is not provided, this argument has no effect. This argument can also be spelled as ``permission``. view_renderer .. deprecated:: 1.1 This is either a single string term (e.g. ``json``) or a string implying a path or :term:`asset specification` (e.g. ``templates/views.pt``). If the renderer value is a single term (does not contain a dot ``.``), the specified term will be used to look up a renderer implementation, and that renderer implementation will be used to construct a response from the view return value. If the renderer term contains a dot (``.``), the specified term will be treated as a path, and the filename extension of the last element in the path will be used to look up the renderer implementation, which will be passed the full path. The renderer implementation will be used to construct a response from the view return value. See :ref:`views_which_use_a_renderer` for more information. If the ``view`` argument is not provided, this argument has no effect. This argument can also be spelled as ``renderer``. view_attr .. deprecated:: 1.1 The view machinery defaults to using the ``__call__`` method of the view callable (or the function itself, if the view callable is a function) to obtain a response dictionary. The ``attr`` value allows you to vary the method attribute used to obtain the response. For example, if your view was a class, and the class has a method named ``index`` and you wanted to use this method instead of the class' ``__call__`` method to return the response, you'd say ``attr="index"`` in the view configuration for the view. This is most useful when the view definition is a class. If the ``view`` argument is not provided, this argument has no effect. """ # these are route predicates; if they do not match, the next route # in the routelist will be tried if request_method is not None: request_method = as_sorted_tuple(request_method) factory = self.maybe_dotted(factory) if pattern is None: pattern = path if pattern is None: raise ConfigurationError('"pattern" argument may not be None') # check for an external route; an external route is one which is # is a full url (e.g. 'http://example.com/{id}') parsed = urlparse.urlparse(pattern) if parsed.hostname: pattern = parsed.path original_pregenerator = pregenerator def external_url_pregenerator(request, elements, kw): if '_app_url' in kw: raise ValueError( 'You cannot generate a path to an external route ' 'pattern via request.route_path nor pass an _app_url ' 'to request.route_url when generating a URL for an ' 'external route pattern (pattern was "%s") ' % (pattern,) ) if '_scheme' in kw: scheme = kw['_scheme'] elif parsed.scheme: scheme = parsed.scheme else: scheme = request.scheme kw['_app_url'] = '{0}://{1}'.format(scheme, parsed.netloc) if original_pregenerator: elements, kw = original_pregenerator( request, elements, kw) return elements, kw pregenerator = external_url_pregenerator static = True elif self.route_prefix: pattern = self.route_prefix.rstrip('/') + '/' + pattern.lstrip('/') mapper = self.get_routes_mapper() introspectables = [] intr = self.introspectable('routes', name, '%s (pattern: %r)' % (name, pattern), 'route') intr['name'] = name intr['pattern'] = pattern intr['factory'] = factory intr['xhr'] = xhr intr['request_methods'] = request_method intr['path_info'] = path_info intr['request_param'] = request_param intr['header'] = header intr['accept'] = accept intr['traverse'] = traverse intr['custom_predicates'] = custom_predicates intr['pregenerator'] = pregenerator intr['static'] = static intr['use_global_views'] = use_global_views introspectables.append(intr) if factory: factory_intr = self.introspectable('root factories', name, self.object_description(factory), 'root factory') factory_intr['factory'] = factory factory_intr['route_name'] = name factory_intr.relate('routes', name) introspectables.append(factory_intr) def register_route_request_iface(): request_iface = self.registry.queryUtility(IRouteRequest, name=name) if request_iface is None: if use_global_views: bases = (IRequest,) else: bases = () request_iface = route_request_iface(name, bases) self.registry.registerUtility( request_iface, IRouteRequest, name=name) def register_connect(): pvals = predicates.copy() pvals.update( dict( xhr=xhr, request_method=request_method, path_info=path_info, request_param=request_param, header=header, accept=accept, traverse=traverse, custom=predvalseq(custom_predicates), ) ) predlist = self.get_predlist('route') _, preds, _ = predlist.make(self, **pvals) route = mapper.connect( name, pattern, factory, predicates=preds, pregenerator=pregenerator, static=static ) intr['object'] = route return route # We have to connect routes in the order they were provided; # we can't use a phase to do that, because when the actions are # sorted, actions in the same phase lose relative ordering self.action(('route-connect', name), register_connect) # But IRouteRequest interfaces must be registered before we begin to # process view registrations (in phase 3) self.action(('route', name), register_route_request_iface, order=PHASE2_CONFIG, introspectables=introspectables) # deprecated adding views from add_route; must come after # route registration for purposes of autocommit ordering if any([view, view_context, view_permission, view_renderer, view_for, for_, permission, renderer, view_attr]): self._add_view_from_route( route_name=name, view=view, permission=view_permission or permission, context=view_context or view_for or for_, renderer=view_renderer or renderer, attr=view_attr, )
def add_route( self, name, pattern=None, factory=None, for_=None, header=None, xhr=None, accept=None, path_info=None, request_method=None, request_param=None, traverse=None, custom_predicates=(), use_global_views=False, path=None, pregenerator=None, static=False, **predicates ): """ Add a :term:`route configuration` to the current configuration state, as well as possibly a :term:`view configuration` to be used to specify a :term:`view callable` that will be invoked when this route matches. The arguments to this method are divided into *predicate*, *non-predicate*, and *view-related* types. :term:`Route predicate` arguments narrow the circumstances in which a route will be match a request; non-predicate arguments are informational. Non-Predicate Arguments name The name of the route, e.g. ``myroute``. This attribute is required. It must be unique among all defined routes in a given application. factory A Python object (often a function or a class) or a :term:`dotted Python name` which refers to the same object that will generate a :app:`Pyramid` root resource object when this route matches. For example, ``mypackage.resources.MyFactory``. If this argument is not specified, a default root factory will be used. See :ref:`the_resource_tree` for more information about root factories. traverse If you would like to cause the :term:`context` to be something other than the :term:`root` object when this route matches, you can spell a traversal pattern as the ``traverse`` argument. This traversal pattern will be used as the traversal path: traversal will begin at the root object implied by this route (either the global root, or the object returned by the ``factory`` associated with this route). The syntax of the ``traverse`` argument is the same as it is for ``pattern``. For example, if the ``pattern`` provided to ``add_route`` is ``articles/{article}/edit``, and the ``traverse`` argument provided to ``add_route`` is ``/{article}``, when a request comes in that causes the route to match in such a way that the ``article`` match value is ``'1'`` (when the request URI is ``/articles/1/edit``), the traversal path will be generated as ``/1``. This means that the root object's ``__getitem__`` will be called with the name ``'1'`` during the traversal phase. If the ``'1'`` object exists, it will become the :term:`context` of the request. :ref:`traversal_chapter` has more information about traversal. If the traversal path contains segment marker names which are not present in the ``pattern`` argument, a runtime error will occur. The ``traverse`` pattern should not contain segment markers that do not exist in the ``pattern`` argument. A similar combining of routing and traversal is available when a route is matched which contains a ``*traverse`` remainder marker in its pattern (see :ref:`using_traverse_in_a_route_pattern`). The ``traverse`` argument to add_route allows you to associate route patterns with an arbitrary traversal path without using a ``*traverse`` remainder marker; instead you can use other match information. Note that the ``traverse`` argument to ``add_route`` is ignored when attached to a route that has a ``*traverse`` remainder marker in its pattern. pregenerator This option should be a callable object that implements the :class:`pyramid.interfaces.IRoutePregenerator` interface. A :term:`pregenerator` is a callable called by the :meth:`pyramid.request.Request.route_url` function to augment or replace the arguments it is passed when generating a URL for the route. This is a feature not often used directly by applications, it is meant to be hooked by frameworks that use :app:`Pyramid` as a base. use_global_views When a request matches this route, and view lookup cannot find a view which has a ``route_name`` predicate argument that matches the route, try to fall back to using a view that otherwise matches the context, request, and view name (but which does not match the route_name predicate). static If ``static`` is ``True``, this route will never match an incoming request; it will only be useful for URL generation. By default, ``static`` is ``False``. See :ref:`static_route_narr`. .. versionadded:: 1.1 Predicate Arguments pattern The pattern of the route e.g. ``ideas/{idea}``. This argument is required. See :ref:`route_pattern_syntax` for information about the syntax of route patterns. If the pattern doesn't match the current URL, route matching continues. .. note:: For backwards compatibility purposes (as of :app:`Pyramid` 1.0), a ``path`` keyword argument passed to this function will be used to represent the pattern value if the ``pattern`` argument is ``None``. If both ``path`` and ``pattern`` are passed, ``pattern`` wins. xhr This value should be either ``True`` or ``False``. If this value is specified and is ``True``, the :term:`request` must possess an ``HTTP_X_REQUESTED_WITH`` (aka ``X-Requested-With``) header for this route to match. This is useful for detecting AJAX requests issued from jQuery, Prototype and other Javascript libraries. If this predicate returns ``False``, route matching continues. request_method A string representing an HTTP method name, e.g. ``GET``, ``POST``, ``HEAD``, ``DELETE``, ``PUT`` or a tuple of elements containing HTTP method names. If this argument is not specified, this route will match if the request has *any* request method. If this predicate returns ``False``, route matching continues. .. versionchanged:: 1.2 The ability to pass a tuple of items as ``request_method``. Previous versions allowed only a string. path_info This value represents a regular expression pattern that will be tested against the ``PATH_INFO`` WSGI environment variable. If the regex matches, this predicate will return ``True``. If this predicate returns ``False``, route matching continues. request_param This value can be any string or an iterable of strings. A view declaration with this argument ensures that the associated route will only match when the request has a key in the ``request.params`` dictionary (an HTTP ``GET`` or ``POST`` variable) that has a name which matches the supplied value. If the value supplied as the argument has a ``=`` sign in it, e.g. ``request_param="foo=123"``, then the key (``foo``) must both exist in the ``request.params`` dictionary, and the value must match the right hand side of the expression (``123``) for the route to "match" the current request. If this predicate returns ``False``, route matching continues. header This argument represents an HTTP header name or a header name/value pair. If the argument contains a ``:`` (colon), it will be considered a name/value pair (e.g. ``User-Agent:Mozilla/.*`` or ``Host:localhost``). If the value contains a colon, the value portion should be a regular expression. If the value does not contain a colon, the entire value will be considered to be the header name (e.g. ``If-Modified-Since``). If the value evaluates to a header name only without a value, the header specified by the name must be present in the request for this predicate to be true. If the value evaluates to a header name/value pair, the header specified by the name must be present in the request *and* the regular expression specified as the value must match the header value. Whether or not the value represents a header name or a header name/value pair, the case of the header name is not significant. If this predicate returns ``False``, route matching continues. accept A :term:`media type` that will be matched against the ``Accept`` HTTP request header. If this value is specified, it may be a specific media type such as ``text/html``, or a list of the same. If the media type is acceptable by the ``Accept`` header of the request, or if the ``Accept`` header isn't set at all in the request, this predicate will match. If this does not match the ``Accept`` header of the request, route matching continues. If ``accept`` is not specified, the ``HTTP_ACCEPT`` HTTP header is not taken into consideration when deciding whether or not to select the route. Unlike the ``accept`` argument to :meth:`pyramid.config.Configurator.add_view`, this value is strictly a predicate and supports :func:`pyramid.config.not_`. .. versionchanged:: 1.10 Specifying a media range is deprecated due to changes in WebOb and ambiguities that occur when trying to match ranges against ranges in the ``Accept`` header. Support will be removed in :app:`Pyramid` 2.0. Use a list of specific media types to match more than one type. .. versionchanged:: 2.0 Removed support for media ranges. effective_principals If specified, this value should be a :term:`principal` identifier or a sequence of principal identifiers. If the :attr:`pyramid.request.Request.effective_principals` property indicates that every principal named in the argument list is present in the current request, this predicate will return True; otherwise it will return False. For example: ``effective_principals=pyramid.security.Authenticated`` or ``effective_principals=('fred', 'group:admins')``. .. versionadded:: 1.4a4 custom_predicates .. deprecated:: 1.5 This value should be a sequence of references to custom predicate callables. Use custom predicates when no set of predefined predicates does what you need. Custom predicates can be combined with predefined predicates as necessary. Each custom predicate callable should accept two arguments: ``info`` and ``request`` and should return either ``True`` or ``False`` after doing arbitrary evaluation of the info and/or the request. If all custom and non-custom predicate callables return ``True`` the associated route will be considered viable for a given request. If any predicate callable returns ``False``, route matching continues. Note that the value ``info`` passed to a custom route predicate is a dictionary containing matching information; see :ref:`custom_route_predicates` for more information about ``info``. predicates Pass a key/value pair here to use a third-party predicate registered via :meth:`pyramid.config.Configurator.add_route_predicate`. More than one key/value pair can be used at the same time. See :ref:`view_and_route_predicates` for more information about third-party predicates. .. versionadded:: 1.4 """ if custom_predicates: warnings.warn( ( 'The "custom_predicates" argument to ' 'Configurator.add_route is deprecated as of Pyramid 1.5. ' 'Use "config.add_route_predicate" and use the registered ' 'route predicate as a predicate argument to add_route ' 'instead. See "Adding A Third Party View, Route, or ' 'Subscriber Predicate" in the "Hooks" chapter of the ' 'documentation for more information.' ), DeprecationWarning, stacklevel=3, ) if accept is not None: if not is_nonstr_iter(accept): accept = [accept] accept = [ normalize_accept_offer(accept_option) for accept_option in accept ] # these are route predicates; if they do not match, the next route # in the routelist will be tried if request_method is not None: request_method = as_sorted_tuple(request_method) factory = self.maybe_dotted(factory) if pattern is None: pattern = path if pattern is None: raise ConfigurationError('"pattern" argument may not be None') # check for an external route; an external route is one which is # is a full url (e.g. 'http://example.com/{id}') parsed = urlparse.urlparse(pattern) external_url = pattern if parsed.hostname: pattern = parsed.path original_pregenerator = pregenerator def external_url_pregenerator(request, elements, kw): if '_app_url' in kw: raise ValueError( 'You cannot generate a path to an external route ' 'pattern via request.route_path nor pass an _app_url ' 'to request.route_url when generating a URL for an ' 'external route pattern (pattern was "%s") ' % (pattern,) ) if '_scheme' in kw: scheme = kw['_scheme'] elif parsed.scheme: scheme = parsed.scheme else: scheme = request.scheme kw['_app_url'] = '{0}://{1}'.format(scheme, parsed.netloc) if original_pregenerator: elements, kw = original_pregenerator(request, elements, kw) return elements, kw pregenerator = external_url_pregenerator static = True elif self.route_prefix: pattern = self.route_prefix.rstrip('/') + '/' + pattern.lstrip('/') mapper = self.get_routes_mapper() introspectables = [] intr = self.introspectable( 'routes', name, '%s (pattern: %r)' % (name, pattern), 'route' ) intr['name'] = name intr['pattern'] = pattern intr['factory'] = factory intr['xhr'] = xhr intr['request_methods'] = request_method intr['path_info'] = path_info intr['request_param'] = request_param intr['header'] = header intr['accept'] = accept intr['traverse'] = traverse intr['custom_predicates'] = custom_predicates intr['pregenerator'] = pregenerator intr['static'] = static intr['use_global_views'] = use_global_views if static is True: intr['external_url'] = external_url introspectables.append(intr) if factory: factory_intr = self.introspectable( 'root factories', name, self.object_description(factory), 'root factory', ) factory_intr['factory'] = factory factory_intr['route_name'] = name factory_intr.relate('routes', name) introspectables.append(factory_intr) def register_route_request_iface(): request_iface = self.registry.queryUtility( IRouteRequest, name=name ) if request_iface is None: if use_global_views: bases = (IRequest,) else: bases = () request_iface = route_request_iface(name, bases) self.registry.registerUtility( request_iface, IRouteRequest, name=name ) def register_connect(): pvals = predicates.copy() pvals.update( dict( xhr=xhr, request_method=request_method, path_info=path_info, request_param=request_param, header=header, accept=accept, traverse=traverse, custom=predvalseq(custom_predicates), ) ) predlist = self.get_predlist('route') _, preds, _ = predlist.make(self, **pvals) route = mapper.connect( name, pattern, factory, predicates=preds, pregenerator=pregenerator, static=static, ) intr['object'] = route return route # We have to connect routes in the order they were provided; # we can't use a phase to do that, because when the actions are # sorted, actions in the same phase lose relative ordering self.action(('route-connect', name), register_connect) # But IRouteRequest interfaces must be registered before we begin to # process view registrations (in phase 3) self.action( ('route', name), register_route_request_iface, order=PHASE2_CONFIG, introspectables=introspectables, )
def check_csrf_origin(request, trusted_origins=None, raises=True): """ Check the ``Origin`` of the request to see if it is a cross site request or not. If the value supplied by the ``Origin`` or ``Referer`` header isn't one of the trusted origins and ``raises`` is ``True``, this function will raise a :exc:`pyramid.exceptions.BadCSRFOrigin` exception, but if ``raises`` is ``False``, this function will return ``False`` instead. If the CSRF origin checks are successful this function will return ``True`` unconditionally. Additional trusted origins may be added by passing a list of domain (and ports if non-standard like ``['example.com', 'dev.example.com:8080']``) in with the ``trusted_origins`` parameter. If ``trusted_origins`` is ``None`` (the default) this list of additional domains will be pulled from the ``pyramid.csrf_trusted_origins`` setting. Note that this function will do nothing if ``request.scheme`` is not ``https``. .. versionadded:: 1.7 .. versionchanged:: 1.9 Moved from :mod:`pyramid.session` to :mod:`pyramid.csrf` """ def _fail(reason): if raises: raise BadCSRFOrigin(reason) else: return False if request.scheme == "https": # Suppose user visits http://example.com/ # An active network attacker (man-in-the-middle, MITM) sends a # POST form that targets https://example.com/detonate-bomb/ and # submits it via JavaScript. # # The attacker will need to provide a CSRF cookie and token, but # that's no problem for a MITM when we cannot make any assumptions # about what kind of session storage is being used. So the MITM can # circumvent the CSRF protection. This is true for any HTTP connection, # but anyone using HTTPS expects better! For this reason, for # https://example.com/ we need additional protection that treats # http://example.com/ as completely untrusted. Under HTTPS, # Barth et al. found that the Referer header is missing for # same-domain requests in only about 0.2% of cases or less, so # we can use strict Referer checking. # Determine the origin of this request origin = request.headers.get("Origin") if origin is None: origin = request.referrer # Fail if we were not able to locate an origin at all if not origin: return _fail("Origin checking failed - no Origin or Referer.") # Parse our origin so we we can extract the required information from # it. originp = urlparse.urlparse(origin) # Ensure that our Referer is also secure. if originp.scheme != "https": return _fail( "Referer checking failed - Referer is insecure while host is " "secure.") # Determine which origins we trust, which by default will include the # current origin. if trusted_origins is None: trusted_origins = aslist( request.registry.settings.get("pyramid.csrf_trusted_origins", [])) if request.host_port not in set(["80", "443"]): trusted_origins.append("{0.domain}:{0.host_port}".format(request)) else: trusted_origins.append(request.domain) # Actually check to see if the request's origin matches any of our # trusted origins. if not any( is_same_domain(originp.netloc, host) for host in trusted_origins): reason = ( "Referer checking failed - {0} does not match any trusted " "origins.") return _fail(reason.format(origin)) return True
def check_csrf_origin(request, trusted_origins=None, raises=True): """ Check the Origin of the request to see if it is a cross site request or not. If the value supplied by the Origin or Referer header isn't one of the trusted origins and ``raises`` is ``True``, this function will raise a :exc:`pyramid.exceptions.BadCSRFOrigin` exception but if ``raises`` is ``False`` this function will return ``False`` instead. If the CSRF origin checks are successful this function will return ``True`` unconditionally. Additional trusted origins may be added by passing a list of domain (and ports if nonstandard like `['example.com', 'dev.example.com:8080']`) in with the ``trusted_origins`` parameter. If ``trusted_origins`` is ``None`` (the default) this list of additional domains will be pulled from the ``pyramid.csrf_trusted_origins`` setting. Note that this function will do nothing if request.scheme is not https. .. versionadded:: 1.7 """ def _fail(reason): if raises: raise BadCSRFOrigin(reason) else: return False if request.scheme == "https": # Suppose user visits http://example.com/ # An active network attacker (man-in-the-middle, MITM) sends a # POST form that targets https://example.com/detonate-bomb/ and # submits it via JavaScript. # # The attacker will need to provide a CSRF cookie and token, but # that's no problem for a MITM when we cannot make any assumptions # about what kind of session storage is being used. So the MITM can # circumvent the CSRF protection. This is true for any HTTP connection, # but anyone using HTTPS expects better! For this reason, for # https://example.com/ we need additional protection that treats # http://example.com/ as completely untrusted. Under HTTPS, # Barth et al. found that the Referer header is missing for # same-domain requests in only about 0.2% of cases or less, so # we can use strict Referer checking. # Determine the origin of this request origin = request.headers.get("Origin") if origin is None: origin = request.referrer # Fail if we were not able to locate an origin at all if not origin: return _fail("Origin checking failed - no Origin or Referer.") # Parse our origin so we we can extract the required information from # it. originp = urlparse.urlparse(origin) # Ensure that our Referer is also secure. if originp.scheme != "https": return _fail( "Referer checking failed - Referer is insecure while host is " "secure." ) # Determine which origins we trust, which by default will include the # current origin. if trusted_origins is None: trusted_origins = aslist( request.registry.settings.get( "pyramid.csrf_trusted_origins", []) ) if request.host_port not in set(["80", "443"]): trusted_origins.append("{0.domain}:{0.host_port}".format(request)) else: trusted_origins.append(request.domain) # Actually check to see if the request's origin matches any of our # trusted origins. if not any(is_same_domain(originp.netloc, host) for host in trusted_origins): reason = ( "Referer checking failed - {0} does not match any trusted " "origins." ) return _fail(reason.format(origin)) return True