Back to index

moin  1.9.0~rc2
Public Member Functions | Public Attributes
MoinMoin.support.werkzeug.routing.MapAdapter Class Reference

List of all members.

Public Member Functions

def __init__
def dispatch
def match
def test
def build

Public Attributes

 map
 server_name
 script_name
 subdomain
 url_scheme
 path_info
 default_method

Detailed Description

Returned by :meth:`Map.bind` or :meth:`Map.bind_to_environ` and does
the URL matching and building based on runtime information.

Definition at line 1069 of file routing.py.


Constructor & Destructor Documentation

def MoinMoin.support.werkzeug.routing.MapAdapter.__init__ (   self,
  map,
  server_name,
  script_name,
  subdomain,
  url_scheme,
  path_info,
  default_method 
)

Definition at line 1075 of file routing.py.

01075 
01076                  url_scheme, path_info, default_method):
01077         self.map = map
01078         self.server_name = server_name
01079         if not script_name.endswith('/'):
01080             script_name += '/'
01081         self.script_name = script_name
01082         self.subdomain = subdomain
01083         self.url_scheme = url_scheme
01084         self.path_info = path_info or u''
01085         self.default_method = default_method


Member Function Documentation

def MoinMoin.support.werkzeug.routing.MapAdapter.build (   self,
  endpoint,
  values = None,
  method = None,
  force_external = False 
)
Building URLs works pretty much the other way round.  Instead of
`match` you call `build` and pass it the endpoint and a dict of
arguments for the placeholders.

The `build` function also accepts an argument called `force_external`
which, if you set it to `True` will force external URLs. Per default
external URLs (include the server name) will only be used if the
target URL is on a different subdomain.

>>> m = Map([
...     Rule('/', endpoint='index'),
...     Rule('/downloads/', endpoint='downloads/index'), 
...     Rule('/downloads/<int:id>', endpoint='downloads/show')
... ])
>>> urls = m.bind("example.com", "/")
>>> urls.build("index", {})
'/'
>>> urls.build("downloads/show", {'id': 42})
'/downloads/42'
>>> urls.build("downloads/show", {'id': 42}, force_external=True)
'http://example.com/downloads/42'

Because URLs cannot contain non ASCII data you will always get
bytestrings back.  Non ASCII characters are urlencoded with the
charset defined on the map instance.

Additional values are converted to unicode and appended to the URL as
URL querystring parameters:

>>> urls.build("index", {'q': 'My Searchstring'})
'/?q=My+Searchstring'

If a rule does not exist when building a `BuildError` exception is
raised.

The build method accepts an argument called `method` which allows you
to specify the method you want to have an URL built for if you have
different methods for the same endpoint specified.

:param endpoint: the endpoint of the URL to build.
:param values: the values for the URL to build.  Unhandled values are
       appended to the URL as query parameters.
:param method: the HTTP method for the rule if there are different
       URLs for different methods on the same endpoint.
:param force_external: enforce full canonical external URLs.

Definition at line 1275 of file routing.py.

01275 
01276     def build(self, endpoint, values=None, method=None, force_external=False):
01277         """Building URLs works pretty much the other way round.  Instead of
01278         `match` you call `build` and pass it the endpoint and a dict of
01279         arguments for the placeholders.
01280 
01281         The `build` function also accepts an argument called `force_external`
01282         which, if you set it to `True` will force external URLs. Per default
01283         external URLs (include the server name) will only be used if the
01284         target URL is on a different subdomain.
01285 
01286         >>> m = Map([
01287         ...     Rule('/', endpoint='index'),
01288         ...     Rule('/downloads/', endpoint='downloads/index'), 
01289         ...     Rule('/downloads/<int:id>', endpoint='downloads/show')
01290         ... ])
01291         >>> urls = m.bind("example.com", "/")
01292         >>> urls.build("index", {})
01293         '/'
01294         >>> urls.build("downloads/show", {'id': 42})
01295         '/downloads/42'
01296         >>> urls.build("downloads/show", {'id': 42}, force_external=True)
01297         'http://example.com/downloads/42'
01298 
01299         Because URLs cannot contain non ASCII data you will always get
01300         bytestrings back.  Non ASCII characters are urlencoded with the
01301         charset defined on the map instance.
01302 
01303         Additional values are converted to unicode and appended to the URL as
01304         URL querystring parameters:
01305 
01306         >>> urls.build("index", {'q': 'My Searchstring'})
01307         '/?q=My+Searchstring'
01308 
01309         If a rule does not exist when building a `BuildError` exception is
01310         raised.
01311 
01312         The build method accepts an argument called `method` which allows you
01313         to specify the method you want to have an URL built for if you have
01314         different methods for the same endpoint specified.
01315 
01316         :param endpoint: the endpoint of the URL to build.
01317         :param values: the values for the URL to build.  Unhandled values are
01318                        appended to the URL as query parameters.
01319         :param method: the HTTP method for the rule if there are different
01320                        URLs for different methods on the same endpoint.
01321         :param force_external: enforce full canonical external URLs.
01322         """
01323         self.map.update()
01324         method = method or self.default_method
01325         if values:
01326             values = dict([(k, v) for k, v in values.items() if v is not None])
01327         else:
01328             values = {}
01329 
01330         for rule in self.map._rules_by_endpoint.get(endpoint, ()):
01331             if rule.suitable_for(values, method):
01332                 rv = rule.build(values)
01333                 if rv is not None:
01334                     break
01335         else:
01336             raise BuildError(endpoint, values, method)
01337         subdomain, path = rv
01338         if not force_external and subdomain == self.subdomain:
01339             return str(urljoin(self.script_name, path.lstrip('/')))
01340         return str('%s://%s%s%s/%s' % (
01341             self.url_scheme,
01342             subdomain and subdomain + '.' or '',
01343             self.server_name,
01344             self.script_name[:-1],
01345             path.lstrip('/')
01346         ))
01347 
01348 
#: the default converter mapping for the map.
def MoinMoin.support.werkzeug.routing.MapAdapter.dispatch (   self,
  view_func,
  path_info = None,
  method = None,
  catch_http_exceptions = False 
)
Does the complete dispatching process.  `view_func` is called with
the endpoint and a dict with the values for the view.  It should
look up the view function, call it, and return a response object
or WSGI application.  http exceptions are not catched by default
so that applications can display nicer error messages by just
catching them by hand.  If you want to stick with the default
error messages you can pass it ``catch_http_exceptions=True`` and
it will catch the http exceptions.

Here a small example for the dispatch usage::

    from werkzeug import Request, Response, responder
    from werkzeug.routing import Map, Rule

    def on_index(request):
return Response('Hello from the index')

    url_map = Map([Rule('/', endpoint='index')])
    views = {'index': on_index}

    @responder
    def application(environ, start_response):
request = Request(environ)
urls = url_map.bind_to_environ(environ)
return urls.dispatch(lambda e, v: views[e](request, **v),
                     catch_http_exceptions=True)

Keep in mind that this method might return exception objects, too, so
use :class:`Response.force_type` to get a response object.

:param view_func: a function that is called with the endpoint as
          first argument and the value dict as second.  Has
          to dispatch to the actual view function with this
          information.  (see above)
:param path_info: the path info to use for matching.  Overrides the
          path info specified on binding.
:param method: the HTTP method used for matching.  Overrides the
       method specified on binding.
:param catch_http_exceptions: set to `True` to catch any of the
                      werkzeug :class:`HTTPException`\s.

Definition at line 1087 of file routing.py.

01087 
01088                  catch_http_exceptions=False):
01089         """Does the complete dispatching process.  `view_func` is called with
01090         the endpoint and a dict with the values for the view.  It should
01091         look up the view function, call it, and return a response object
01092         or WSGI application.  http exceptions are not catched by default
01093         so that applications can display nicer error messages by just
01094         catching them by hand.  If you want to stick with the default
01095         error messages you can pass it ``catch_http_exceptions=True`` and
01096         it will catch the http exceptions.
01097 
01098         Here a small example for the dispatch usage::
01099 
01100             from werkzeug import Request, Response, responder
01101             from werkzeug.routing import Map, Rule
01102 
01103             def on_index(request):
01104                 return Response('Hello from the index')
01105 
01106             url_map = Map([Rule('/', endpoint='index')])
01107             views = {'index': on_index}
01108 
01109             @responder
01110             def application(environ, start_response):
01111                 request = Request(environ)
01112                 urls = url_map.bind_to_environ(environ)
01113                 return urls.dispatch(lambda e, v: views[e](request, **v),
01114                                      catch_http_exceptions=True)
01115 
01116         Keep in mind that this method might return exception objects, too, so
01117         use :class:`Response.force_type` to get a response object.
01118 
01119         :param view_func: a function that is called with the endpoint as
01120                           first argument and the value dict as second.  Has
01121                           to dispatch to the actual view function with this
01122                           information.  (see above)
01123         :param path_info: the path info to use for matching.  Overrides the
01124                           path info specified on binding.
01125         :param method: the HTTP method used for matching.  Overrides the
01126                        method specified on binding.
01127         :param catch_http_exceptions: set to `True` to catch any of the
01128                                       werkzeug :class:`HTTPException`\s.
01129         """
01130         try:
01131             try:
01132                 endpoint, args = self.match(path_info, method)
01133             except RequestRedirect, e:
01134                 return e
01135             return view_func(endpoint, args)
01136         except HTTPException, e:
01137             if catch_http_exceptions:
01138                 return e
01139             raise

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.werkzeug.routing.MapAdapter.match (   self,
  path_info = None,
  method = None 
)
The usage is simple: you just pass the match method the current
path info as well as the method (which defaults to `GET`).  The
following things can then happen:

- you receive a `NotFound` exception that indicates that no URL is
  matching.  A `NotFound` exception is also a WSGI application you
  can call to get a default page not found page (happens to be the
  same object as `werkzeug.exceptions.NotFound`)

- you receive a `MethodNotAllowed` exception that indicates that there
  is a match for this URL but non for the current request method.
  This is useful for RESTful applications.

- you receive a `RequestRedirect` exception with a `new_url`
  attribute.  This exception is used to notify you about a request
  Werkzeug requests by your WSGI application.  This is for example the
  case if you request ``/foo`` although the correct URL is ``/foo/``
  You can use the `RequestRedirect` instance as response-like object
  similar to all other subclasses of `HTTPException`.

- you get a tuple in the form ``(endpoint, arguments)`` when there is
  a match.

If the path info is not passed to the match method the default path
info of the map is used (defaults to the root URL if not defined
explicitly).

All of the exceptions raised are subclasses of `HTTPException` so they
can be used as WSGI responses.  The will all render generic error or
redirect pages.

Here is a small example for matching:

>>> m = Map([
...     Rule('/', endpoint='index'),
...     Rule('/downloads/', endpoint='downloads/index'), 
...     Rule('/downloads/<int:id>', endpoint='downloads/show')
... ])
>>> urls = m.bind("example.com", "/")
>>> urls.match("/", "GET")
('index', {})
>>> urls.match("/downloads/42")
('downloads/show', {'id': 42})

And here is what happens on redirect and missing URLs:

>>> urls.match("/downloads")
Traceback (most recent call last):
  ...
RequestRedirect: http://example.com/downloads/
>>> urls.match("/missing")
Traceback (most recent call last):
  ...
NotFound: 404 Not Found

:param path_info: the path info to use for matching.  Overrides the
          path info specified on binding.
:param method: the HTTP method used for matching.  Overrides the
       method specified on binding.

Definition at line 1140 of file routing.py.

01140 
01141     def match(self, path_info=None, method=None):
01142         """The usage is simple: you just pass the match method the current
01143         path info as well as the method (which defaults to `GET`).  The
01144         following things can then happen:
01145 
01146         - you receive a `NotFound` exception that indicates that no URL is
01147           matching.  A `NotFound` exception is also a WSGI application you
01148           can call to get a default page not found page (happens to be the
01149           same object as `werkzeug.exceptions.NotFound`)
01150 
01151         - you receive a `MethodNotAllowed` exception that indicates that there
01152           is a match for this URL but non for the current request method.
01153           This is useful for RESTful applications.
01154 
01155         - you receive a `RequestRedirect` exception with a `new_url`
01156           attribute.  This exception is used to notify you about a request
01157           Werkzeug requests by your WSGI application.  This is for example the
01158           case if you request ``/foo`` although the correct URL is ``/foo/``
01159           You can use the `RequestRedirect` instance as response-like object
01160           similar to all other subclasses of `HTTPException`.
01161 
01162         - you get a tuple in the form ``(endpoint, arguments)`` when there is
01163           a match.
01164 
01165         If the path info is not passed to the match method the default path
01166         info of the map is used (defaults to the root URL if not defined
01167         explicitly).
01168 
01169         All of the exceptions raised are subclasses of `HTTPException` so they
01170         can be used as WSGI responses.  The will all render generic error or
01171         redirect pages.
01172 
01173         Here is a small example for matching:
01174 
01175         >>> m = Map([
01176         ...     Rule('/', endpoint='index'),
01177         ...     Rule('/downloads/', endpoint='downloads/index'), 
01178         ...     Rule('/downloads/<int:id>', endpoint='downloads/show')
01179         ... ])
01180         >>> urls = m.bind("example.com", "/")
01181         >>> urls.match("/", "GET")
01182         ('index', {})
01183         >>> urls.match("/downloads/42")
01184         ('downloads/show', {'id': 42})
01185 
01186         And here is what happens on redirect and missing URLs:
01187 
01188         >>> urls.match("/downloads")
01189         Traceback (most recent call last):
01190           ...
01191         RequestRedirect: http://example.com/downloads/
01192         >>> urls.match("/missing")
01193         Traceback (most recent call last):
01194           ...
01195         NotFound: 404 Not Found
01196 
01197         :param path_info: the path info to use for matching.  Overrides the
01198                           path info specified on binding.
01199         :param method: the HTTP method used for matching.  Overrides the
01200                        method specified on binding.
01201         """
01202         self.map.update()
01203         if path_info is None:
01204             path_info = self.path_info
01205         if not isinstance(path_info, unicode):
01206             path_info = path_info.decode(self.map.charset, 'ignore')
01207         method = (method or self.default_method).upper()
01208         path = u'%s|/%s' % (self.subdomain, path_info.lstrip('/'))
01209         have_match_for = set()
01210         for rule in self.map._rules:
01211             try:
01212                 rv = rule.match(path)
01213             except RequestSlash:
01214                 raise RequestRedirect(str('%s://%s%s%s/%s/' % (
01215                     self.url_scheme,
01216                     self.subdomain and self.subdomain + '.' or '',
01217                     self.server_name,
01218                     self.script_name[:-1],
01219                     url_quote(path_info.lstrip('/'), self.map.charset)
01220                 )))
01221             if rv is None:
01222                 continue
01223             if rule.methods is not None and method not in rule.methods:
01224                 have_match_for.update(rule.methods)
01225                 continue
01226             if self.map.redirect_defaults:
01227                 for r in self.map._rules_by_endpoint[rule.endpoint]:
01228                     if r.provides_defaults_for(rule) and \
01229                        r.suitable_for(rv, method):
01230                         rv.update(r.defaults)
01231                         subdomain, path = r.build(rv)
01232                         raise RequestRedirect(str('%s://%s%s%s/%s' % (
01233                             self.url_scheme,
01234                             subdomain and subdomain + '.' or '',
01235                             self.server_name,
01236                             self.script_name[:-1],
01237                             url_quote(path.lstrip('/'), self.map.charset)
01238                         )))
01239             if rule.redirect_to is not None:
01240                 if isinstance(rule.redirect_to, basestring):
01241                     def _handle_match(match):
01242                         value = rv[match.group(1)]
01243                         return rule._converters[match.group(1)].to_url(value)
01244                     redirect_url = _simple_rule_re.sub(_handle_match,
01245                                                        rule.redirect_to)
01246                 else:
01247                     redirect_url = rule.redirect_to(self, **rv)
01248                 raise RequestRedirect(str(urljoin('%s://%s%s%s' % (
01249                     self.url_scheme,
01250                     self.subdomain and self.subdomain + '.' or '',
01251                     self.server_name,
01252                     self.script_name
01253                 ), redirect_url)))
01254             return rule.endpoint, rv
01255         if have_match_for:
01256             raise MethodNotAllowed(valid_methods=list(have_match_for))
01257         raise NotFound()

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.werkzeug.routing.MapAdapter.test (   self,
  path_info = None,
  method = None 
)
Test if a rule would match.  Works like `match` but returns `True`
if the URL matches, or `False` if it does not exist.

:param path_info: the path info to use for matching.  Overrides the
          path info specified on binding.
:param method: the HTTP method used for matching.  Overrides the
       method specified on binding.

Definition at line 1258 of file routing.py.

01258 
01259     def test(self, path_info=None, method=None):
01260         """Test if a rule would match.  Works like `match` but returns `True`
01261         if the URL matches, or `False` if it does not exist.
01262 
01263         :param path_info: the path info to use for matching.  Overrides the
01264                           path info specified on binding.
01265         :param method: the HTTP method used for matching.  Overrides the
01266                        method specified on binding.
01267         """
01268         try:
01269             self.match(path_info, method)
01270         except RequestRedirect:
01271             pass
01272         except NotFound:
01273             return False
01274         return True

Here is the call graph for this function:


Member Data Documentation

Definition at line 1084 of file routing.py.

Definition at line 1076 of file routing.py.

Definition at line 1083 of file routing.py.

Definition at line 1080 of file routing.py.

Definition at line 1077 of file routing.py.

Definition at line 1081 of file routing.py.

Definition at line 1082 of file routing.py.


The documentation for this class was generated from the following file: