signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
|---|---|---|---|
def generate_adapter(adapter, name='<STR_LIT>', map_name='<STR_LIT>'):
|
values = {<EOL>u'<STR_LIT>': dumps(adapter.server_name),<EOL>u'<STR_LIT>': dumps(adapter.script_name),<EOL>u'<STR_LIT>': dumps(adapter.subdomain),<EOL>u'<STR_LIT>': dumps(adapter.url_scheme),<EOL>u'<STR_LIT:name>': name,<EOL>u'<STR_LIT>': map_name<EOL>}<EOL>return
|
Generates the url building function for a map.
|
f5854:m2
|
def js_to_url_function(converter):
|
if hasattr(converter, '<STR_LIT>'):<EOL><INDENT>data = converter.js_to_url_function()<EOL><DEDENT>else:<EOL><INDENT>for cls in getmro(type(converter)):<EOL><INDENT>if cls in js_to_url_functions:<EOL><INDENT>data = js_to_url_functions[cls](converter)<EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT><DEDENT>return '<STR_LIT>' % data<EOL>
|
Get the JavaScript converter function from a rule.
|
f5854:m3
|
def process_view(self, request, view_func, view_args, view_kwargs):
|
return None<EOL>
|
process_view() is called just before the Application calls the
function specified by view_func.
If this returns None, the Application processes the next Processor,
and if it returns something else (like a Response instance), that
will be returned without any further processing.
|
f5855:c2:m2
|
def config_session(self, store, expiration='<STR_LIT>'):
|
self.store = store<EOL>
|
Configures the setting for cookies. You can also disable cookies by
setting store to None.
|
f5855:c3:m2
|
def get_template(self, name):
|
filename = path.join(self.search_path, *[p for p in name.split('<STR_LIT:/>')<EOL>if p and p[<NUM_LIT:0>] != '<STR_LIT:.>'])<EOL>if not path.exists(filename):<EOL><INDENT>raise TemplateNotFound(name)<EOL><DEDENT>return Template.from_file(filename, self.encoding)<EOL>
|
Get a template from a given name.
|
f5855:c5:m1
|
def render_to_response(self, *args, **kwargs):
|
return Response(self.render_to_string(*args, **kwargs))<EOL>
|
Load and render a template into a response object.
|
f5855:c5:m2
|
def render_to_string(self, *args, **kwargs):
|
try:<EOL><INDENT>template_name, args = args[<NUM_LIT:0>], args[<NUM_LIT:1>:]<EOL><DEDENT>except IndexError:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>return self.get_template(template_name).render(*args, **kwargs)<EOL>
|
Load and render a template into a unicode string.
|
f5855:c5:m3
|
def get_template(self, template_name):
|
try:<EOL><INDENT>return self.loader.load(template_name, encoding=self.encoding)<EOL><DEDENT>except self.not_found_exception as e:<EOL><INDENT>raise TemplateNotFound(template_name)<EOL><DEDENT>
|
Get the template which is at the given name
|
f5855:c6:m1
|
def render_to_string(self, template_name, context=None):
|
<EOL>context = context or {}<EOL>tmpl = self.get_template(template_name)<EOL>return tmpl.generate(**context).render(self.output_type, encoding=None)<EOL>
|
Load and render a template into an unicode string
|
f5855:c6:m2
|
def _make_text_block(name, content, content_type=None):
|
if content_type == '<STR_LIT>':<EOL><INDENT>return u'<STR_LIT>' %(name, XHTML_NAMESPACE, content, name)<EOL><DEDENT>if not content_type:<EOL><INDENT>return u'<STR_LIT>' % (name, escape(content), name)<EOL><DEDENT>return u'<STR_LIT>' % (name, content_type,<EOL>escape(content), name)<EOL>
|
Helper function for the builder that creates an XML text block.
|
f5856:m0
|
def format_iso8601(obj):
|
return obj.strftime('<STR_LIT>')<EOL>
|
Format a datetime object for iso8601
|
f5856:m1
|
def add(self, *args, **kwargs):
|
if len(args) == <NUM_LIT:1> and not kwargs and isinstance(args[<NUM_LIT:0>], FeedEntry):<EOL><INDENT>self.entries.append(args[<NUM_LIT:0>])<EOL><DEDENT>else:<EOL><INDENT>kwargs['<STR_LIT>'] = self.feed_url<EOL>self.entries.append(FeedEntry(*args, **kwargs))<EOL><DEDENT>
|
Add a new entry to the feed. This function can either be called
with a :class:`FeedEntry` or some keyword and positional arguments
that are forwarded to the :class:`FeedEntry` constructor.
|
f5856:c0:m1
|
def generate(self):
|
<EOL>if not self.author:<EOL><INDENT>if False in map(lambda e: bool(e.author), self.entries):<EOL><INDENT>self.author = ({'<STR_LIT:name>': '<STR_LIT>'},)<EOL><DEDENT><DEDENT>if not self.updated:<EOL><INDENT>dates = sorted([entry.updated for entry in self.entries])<EOL>self.updated = dates and dates[-<NUM_LIT:1>] or datetime.utcnow()<EOL><DEDENT>yield u'<STR_LIT>'<EOL>yield u'<STR_LIT>'<EOL>yield '<STR_LIT:U+0020>' + _make_text_block('<STR_LIT:title>', self.title, self.title_type)<EOL>yield u'<STR_LIT>' % escape(self.id)<EOL>yield u'<STR_LIT>' % format_iso8601(self.updated)<EOL>if self.url:<EOL><INDENT>yield u'<STR_LIT>' % escape(self.url, True)<EOL><DEDENT>if self.feed_url:<EOL><INDENT>yield u'<STR_LIT>' %escape(self.feed_url, True)<EOL><DEDENT>for link in self.links:<EOL><INDENT>yield u'<STR_LIT>' % '<STR_LIT>'.join('<STR_LIT>' %(k, escape(link[k], True)) for k in link)<EOL><DEDENT>for author in self.author:<EOL><INDENT>yield u'<STR_LIT>'<EOL>yield u'<STR_LIT>' % escape(author['<STR_LIT:name>'])<EOL>if '<STR_LIT>' in author:<EOL><INDENT>yield u'<STR_LIT>' % escape(author['<STR_LIT>'])<EOL><DEDENT>if '<STR_LIT:email>' in author:<EOL><INDENT>yield '<STR_LIT>' % escape(author['<STR_LIT:email>'])<EOL><DEDENT>yield '<STR_LIT>'<EOL><DEDENT>if self.subtitle:<EOL><INDENT>yield '<STR_LIT:U+0020>' + _make_text_block('<STR_LIT>', self.subtitle,<EOL>self.subtitle_type)<EOL><DEDENT>if self.icon:<EOL><INDENT>yield u'<STR_LIT>' % escape(self.icon)<EOL><DEDENT>if self.logo:<EOL><INDENT>yield u'<STR_LIT>' % escape(self.logo)<EOL><DEDENT>if self.rights:<EOL><INDENT>yield '<STR_LIT:U+0020>' + _make_text_block('<STR_LIT>', self.rights,<EOL>self.rights_type)<EOL><DEDENT>generator_name, generator_url, generator_version = self.generator<EOL>if generator_name or generator_url or generator_version:<EOL><INDENT>tmp = [u'<STR_LIT>']<EOL>if generator_url:<EOL><INDENT>tmp.append(u'<STR_LIT>' % escape(generator_url, True))<EOL><DEDENT>if generator_version:<EOL><INDENT>tmp.append(u'<STR_LIT>' % escape(generator_version, True))<EOL><DEDENT>tmp.append(u'<STR_LIT>' % escape(generator_name))<EOL>yield u'<STR_LIT>'.join(tmp)<EOL><DEDENT>for entry in self.entries:<EOL><INDENT>for line in entry.generate():<EOL><INDENT>yield u'<STR_LIT:U+0020>' + line<EOL><DEDENT><DEDENT>yield u'<STR_LIT>'<EOL>
|
Return a generator that yields pieces of XML.
|
f5856:c0:m3
|
def to_string(self):
|
return u'<STR_LIT>'.join(self.generate())<EOL>
|
Convert the feed into a string.
|
f5856:c0:m4
|
def get_response(self):
|
return BaseResponse(self.to_string(), mimetype='<STR_LIT>')<EOL>
|
Return a response object for the feed.
|
f5856:c0:m5
|
def __call__(self, environ, start_response):
|
return self.get_response()(environ, start_response)<EOL>
|
Use the class as WSGI response object.
|
f5856:c0:m6
|
def generate(self):
|
base = '<STR_LIT>'<EOL>if self.xml_base:<EOL><INDENT>base = '<STR_LIT>' % escape(self.xml_base, True)<EOL><DEDENT>yield u'<STR_LIT>' % base<EOL>yield u'<STR_LIT:U+0020>' + _make_text_block('<STR_LIT:title>', self.title, self.title_type)<EOL>yield u'<STR_LIT>' % escape(self.id)<EOL>yield u'<STR_LIT>' % format_iso8601(self.updated)<EOL>if self.published:<EOL><INDENT>yield u'<STR_LIT>' %format_iso8601(self.published)<EOL><DEDENT>if self.url:<EOL><INDENT>yield u'<STR_LIT>' % escape(self.url)<EOL><DEDENT>for author in self.author:<EOL><INDENT>yield u'<STR_LIT>'<EOL>yield u'<STR_LIT>' % escape(author['<STR_LIT:name>'])<EOL>if '<STR_LIT>' in author:<EOL><INDENT>yield u'<STR_LIT>' % escape(author['<STR_LIT>'])<EOL><DEDENT>if '<STR_LIT:email>' in author:<EOL><INDENT>yield u'<STR_LIT>' % escape(author['<STR_LIT:email>'])<EOL><DEDENT>yield u'<STR_LIT>'<EOL><DEDENT>for link in self.links:<EOL><INDENT>yield u'<STR_LIT>' % '<STR_LIT>'.join('<STR_LIT>' %(k, escape(link[k], True)) for k in link)<EOL><DEDENT>for category in self.categories:<EOL><INDENT>yield u'<STR_LIT>' % '<STR_LIT>'.join('<STR_LIT>' %(k, escape(category[k], True)) for k in category)<EOL><DEDENT>if self.summary:<EOL><INDENT>yield u'<STR_LIT:U+0020>' + _make_text_block('<STR_LIT>', self.summary,<EOL>self.summary_type)<EOL><DEDENT>if self.content:<EOL><INDENT>yield u'<STR_LIT:U+0020>' + _make_text_block('<STR_LIT:content>', self.content,<EOL>self.content_type)<EOL><DEDENT>yield u'<STR_LIT>'<EOL>
|
Yields pieces of ATOM XML.
|
f5856:c1:m2
|
def to_string(self):
|
return u'<STR_LIT>'.join(self.generate())<EOL>
|
Convert the feed item into a unicode object.
|
f5856:c1:m3
|
def is_known_charset(charset):
|
try:<EOL><INDENT>codecs.lookup(charset)<EOL><DEDENT>except LookupError:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
Checks if the given charset is known to Python.
|
f5857:m0
|
@cached_property<EOL><INDENT>def json(self):<DEDENT>
|
if '<STR_LIT>' not in self.environ.get('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>raise BadRequest('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>return loads(self.data)<EOL><DEDENT>except Exception:<EOL><INDENT>raise BadRequest('<STR_LIT>')<EOL><DEDENT>
|
Get the result of simplejson.loads if possible.
|
f5857:c0:m0
|
def parse_protobuf(self, proto_type):
|
if '<STR_LIT>' not in self.environ.get('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>raise BadRequest('<STR_LIT>')<EOL><DEDENT>obj = proto_type()<EOL>try:<EOL><INDENT>obj.ParseFromString(self.data)<EOL><DEDENT>except Exception:<EOL><INDENT>raise BadRequest("<STR_LIT>")<EOL><DEDENT>if self.protobuf_check_initialization and not obj.IsInitialized():<EOL><INDENT>raise BadRequest("<STR_LIT>")<EOL><DEDENT>return obj<EOL>
|
Parse the data into an instance of proto_type.
|
f5857:c1:m0
|
@cached_property<EOL><INDENT>def path(self):<DEDENT>
|
path = wsgi_decoding_dance(self.environ.get('<STR_LIT>') or '<STR_LIT>',<EOL>self.charset, self.encoding_errors)<EOL>return path.lstrip('<STR_LIT:/>')<EOL>
|
Requested path as unicode. This works a bit like the regular path
info in the WSGI environment but will not include a leading slash.
|
f5857:c3:m0
|
@cached_property<EOL><INDENT>def script_root(self):<DEDENT>
|
path = wsgi_decoding_dance(self.environ.get('<STR_LIT>') or '<STR_LIT>',<EOL>self.charset, self.encoding_errors)<EOL>return path.rstrip('<STR_LIT:/>') + '<STR_LIT:/>'<EOL>
|
The root path of the script includling a trailing slash.
|
f5857:c3:m1
|
def unknown_charset(self, charset):
|
return '<STR_LIT>'<EOL>
|
Called if a charset was provided but is not supported by
the Python codecs module. By default latin1 is assumed then
to not lose any information, you may override this method to
change the behavior.
:param charset: the charset that was not found.
:return: the replacement charset.
|
f5857:c4:m0
|
@cached_property<EOL><INDENT>def charset(self):<DEDENT>
|
header = self.environ.get('<STR_LIT>')<EOL>if header:<EOL><INDENT>ct, options = parse_options_header(header)<EOL>charset = options.get('<STR_LIT>')<EOL>if charset:<EOL><INDENT>if is_known_charset(charset):<EOL><INDENT>return charset<EOL><DEDENT>return self.unknown_charset(charset)<EOL><DEDENT><DEDENT>return self.default_charset<EOL>
|
The charset from the content type.
|
f5857:c4:m1
|
def xml(self):
|
if '<STR_LIT>' not in self.mimetype:<EOL><INDENT>raise AttributeError(<EOL>'<STR_LIT>'<EOL>% self.mimetype)<EOL><DEDENT>for module in ['<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>']:<EOL><INDENT>etree = import_string(module, silent=True)<EOL>if etree is not None:<EOL><INDENT>return etree.XML(self.body)<EOL><DEDENT><DEDENT>raise RuntimeError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>
|
Get an etree if possible.
|
f5858:c0:m0
|
def lxml(self):
|
if ('<STR_LIT:html>' not in self.mimetype and '<STR_LIT>' not in self.mimetype):<EOL><INDENT>raise AttributeError('<STR_LIT>')<EOL><DEDENT>from lxml import etree<EOL>try:<EOL><INDENT>from lxml.html import fromstring<EOL><DEDENT>except ImportError:<EOL><INDENT>fromstring = etree.HTML<EOL><DEDENT>if self.mimetype=='<STR_LIT>':<EOL><INDENT>return fromstring(self.data)<EOL><DEDENT>return etree.XML(self.data)<EOL>
|
Get an lxml etree if possible.
|
f5858:c0:m1
|
def json(self):
|
if '<STR_LIT>' not in self.mimetype:<EOL><INDENT>raise AttributeError('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>from simplejson import loads<EOL><DEDENT>except ImportError:<EOL><INDENT>from json import loads<EOL><DEDENT>return loads(self.data)<EOL>
|
Get the result of simplejson.loads if possible.
|
f5858:c0:m2
|
def _mixed_join(iterable, sentinel):
|
iterator = iter(iterable)<EOL>first_item = next(iterator, sentinel)<EOL>if isinstance(first_item, bytes):<EOL><INDENT>return first_item + b'<STR_LIT>'.join(iterator)<EOL><DEDENT>return first_item + u'<STR_LIT>'.join(iterator)<EOL>
|
concatenate any string type in an intelligent way.
|
f5859:m0
|
def _buf_append(self, string):
|
if not self._buf:<EOL><INDENT>self._buf = string<EOL><DEDENT>else:<EOL><INDENT>self._buf += string<EOL><DEDENT>
|
Replace string directly without appending to an empty string,
avoiding type issues.
|
f5859:c2:m2
|
def get_remote_addr(self, forwarded_for):
|
if len(forwarded_for) >= self.num_proxies:<EOL><INDENT>return forwarded_for[<NUM_LIT:0>]<EOL><DEDENT>
|
Selects the new remote addr from the given list of ips in
X-Forwarded-For. By default it picks the one that the `num_proxies`
proxy server provides. Before 0.9 it would always pick the first.
.. versionadded:: 0.8
|
f5861:c2:m1
|
def make_action(app_factory, hostname='<STR_LIT:localhost>', port=<NUM_LIT>,<EOL>threaded=False, processes=<NUM_LIT:1>, stream=None,<EOL>sort_by=('<STR_LIT:time>', '<STR_LIT>'), restrictions=()):
|
def action(hostname=('<STR_LIT:h>', hostname), port=('<STR_LIT:p>', port),<EOL>threaded=threaded, processes=processes):<EOL><INDENT>"""<STR_LIT>"""<EOL>from werkzeug.serving import run_simple<EOL>app = ProfilerMiddleware(app_factory(), stream, sort_by, restrictions)<EOL>run_simple(hostname, port, app, False, None, threaded, processes)<EOL><DEDENT>return action<EOL>
|
Return a new callback for :mod:`werkzeug.script` that starts a local
server with the profiler enabled.
::
from werkzeug.contrib import profiler
action_profile = profiler.make_action(make_app)
|
f5863:m0
|
def processed(self):
|
Called after pos has changed for threshold or a line was read.
|
f5864:c0:m1
|
|
def copy(self):
|
missing = object()<EOL>result = object.__new__(self.__class__)<EOL>for name in self.__slots__:<EOL><INDENT>val = getattr(self, name, missing)<EOL>if val is not missing:<EOL><INDENT>setattr(result, name, val)<EOL><DEDENT><DEDENT>return result<EOL>
|
Create a flat copy of the dict.
|
f5865:c0:m1
|
@property<EOL><INDENT>def should_save(self):<DEDENT>
|
return self.modified<EOL>
|
True if the session should be saved.
.. versionchanged:: 0.6
By default the session is now only saved if the session is
modified, not if it is new like it was before.
|
f5865:c1:m2
|
def is_valid_key(self, key):
|
return _sha1_re.match(key) is not None<EOL>
|
Check if a key has the correct format.
|
f5865:c2:m1
|
def generate_key(self, salt=None):
|
return generate_key(salt)<EOL>
|
Simple function that generates a new session key.
|
f5865:c2:m2
|
def new(self):
|
return self.session_class({}, self.generate_key(), True)<EOL>
|
Generate a new session.
|
f5865:c2:m3
|
def save(self, session):
|
Save a session.
|
f5865:c2:m4
|
|
def save_if_modified(self, session):
|
if session.should_save:<EOL><INDENT>self.save(session)<EOL><DEDENT>
|
Save if a session class wants an update.
|
f5865:c2:m5
|
def delete(self, session):
|
Delete a session.
|
f5865:c2:m6
|
|
def get(self, sid):
|
return self.session_class({}, sid, True)<EOL>
|
Get a session for this sid or a new session object. This method
has to check if the session key is valid and create a new session if
that wasn't the case.
|
f5865:c2:m7
|
def list(self):
|
before, after = self.filename_template.split('<STR_LIT:%s>', <NUM_LIT:1>)<EOL>filename_re = re.compile(r'<STR_LIT>' % (re.escape(before),<EOL>re.escape(after)))<EOL>result = []<EOL>for filename in os.listdir(self.path):<EOL><INDENT>if filename.endswith(_fs_transaction_suffix):<EOL><INDENT>continue<EOL><DEDENT>match = filename_re.match(filename)<EOL>if match is not None:<EOL><INDENT>result.append(match.group(<NUM_LIT:1>))<EOL><DEDENT><DEDENT>return result<EOL>
|
Lists all sessions in the store.
.. versionadded:: 0.6
|
f5865:c3:m5
|
@property<EOL><INDENT>def should_save(self):<DEDENT>
|
return self.modified<EOL>
|
True if the session should be saved. By default this is only true
for :attr:`modified` cookies, not :attr:`new`.
|
f5866:c1:m2
|
@classmethod<EOL><INDENT>def quote(cls, value):<DEDENT>
|
if cls.serialization_method is not None:<EOL><INDENT>value = cls.serialization_method.dumps(value)<EOL><DEDENT>if cls.quote_base64:<EOL><INDENT>value = b'<STR_LIT>'.join(base64.b64encode(value).splitlines()).strip()<EOL><DEDENT>return value<EOL>
|
Quote the value for the cookie. This can be any object supported
by :attr:`serialization_method`.
:param value: the value to quote.
|
f5866:c1:m3
|
@classmethod<EOL><INDENT>def unquote(cls, value):<DEDENT>
|
try:<EOL><INDENT>if cls.quote_base64:<EOL><INDENT>value = base64.b64decode(value)<EOL><DEDENT>if cls.serialization_method is not None:<EOL><INDENT>value = cls.serialization_method.loads(value)<EOL><DEDENT>return value<EOL><DEDENT>except Exception:<EOL><INDENT>raise UnquoteError()<EOL><DEDENT>
|
Unquote the value for the cookie. If unquoting does not work a
:exc:`UnquoteError` is raised.
:param value: the value to unquote.
|
f5866:c1:m4
|
def serialize(self, expires=None):
|
if self.secret_key is None:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>if expires:<EOL><INDENT>self['<STR_LIT>'] = _date_to_unix(expires)<EOL><DEDENT>result = []<EOL>mac = hmac(self.secret_key, None, self.hash_method)<EOL>for key, value in sorted(self.items()):<EOL><INDENT>result.append(('<STR_LIT>' % (<EOL>url_quote_plus(key),<EOL>self.quote(value).decode('<STR_LIT:ascii>')<EOL>)).encode('<STR_LIT:ascii>'))<EOL>mac.update(b'<STR_LIT:|>' + result[-<NUM_LIT:1>])<EOL><DEDENT>return b'<STR_LIT:?>'.join([<EOL>base64.b64encode(mac.digest()).strip(),<EOL>b'<STR_LIT:&>'.join(result)<EOL>])<EOL>
|
Serialize the secure cookie into a string.
If expires is provided, the session will be automatically invalidated
after expiration when you unseralize it. This provides better
protection against session cookie theft.
:param expires: an optional expiration date for the cookie (a
:class:`datetime.datetime` object)
|
f5866:c1:m5
|
@classmethod<EOL><INDENT>def unserialize(cls, string, secret_key):<DEDENT>
|
if isinstance(string, text_type):<EOL><INDENT>string = string.encode('<STR_LIT:utf-8>', '<STR_LIT:replace>')<EOL><DEDENT>if isinstance(secret_key, text_type):<EOL><INDENT>secret_key = secret_key.encode('<STR_LIT:utf-8>', '<STR_LIT:replace>')<EOL><DEDENT>try:<EOL><INDENT>base64_hash, data = string.split(b'<STR_LIT:?>', <NUM_LIT:1>)<EOL><DEDENT>except (ValueError, IndexError):<EOL><INDENT>items = ()<EOL><DEDENT>else:<EOL><INDENT>items = {}<EOL>mac = hmac(secret_key, None, cls.hash_method)<EOL>for item in data.split(b'<STR_LIT:&>'):<EOL><INDENT>mac.update(b'<STR_LIT:|>' + item)<EOL>if not b'<STR_LIT:=>' in item:<EOL><INDENT>items = None<EOL>break<EOL><DEDENT>key, value = item.split(b'<STR_LIT:=>', <NUM_LIT:1>)<EOL>key = url_unquote_plus(key.decode('<STR_LIT:ascii>'))<EOL>try:<EOL><INDENT>key = to_native(key)<EOL><DEDENT>except UnicodeError:<EOL><INDENT>pass<EOL><DEDENT>items[key] = value<EOL><DEDENT>try:<EOL><INDENT>client_hash = base64.b64decode(base64_hash)<EOL><DEDENT>except TypeError:<EOL><INDENT>items = client_hash = None<EOL><DEDENT>if items is not None and safe_str_cmp(client_hash, mac.digest()):<EOL><INDENT>try:<EOL><INDENT>for key, value in iteritems(items):<EOL><INDENT>items[key] = cls.unquote(value)<EOL><DEDENT><DEDENT>except UnquoteError:<EOL><INDENT>items = ()<EOL><DEDENT>else:<EOL><INDENT>if '<STR_LIT>' in items:<EOL><INDENT>if time() > items['<STR_LIT>']:<EOL><INDENT>items = ()<EOL><DEDENT>else:<EOL><INDENT>del items['<STR_LIT>']<EOL><DEDENT><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>items = ()<EOL><DEDENT><DEDENT>return cls(items, secret_key, False)<EOL>
|
Load the secure cookie from a serialized string.
:param string: the cookie value to unserialize.
:param secret_key: the secret key used to serialize the cookie.
:return: a new :class:`SecureCookie`.
|
f5866:c1:m6
|
@classmethod<EOL><INDENT>def load_cookie(cls, request, key='<STR_LIT>', secret_key=None):<DEDENT>
|
data = request.cookies.get(key)<EOL>if not data:<EOL><INDENT>return cls(secret_key=secret_key)<EOL><DEDENT>return cls.unserialize(data, secret_key)<EOL>
|
Loads a :class:`SecureCookie` from a cookie in request. If the
cookie is not set, a new :class:`SecureCookie` instanced is
returned.
:param request: a request object that has a `cookies` attribute
which is a dict of all cookie values.
:param key: the name of the cookie.
:param secret_key: the secret key used to unquote the cookie.
Always provide the value even though it has
no default!
|
f5866:c1:m7
|
def save_cookie(self, response, key='<STR_LIT>', expires=None,<EOL>session_expires=None, max_age=None, path='<STR_LIT:/>', domain=None,<EOL>secure=None, httponly=False, force=False):
|
if force or self.should_save:<EOL><INDENT>data = self.serialize(session_expires or expires)<EOL>response.set_cookie(key, data, expires=expires, max_age=max_age,<EOL>path=path, domain=domain, secure=secure,<EOL>httponly=httponly)<EOL><DEDENT>
|
Saves the SecureCookie in a cookie on response object. All
parameters that are not described here are forwarded directly
to :meth:`~BaseResponse.set_cookie`.
:param response: a response object that has a
:meth:`~BaseResponse.set_cookie` method.
:param key: the name of the cookie.
:param session_expires: the expiration date of the secure cookie
stored information. If this is not provided
the cookie `expires` date is used instead.
|
f5866:c1:m8
|
def make_ssl_devcert(base_path, host=None, cn=None):
|
from OpenSSL import crypto<EOL>if host is not None:<EOL><INDENT>cn = '<STR_LIT>' % (host, host)<EOL><DEDENT>cert, pkey = generate_adhoc_ssl_pair(cn=cn)<EOL>cert_file = base_path + '<STR_LIT>'<EOL>pkey_file = base_path + '<STR_LIT>'<EOL>with open(cert_file, '<STR_LIT:w>') as f:<EOL><INDENT>f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))<EOL><DEDENT>with open(pkey_file, '<STR_LIT:w>') as f:<EOL><INDENT>f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))<EOL><DEDENT>return cert_file, pkey_file<EOL>
|
Creates an SSL key for development. This should be used instead of
the ``'adhoc'`` key which generates a new cert on each server start.
It accepts a path for where it should store the key and cert and
either a host or CN. If a host is given it will use the CN
``*.host/CN=host``.
For more information see :func:`run_simple`.
.. versionadded:: 0.9
:param base_path: the path to the certificate and key. The extension
``.crt`` is added for the certificate, ``.key`` is
added for the key.
:param host: the name of the host. This can be used as an alternative
for the `cn`.
:param cn: the `CN` to use.
|
f5867:m1
|
def generate_adhoc_ssl_context():
|
from OpenSSL import SSL<EOL>cert, pkey = generate_adhoc_ssl_pair()<EOL>ctx = SSL.Context(SSL.SSLv23_METHOD)<EOL>ctx.use_privatekey(pkey)<EOL>ctx.use_certificate(cert)<EOL>return ctx<EOL>
|
Generates an adhoc SSL context for the development server.
|
f5867:m2
|
def load_ssl_context(cert_file, pkey_file):
|
from OpenSSL import SSL<EOL>ctx = SSL.Context(SSL.SSLv23_METHOD)<EOL>ctx.use_certificate_file(cert_file)<EOL>ctx.use_privatekey_file(pkey_file)<EOL>return ctx<EOL>
|
Loads an SSL context from a certificate and private key file.
|
f5867:m3
|
def is_ssl_error(error=None):
|
if error is None:<EOL><INDENT>error = sys.exc_info()[<NUM_LIT:1>]<EOL><DEDENT>from OpenSSL import SSL<EOL>return isinstance(error, SSL.Error)<EOL>
|
Checks if the given error (or the current one) is an SSL error.
|
f5867:m4
|
def select_ip_version(host, port):
|
<EOL>if '<STR_LIT::>' in host and hasattr(socket, '<STR_LIT>'):<EOL><INDENT>return socket.AF_INET6<EOL><DEDENT>return socket.AF_INET<EOL>
|
Returns AF_INET4 or AF_INET6 depending on where to connect to.
|
f5867:m5
|
def make_server(host, port, app=None, threaded=False, processes=<NUM_LIT:1>,<EOL>request_handler=None, passthrough_errors=False,<EOL>ssl_context=None):
|
if threaded and processes > <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>elif threaded:<EOL><INDENT>return ThreadedWSGIServer(host, port, app, request_handler,<EOL>passthrough_errors, ssl_context)<EOL><DEDENT>elif processes > <NUM_LIT:1>:<EOL><INDENT>return ForkingWSGIServer(host, port, app, processes, request_handler,<EOL>passthrough_errors, ssl_context)<EOL><DEDENT>else:<EOL><INDENT>return BaseWSGIServer(host, port, app, request_handler,<EOL>passthrough_errors, ssl_context)<EOL><DEDENT>
|
Create a new server instance that is either threaded, or forks
or just processes one request after another.
|
f5867:m6
|
def _reloader_stat_loop(extra_files=None, interval=<NUM_LIT:1>):
|
from itertools import chain<EOL>mtimes = {}<EOL>while <NUM_LIT:1>:<EOL><INDENT>for filename in chain(_iter_module_files(), extra_files or ()):<EOL><INDENT>try:<EOL><INDENT>mtime = os.stat(filename).st_mtime<EOL><DEDENT>except OSError:<EOL><INDENT>continue<EOL><DEDENT>old_time = mtimes.get(filename)<EOL>if old_time is None:<EOL><INDENT>mtimes[filename] = mtime<EOL>continue<EOL><DEDENT>elif mtime > old_time:<EOL><INDENT>_log('<STR_LIT:info>', '<STR_LIT>' % filename)<EOL>sys.exit(<NUM_LIT:3>)<EOL><DEDENT><DEDENT>time.sleep(interval)<EOL><DEDENT>
|
When this function is run from the main thread, it will force other
threads to exit when any modules currently loaded change.
Copyright notice. This function is based on the autoreload.py from
the CherryPy trac which originated from WSGIKit which is now dead.
:param extra_files: a list of additional files it should watch.
|
f5867:m8
|
def restart_with_reloader():
|
while <NUM_LIT:1>:<EOL><INDENT>_log('<STR_LIT:info>', '<STR_LIT>')<EOL>if sys.argv[<NUM_LIT:0>].endswith('<STR_LIT>') or sys.argv[<NUM_LIT:0>].endswith('<STR_LIT>'):<EOL><INDENT>args = [sys.executable] + sys.argv<EOL><DEDENT>else:<EOL><INDENT>args = sys.argv<EOL><DEDENT>new_environ = os.environ.copy()<EOL>new_environ['<STR_LIT>'] = '<STR_LIT:true>'<EOL>if os.name == '<STR_LIT>' and PY2:<EOL><INDENT>for key, value in iteritems(new_environ):<EOL><INDENT>if isinstance(value, text_type):<EOL><INDENT>new_environ[key] = value.encode('<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>exit_code = subprocess.call(args, env=new_environ)<EOL>if exit_code != <NUM_LIT:3>:<EOL><INDENT>return exit_code<EOL><DEDENT><DEDENT>
|
Spawn a new Python interpreter with the same arguments as this one,
but running the reloader thread.
|
f5867:m10
|
def run_with_reloader(main_func, extra_files=None, interval=<NUM_LIT:1>):
|
import signal<EOL>signal.signal(signal.SIGTERM, lambda *args: sys.exit(<NUM_LIT:0>))<EOL>if os.environ.get('<STR_LIT>') == '<STR_LIT:true>':<EOL><INDENT>thread.start_new_thread(main_func, ())<EOL>try:<EOL><INDENT>reloader_loop(extra_files, interval)<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>return<EOL><DEDENT><DEDENT>try:<EOL><INDENT>sys.exit(restart_with_reloader())<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>pass<EOL><DEDENT>
|
Run the given function in an independent python interpreter.
|
f5867:m11
|
def run_simple(hostname, port, application, use_reloader=False,<EOL>use_debugger=False, use_evalex=True,<EOL>extra_files=None, reloader_interval=<NUM_LIT:1>, threaded=False,<EOL>processes=<NUM_LIT:1>, request_handler=None, static_files=None,<EOL>passthrough_errors=False, ssl_context=None):
|
if use_debugger:<EOL><INDENT>from werkzeug.debug import DebuggedApplication<EOL>application = DebuggedApplication(application, use_evalex)<EOL><DEDENT>if static_files:<EOL><INDENT>from werkzeug.wsgi import SharedDataMiddleware<EOL>application = SharedDataMiddleware(application, static_files)<EOL><DEDENT>def inner():<EOL><INDENT>make_server(hostname, port, application, threaded,<EOL>processes, request_handler,<EOL>passthrough_errors, ssl_context).serve_forever()<EOL><DEDENT>if os.environ.get('<STR_LIT>') != '<STR_LIT:true>':<EOL><INDENT>display_hostname = hostname != '<STR_LIT:*>' and hostname or '<STR_LIT:localhost>'<EOL>if '<STR_LIT::>' in display_hostname:<EOL><INDENT>display_hostname = '<STR_LIT>' % display_hostname<EOL><DEDENT>_log('<STR_LIT:info>', '<STR_LIT>', ssl_context is None<EOL>and '<STR_LIT:http>' or '<STR_LIT>', display_hostname, port)<EOL><DEDENT>if use_reloader:<EOL><INDENT>address_family = select_ip_version(hostname, port)<EOL>test_socket = socket.socket(address_family, socket.SOCK_STREAM)<EOL>test_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, <NUM_LIT:1>)<EOL>test_socket.bind((hostname, port))<EOL>test_socket.close()<EOL>run_with_reloader(inner, extra_files, reloader_interval)<EOL><DEDENT>else:<EOL><INDENT>inner()<EOL><DEDENT>
|
Start an application using wsgiref and with an optional reloader. This
wraps `wsgiref` to fix the wrong default reporting of the multithreaded
WSGI variable and adds optional multithreading and fork support.
This function has a command-line interface too::
python -m werkzeug.serving --help
.. versionadded:: 0.5
`static_files` was added to simplify serving of static files as well
as `passthrough_errors`.
.. versionadded:: 0.6
support for SSL was added.
.. versionadded:: 0.8
Added support for automatically loading a SSL context from certificate
file and private key.
.. versionadded:: 0.9
Added command-line interface.
:param hostname: The host for the application. eg: ``'localhost'``
:param port: The port for the server. eg: ``8080``
:param application: the WSGI application to execute
:param use_reloader: should the server automatically restart the python
process if modules were changed?
:param use_debugger: should the werkzeug debugging system be used?
:param use_evalex: should the exception evaluation feature be enabled?
:param extra_files: a list of files the reloader should watch
additionally to the modules. For example configuration
files.
:param reloader_interval: the interval for the reloader in seconds.
:param threaded: should the process handle each request in a separate
thread?
:param processes: if greater than 1 then handle each request in a new process
up to this maximum number of concurrent processes.
:param request_handler: optional parameter that can be used to replace
the default one. You can use this to replace it
with a different
:class:`~BaseHTTPServer.BaseHTTPRequestHandler`
subclass.
:param static_files: a dict of paths for static files. This works exactly
like :class:`SharedDataMiddleware`, it's actually
just wrapping the application in that middleware before
serving.
:param passthrough_errors: set this to `True` to disable the error catching.
This means that the server will die on errors but
it can be useful to hook debuggers in (pdb etc.)
:param ssl_context: an SSL context for the connection. Either an OpenSSL
context, a tuple in the form ``(cert_file, pkey_file)``,
the string ``'adhoc'`` if the server should
automatically create one, or `None` to disable SSL
(which is the default).
|
f5867:m12
|
def main():
|
<EOL>import optparse<EOL>from werkzeug.utils import import_string<EOL>parser = optparse.OptionParser(usage='<STR_LIT>')<EOL>parser.add_option('<STR_LIT>', '<STR_LIT>', dest='<STR_LIT:address>',<EOL>help='<STR_LIT>')<EOL>parser.add_option('<STR_LIT>', '<STR_LIT>', dest='<STR_LIT>',<EOL>action='<STR_LIT:store_true>', default=False,<EOL>help='<STR_LIT>')<EOL>parser.add_option('<STR_LIT>', '<STR_LIT>', dest='<STR_LIT>',<EOL>action='<STR_LIT:store_true>', default=False,<EOL>help='<STR_LIT>')<EOL>options, args = parser.parse_args()<EOL>hostname, port = None, None<EOL>if options.address:<EOL><INDENT>address = options.address.split('<STR_LIT::>')<EOL>hostname = address[<NUM_LIT:0>]<EOL>if len(address) > <NUM_LIT:1>:<EOL><INDENT>port = address[<NUM_LIT:1>]<EOL><DEDENT><DEDENT>if len(args) != <NUM_LIT:1>:<EOL><INDENT>sys.stdout.write('<STR_LIT>')<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT>app = import_string(args[<NUM_LIT:0>])<EOL>run_simple(<EOL>hostname=(hostname or '<STR_LIT:127.0.0.1>'), port=int(port or <NUM_LIT>),<EOL>application=app, use_reloader=options.use_reloader,<EOL>use_debugger=options.use_debugger<EOL>)<EOL>
|
A simple command-line interface for :py:func:`run_simple`.
|
f5867:m13
|
def handle(self):
|
rv = None<EOL>try:<EOL><INDENT>rv = BaseHTTPRequestHandler.handle(self)<EOL><DEDENT>except (socket.error, socket.timeout) as e:<EOL><INDENT>self.connection_dropped(e)<EOL><DEDENT>except Exception:<EOL><INDENT>if self.server.ssl_context is None or not is_ssl_error():<EOL><INDENT>raise<EOL><DEDENT><DEDENT>if self.server.shutdown_signal:<EOL><INDENT>self.initiate_shutdown()<EOL><DEDENT>return rv<EOL>
|
Handles a request ignoring dropped connections.
|
f5867:c0:m3
|
def initiate_shutdown(self):
|
<EOL>sig = getattr(signal, '<STR_LIT>', signal.SIGTERM)<EOL>if os.environ.get('<STR_LIT>') == '<STR_LIT:true>':<EOL><INDENT>os.kill(os.getpid(), sig)<EOL><DEDENT>self.server._BaseServer__shutdown_request = True<EOL>self.server._BaseServer__serving = False<EOL>
|
A horrible, horrible way to kill the server for Python 2.6 and
later. It's the best we can do.
|
f5867:c0:m4
|
def connection_dropped(self, error, environ=None):
|
Called if the connection was closed by the client. By default
nothing happens.
|
f5867:c0:m5
|
|
def handle_one_request(self):
|
self.raw_requestline = self.rfile.readline()<EOL>if not self.raw_requestline:<EOL><INDENT>self.close_connection = <NUM_LIT:1><EOL><DEDENT>elif self.parse_request():<EOL><INDENT>return self.run_wsgi()<EOL><DEDENT>
|
Handle a single HTTP request.
|
f5867:c0:m6
|
def send_response(self, code, message=None):
|
self.log_request(code)<EOL>if message is None:<EOL><INDENT>message = code in self.responses and self.responses[code][<NUM_LIT:0>] or '<STR_LIT>'<EOL><DEDENT>if self.request_version != '<STR_LIT>':<EOL><INDENT>hdr = "<STR_LIT>" % (self.protocol_version, code, message)<EOL>self.wfile.write(hdr.encode('<STR_LIT:ascii>'))<EOL><DEDENT>
|
Send the response header and log the response code.
|
f5867:c0:m7
|
@classmethod<EOL><INDENT>def from_file(cls, file, charset='<STR_LIT:utf-8>', errors='<STR_LIT:strict>',<EOL>unicode_mode=True):<DEDENT>
|
close = False<EOL>f = file<EOL>if isinstance(file, str):<EOL><INDENT>f = open(file, '<STR_LIT:r>')<EOL>close = True<EOL><DEDENT>try:<EOL><INDENT>data = _decode_unicode(f.read(), charset, errors)<EOL><DEDENT>finally:<EOL><INDENT>if close:<EOL><INDENT>f.close()<EOL><DEDENT><DEDENT>return cls(data, getattr(f, '<STR_LIT:name>', '<STR_LIT>'), charset,<EOL>errors, unicode_mode)<EOL>
|
Load a template from a file.
.. versionchanged:: 0.5
The encoding parameter was renamed to charset.
:param file: a filename or file object to load the template from.
:param charset: the charset of the template to load.
:param errors: the error behavior of the charset decoding.
:param unicode_mode: set to `False` to disable unicode mode.
:return: a template
|
f5868:c4:m1
|
def render(self, *args, **kwargs):
|
ns = self.default_context.copy()<EOL>if len(args) == <NUM_LIT:1> and isinstance(args[<NUM_LIT:0>], MultiDict):<EOL><INDENT>ns.update(args[<NUM_LIT:0>].to_dict(flat=True))<EOL><DEDENT>else:<EOL><INDENT>ns.update(dict(*args))<EOL><DEDENT>if kwargs:<EOL><INDENT>ns.update(kwargs)<EOL><DEDENT>context = Context(ns, self.charset, self.errors)<EOL>exec(self.code, context.runtime, context)<EOL>return context.get_value(self.unicode_mode)<EOL>
|
This function accepts either a dict or some keyword arguments which
will then be the context the template is evaluated in. The return
value will be the rendered template.
:param context: the function accepts the same arguments as the
:class:`dict` constructor.
:return: the rendered template as string
|
f5868:c4:m2
|
def substitute(self, *args, **kwargs):
|
return self.render(*args, **kwargs)<EOL>
|
For API compatibility with `string.Template`.
|
f5868:c4:m3
|
def get_uid():
|
return str(random()).encode('<STR_LIT>')[<NUM_LIT:3>:<NUM_LIT:11>]<EOL>
|
Return a random unique ID.
|
f5869:m0
|
def highlight_python(source):
|
parser = PythonParser(source)<EOL>parser.parse()<EOL>return parser.get_html_output()<EOL>
|
Highlight some python code. Return a list of lines
|
f5869:m1
|
def get_frame_info(tb, context_lines=<NUM_LIT:7>, simple=False):
|
<EOL>lineno = tb.tb_lineno<EOL>function = tb.tb_frame.f_code.co_name<EOL>variables = tb.tb_frame.f_locals<EOL>files = {}<EOL>if simple:<EOL><INDENT>fn = tb.tb_frame.f_code.co_filename<EOL><DEDENT>else:<EOL><INDENT>fn = tb.tb_frame.f_globals.get('<STR_LIT>')<EOL>if not fn:<EOL><INDENT>fn = os.path.realpath(inspect.getsourcefile(tb) or<EOL>inspect.getfile(tb))<EOL><DEDENT>if fn[-<NUM_LIT:4>:] in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>fn = fn[:-<NUM_LIT:1>]<EOL><DEDENT><DEDENT>loader = None<EOL>if not os.path.exists(fn):<EOL><INDENT>loader = tb.tb_frame.f_globals.get('<STR_LIT>')<EOL>while not loader and tb.tb_next:<EOL><INDENT>tb = tb.tb_next<EOL>loader = tb.tb_frame.f_globals.get('<STR_LIT>')<EOL><DEDENT><DEDENT>source = '<STR_LIT>'<EOL>pre_context, post_context = [], []<EOL>context_line = raw_context_line = context_lineno = None<EOL>try:<EOL><INDENT>if loader:<EOL><INDENT>source = loader.get_source(fn)<EOL><DEDENT>else:<EOL><INDENT>if not fn in files:<EOL><INDENT>source = open(fn).read()<EOL>files[fn] = source<EOL><DEDENT>else:<EOL><INDENT>source = files[fn]<EOL><DEDENT><DEDENT><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>raw_context_line = source.splitlines()[lineno - <NUM_LIT:1>].strip()<EOL><DEDENT>except IndexError:<EOL><INDENT>pass<EOL><DEDENT>if not simple:<EOL><INDENT>parsed_source = highlight_python(source)<EOL>lbound = max(<NUM_LIT:0>, lineno - context_lines - <NUM_LIT:1>)<EOL>ubound = lineno + context_lines<EOL>try:<EOL><INDENT>context_line = parsed_source[lineno - <NUM_LIT:1>]<EOL>pre_context = parsed_source[lbound:lineno - <NUM_LIT:1>]<EOL>post_context = parsed_source[lineno:ubound]<EOL><DEDENT>except IndexError as e:<EOL><INDENT>pass<EOL><DEDENT>context_lineno = lbound<EOL><DEDENT><DEDENT>if isinstance(fn, str):<EOL><INDENT>fn = fn.encode('<STR_LIT:utf-8>')<EOL><DEDENT>return {<EOL>'<STR_LIT>': tb,<EOL>'<STR_LIT:filename>': fn,<EOL>'<STR_LIT>': os.path.basename(fn),<EOL>'<STR_LIT>': loader,<EOL>'<STR_LIT>': function,<EOL>'<STR_LIT>': lineno,<EOL>'<STR_LIT>': variables,<EOL>'<STR_LIT>': pre_context,<EOL>'<STR_LIT>': context_line,<EOL>'<STR_LIT>': raw_context_line,<EOL>'<STR_LIT>': post_context,<EOL>'<STR_LIT>': context_lineno,<EOL>'<STR_LIT:source>': source<EOL>}<EOL>
|
Return a dict of information about a given traceback.
|
f5869:m2
|
def get_html_output(self):
|
def html_splitlines(lines):<EOL><INDENT>open_tag_re = re.compile(r'<STR_LIT>')<EOL>close_tag_re = re.compile(r'<STR_LIT>')<EOL>open_tags = []<EOL>for line in lines:<EOL><INDENT>for tag in open_tags:<EOL><INDENT>line = tag.group(<NUM_LIT:0>) + line<EOL><DEDENT>open_tags = []<EOL>for tag in open_tag_re.finditer(line):<EOL><INDENT>open_tags.append(tag)<EOL><DEDENT>open_tags.reverse()<EOL>for ctag in close_tag_re.finditer(line):<EOL><INDENT>for otag in open_tags:<EOL><INDENT>if otag.group(<NUM_LIT:1>) == ctag.group(<NUM_LIT:1>):<EOL><INDENT>open_tags.remove(otag)<EOL>break<EOL><DEDENT><DEDENT><DEDENT>for tag in open_tags:<EOL><INDENT>line += '<STR_LIT>' % tag.group(<NUM_LIT:1>)<EOL><DEDENT>yield line<EOL><DEDENT><DEDENT>if self.error:<EOL><INDENT>return escape(self.raw).splitlines()<EOL><DEDENT>return list(html_splitlines(self.out.getvalue().splitlines()))<EOL>
|
Return line generator.
|
f5869:c3:m2
|
def format_exception(self, exc_info):
|
return self.create_debug_context({<EOL>'<STR_LIT>': True<EOL>}, exc_info, True).plaintb + '<STR_LIT:\n>'<EOL>
|
Format a text/plain traceback.
|
f5871:c0:m2
|
def get_current_traceback(ignore_system_exceptions=False):
|
exc_type, exc_value, tb = sys.exc_info()<EOL>if ignore_system_exceptions and exc_type in system_exceptions:<EOL><INDENT>raise<EOL><DEDENT>return Traceback(exc_type, exc_value, tb)<EOL>
|
Get the current exception info as `Traceback` object. Per default
calling this method will reraise system exceptions such as generator exit,
system exit or others. This behavior can be disabled by passing `False`
to the function as first parameter.
|
f5872:m0
|
def parse_rule(rule):
|
pos = <NUM_LIT:0><EOL>end = len(rule)<EOL>do_match = _rule_re.match<EOL>used_names = set()<EOL>while pos < end:<EOL><INDENT>m = do_match(rule, pos)<EOL>if m is None:<EOL><INDENT>break<EOL><DEDENT>data = m.groupdict()<EOL>if data['<STR_LIT>']:<EOL><INDENT>yield None, None, data['<STR_LIT>']<EOL><DEDENT>variable = data['<STR_LIT>']<EOL>converter = data['<STR_LIT>'] or '<STR_LIT:default>'<EOL>if variable in used_names:<EOL><INDENT>raise ValueError('<STR_LIT>' % variable)<EOL><DEDENT>used_names.add(variable)<EOL>yield converter, data['<STR_LIT:args>'] or None, variable<EOL>pos = m.end()<EOL><DEDENT>if pos < end:<EOL><INDENT>remaining = rule[pos:]<EOL>if '<STR_LIT:>>' in remaining or '<STR_LIT:<>' in remaining:<EOL><INDENT>raise ValueError('<STR_LIT>' % rule)<EOL><DEDENT>yield None, None, remaining<EOL><DEDENT>
|
Parse a rule and return it as generator. Each iteration yields tuples
in the form ``(converter, arguments, variable)``. If the converter is
`None` it's a static url part, otherwise it's a dynamic one.
:internal:
|
f5873:m2
|
def get_rules(self, map):
|
raise NotImplementedError()<EOL>
|
Subclasses of `RuleFactory` have to override this method and return
an iterable of rules.
|
f5873:c6:m0
|
def empty(self):
|
defaults = None<EOL>if self.defaults:<EOL><INDENT>defaults = dict(self.defaults)<EOL><DEDENT>return Rule(self.rule, defaults, self.subdomain, self.methods,<EOL>self.build_only, self.endpoint, self.strict_slashes,<EOL>self.redirect_to, self.alias, self.host)<EOL>
|
Return an unbound copy of this rule. This can be useful if you
want to reuse an already bound URL for another map.
|
f5873:c12:m1
|
def refresh(self):
|
self.bind(self.map, rebind=True)<EOL>
|
Rebinds and refreshes the URL. Call this if you modified the
rule in place.
:internal:
|
f5873:c12:m3
|
def bind(self, map, rebind=False):
|
if self.map is not None and not rebind:<EOL><INDENT>raise RuntimeError('<STR_LIT>' %<EOL>(self, self.map))<EOL><DEDENT>self.map = map<EOL>if self.strict_slashes is None:<EOL><INDENT>self.strict_slashes = map.strict_slashes<EOL><DEDENT>if self.subdomain is None:<EOL><INDENT>self.subdomain = map.default_subdomain<EOL><DEDENT>self.compile()<EOL>
|
Bind the url to a map and create a regular expression based on
the information from the rule itself and the defaults from the map.
:internal:
|
f5873:c12:m4
|
def get_converter(self, variable_name, converter_name, args, kwargs):
|
if not converter_name in self.map.converters:<EOL><INDENT>raise LookupError('<STR_LIT>' % converter_name)<EOL><DEDENT>return self.map.converters[converter_name](self.map, *args, **kwargs)<EOL>
|
Looks up the converter for the given parameter.
.. versionadded:: 0.9
|
f5873:c12:m5
|
def compile(self):
|
assert self.map is not None, '<STR_LIT>'<EOL>if self.map.host_matching:<EOL><INDENT>domain_rule = self.host or '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>domain_rule = self.subdomain or '<STR_LIT>'<EOL><DEDENT>self._trace = []<EOL>self._converters = {}<EOL>self._weights = []<EOL>regex_parts = []<EOL>def _build_regex(rule):<EOL><INDENT>for converter, arguments, variable in parse_rule(rule):<EOL><INDENT>if converter is None:<EOL><INDENT>regex_parts.append(re.escape(variable))<EOL>self._trace.append((False, variable))<EOL>for part in variable.split('<STR_LIT:/>'):<EOL><INDENT>if part:<EOL><INDENT>self._weights.append((<NUM_LIT:0>, -len(part)))<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>if arguments:<EOL><INDENT>c_args, c_kwargs = parse_converter_args(arguments)<EOL><DEDENT>else:<EOL><INDENT>c_args = ()<EOL>c_kwargs = {}<EOL><DEDENT>convobj = self.get_converter(<EOL>variable, converter, c_args, c_kwargs)<EOL>regex_parts.append('<STR_LIT>' % (variable, convobj.regex))<EOL>self._converters[variable] = convobj<EOL>self._trace.append((True, variable))<EOL>self._weights.append((<NUM_LIT:1>, convobj.weight))<EOL>self.arguments.add(str(variable))<EOL><DEDENT><DEDENT><DEDENT>_build_regex(domain_rule)<EOL>regex_parts.append('<STR_LIT>')<EOL>self._trace.append((False, '<STR_LIT:|>'))<EOL>_build_regex(self.is_leaf and self.rule or self.rule.rstrip('<STR_LIT:/>'))<EOL>if not self.is_leaf:<EOL><INDENT>self._trace.append((False, '<STR_LIT:/>'))<EOL><DEDENT>if self.build_only:<EOL><INDENT>return<EOL><DEDENT>regex = r'<STR_LIT>' % (<EOL>u'<STR_LIT>'.join(regex_parts),<EOL>(not self.is_leaf or not self.strict_slashes) and'<STR_LIT>' or '<STR_LIT>'<EOL>)<EOL>self._regex = re.compile(regex, re.UNICODE)<EOL>
|
Compiles the regular expression and stores it.
|
f5873:c12:m6
|
def match(self, path):
|
if not self.build_only:<EOL><INDENT>m = self._regex.search(path)<EOL>if m is not None:<EOL><INDENT>groups = m.groupdict()<EOL>if self.strict_slashes and not self.is_leaf andnot groups.pop('<STR_LIT>'):<EOL><INDENT>raise RequestSlash()<EOL><DEDENT>elif not self.strict_slashes:<EOL><INDENT>del groups['<STR_LIT>']<EOL><DEDENT>result = {}<EOL>for name, value in iteritems(groups):<EOL><INDENT>try:<EOL><INDENT>value = self._converters[name].to_python(value)<EOL><DEDENT>except ValidationError:<EOL><INDENT>return<EOL><DEDENT>result[str(name)] = value<EOL><DEDENT>if self.defaults:<EOL><INDENT>result.update(self.defaults)<EOL><DEDENT>if self.alias and self.map.redirect_defaults:<EOL><INDENT>raise RequestAliasRedirect(result)<EOL><DEDENT>return result<EOL><DEDENT><DEDENT>
|
Check if the rule matches a given path. Path is a string in the
form ``"subdomain|/path(method)"`` and is assembled by the map. If
the map is doing host matching the subdomain part will be the host
instead.
If the rule matches a dict with the converted values is returned,
otherwise the return value is `None`.
:internal:
|
f5873:c12:m7
|
def build(self, values, append_unknown=True):
|
tmp = []<EOL>add = tmp.append<EOL>processed = set(self.arguments)<EOL>for is_dynamic, data in self._trace:<EOL><INDENT>if is_dynamic:<EOL><INDENT>try:<EOL><INDENT>add(self._converters[data].to_url(values[data]))<EOL><DEDENT>except ValidationError:<EOL><INDENT>return<EOL><DEDENT>processed.add(data)<EOL><DEDENT>else:<EOL><INDENT>add(url_quote(to_bytes(data, self.map.charset), safe='<STR_LIT>'))<EOL><DEDENT><DEDENT>domain_part, url = (u'<STR_LIT>'.join(tmp)).split(u'<STR_LIT:|>', <NUM_LIT:1>)<EOL>if append_unknown:<EOL><INDENT>query_vars = MultiDict(values)<EOL>for key in processed:<EOL><INDENT>if key in query_vars:<EOL><INDENT>del query_vars[key]<EOL><DEDENT><DEDENT>if query_vars:<EOL><INDENT>url += u'<STR_LIT:?>' + url_encode(query_vars, charset=self.map.charset,<EOL>sort=self.map.sort_parameters,<EOL>key=self.map.sort_key)<EOL><DEDENT><DEDENT>return domain_part, url<EOL>
|
Assembles the relative url for that rule and the subdomain.
If building doesn't work for some reasons `None` is returned.
:internal:
|
f5873:c12:m8
|
def provides_defaults_for(self, rule):
|
return not self.build_only and self.defaults andself.endpoint == rule.endpoint and self != rule andself.arguments == rule.arguments<EOL>
|
Check if this rule has defaults for a given rule.
:internal:
|
f5873:c12:m9
|
def suitable_for(self, values, method=None):
|
<EOL>if method is not None and self.methods is not Noneand method not in self.methods:<EOL><INDENT>return False<EOL><DEDENT>defaults = self.defaults or ()<EOL>for key in self.arguments:<EOL><INDENT>if key not in defaults and key not in values:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>if defaults:<EOL><INDENT>for key, value in iteritems(defaults):<EOL><INDENT>if key in values and value != values[key]:<EOL><INDENT>return False<EOL><DEDENT><DEDENT><DEDENT>return True<EOL>
|
Check if the dict of values has enough data for url generation.
:internal:
|
f5873:c12:m10
|
def match_compare_key(self):
|
return bool(self.arguments), -len(self._weights), self._weights<EOL>
|
The match compare key for sorting.
Current implementation:
1. rules without any arguments come first for performance
reasons only as we expect them to match faster and some
common ones usually don't have any arguments (index pages etc.)
2. The more complex rules come first so the second argument is the
negative length of the number of weights.
3. lastly we order by the actual weights.
:internal:
|
f5873:c12:m11
|
def build_compare_key(self):
|
return self.alias and <NUM_LIT:1> or <NUM_LIT:0>, -len(self.arguments),-len(self.defaults or ())<EOL>
|
The build compare key for sorting.
:internal:
|
f5873:c12:m12
|
def is_endpoint_expecting(self, endpoint, *arguments):
|
self.update()<EOL>arguments = set(arguments)<EOL>for rule in self._rules_by_endpoint[endpoint]:<EOL><INDENT>if arguments.issubset(rule.arguments):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>
|
Iterate over all rules and check if the endpoint expects
the arguments provided. This is for example useful if you have
some URLs that expect a language code and others that do not and
you want to wrap the builder a bit so that the current language
code is automatically added if not provided but endpoints expect
it.
:param endpoint: the endpoint to check.
:param arguments: this function accepts one or more arguments
as positional arguments. Each one of them is
checked.
|
f5873:c20:m1
|
def iter_rules(self, endpoint=None):
|
self.update()<EOL>if endpoint is not None:<EOL><INDENT>return iter(self._rules_by_endpoint[endpoint])<EOL><DEDENT>return iter(self._rules)<EOL>
|
Iterate over all rules or the rules of an endpoint.
:param endpoint: if provided only the rules for that endpoint
are returned.
:return: an iterator
|
f5873:c20:m2
|
def add(self, rulefactory):
|
for rule in rulefactory.get_rules(self):<EOL><INDENT>rule.bind(self)<EOL>self._rules.append(rule)<EOL>self._rules_by_endpoint.setdefault(rule.endpoint, []).append(rule)<EOL><DEDENT>self._remap = True<EOL>
|
Add a new rule or factory to the map and bind it. Requires that the
rule is not bound to another map.
:param rulefactory: a :class:`Rule` or :class:`RuleFactory`
|
f5873:c20:m3
|
def bind(self, server_name, script_name=None, subdomain=None,<EOL>url_scheme='<STR_LIT:http>', default_method='<STR_LIT:GET>', path_info=None,<EOL>query_args=None):
|
server_name = server_name.lower()<EOL>if self.host_matching:<EOL><INDENT>if subdomain is not None:<EOL><INDENT>raise RuntimeError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT>elif subdomain is None:<EOL><INDENT>subdomain = self.default_subdomain<EOL><DEDENT>if script_name is None:<EOL><INDENT>script_name = '<STR_LIT:/>'<EOL><DEDENT>server_name = _encode_idna(server_name)<EOL>return MapAdapter(self, server_name, script_name, subdomain,<EOL>url_scheme, path_info, default_method, query_args)<EOL>
|
Return a new :class:`MapAdapter` with the details specified to the
call. Note that `script_name` will default to ``'/'`` if not further
specified or `None`. The `server_name` at least is a requirement
because the HTTP RFC requires absolute URLs for redirects and so all
redirect exceptions raised by Werkzeug will contain the full canonical
URL.
If no path_info is passed to :meth:`match` it will use the default path
info passed to bind. While this doesn't really make sense for
manual bind calls, it's useful if you bind a map to a WSGI
environment which already contains the path info.
`subdomain` will default to the `default_subdomain` for this map if
no defined. If there is no `default_subdomain` you cannot use the
subdomain feature.
.. versionadded:: 0.7
`query_args` added
.. versionadded:: 0.8
`query_args` can now also be a string.
|
f5873:c20:m4
|
def bind_to_environ(self, environ, server_name=None, subdomain=None):
|
environ = _get_environ(environ)<EOL>if server_name is None:<EOL><INDENT>if '<STR_LIT>' in environ:<EOL><INDENT>server_name = environ['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>server_name = environ['<STR_LIT>']<EOL>if (environ['<STR_LIT>'], environ['<STR_LIT>']) notin (('<STR_LIT>', '<STR_LIT>'), ('<STR_LIT:http>', '<STR_LIT>')):<EOL><INDENT>server_name += '<STR_LIT::>' + environ['<STR_LIT>']<EOL><DEDENT><DEDENT><DEDENT>elif subdomain is None and not self.host_matching:<EOL><INDENT>server_name = server_name.lower()<EOL>if '<STR_LIT>' in environ:<EOL><INDENT>wsgi_server_name = environ.get('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>wsgi_server_name = environ.get('<STR_LIT>')<EOL>if (environ['<STR_LIT>'], environ['<STR_LIT>']) notin (('<STR_LIT>', '<STR_LIT>'), ('<STR_LIT:http>', '<STR_LIT>')):<EOL><INDENT>wsgi_server_name += '<STR_LIT::>' + environ['<STR_LIT>']<EOL><DEDENT><DEDENT>wsgi_server_name = wsgi_server_name.lower()<EOL>cur_server_name = wsgi_server_name.split('<STR_LIT:.>')<EOL>real_server_name = server_name.split('<STR_LIT:.>')<EOL>offset = -len(real_server_name)<EOL>if cur_server_name[offset:] != real_server_name:<EOL><INDENT>subdomain = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>subdomain = '<STR_LIT:.>'.join(filter(None, cur_server_name[:offset]))<EOL><DEDENT><DEDENT>def _get_wsgi_string(name):<EOL><INDENT>val = environ.get(name)<EOL>if val is not None:<EOL><INDENT>return wsgi_decoding_dance(val, self.charset)<EOL><DEDENT><DEDENT>script_name = _get_wsgi_string('<STR_LIT>')<EOL>path_info = _get_wsgi_string('<STR_LIT>')<EOL>query_args = _get_wsgi_string('<STR_LIT>')<EOL>return Map.bind(self, server_name, script_name,<EOL>subdomain, environ['<STR_LIT>'],<EOL>environ['<STR_LIT>'], path_info,<EOL>query_args=query_args)<EOL>
|
Like :meth:`bind` but you can pass it an WSGI environment and it
will fetch the information from that dictionary. Note that because of
limitations in the protocol there is no way to get the current
subdomain and real `server_name` from the environment. If you don't
provide it, Werkzeug will use `SERVER_NAME` and `SERVER_PORT` (or
`HTTP_HOST` if provided) as used `server_name` with disabled subdomain
feature.
If `subdomain` is `None` but an environment and a server name is
provided it will calculate the current subdomain automatically.
Example: `server_name` is ``'example.com'`` and the `SERVER_NAME`
in the wsgi `environ` is ``'staging.dev.example.com'`` the calculated
subdomain will be ``'staging.dev'``.
If the object passed as environ has an environ attribute, the value of
this attribute is used instead. This allows you to pass request
objects. Additionally `PATH_INFO` added as a default of the
:class:`MapAdapter` so that you don't have to pass the path info to
the match method.
.. versionchanged:: 0.5
previously this method accepted a bogus `calculate_subdomain`
parameter that did not have any effect. It was removed because
of that.
.. versionchanged:: 0.8
This will no longer raise a ValueError when an unexpected server
name was passed.
:param environ: a WSGI environment.
:param server_name: an optional server name hint (see above).
:param subdomain: optionally the current subdomain (see above).
|
f5873:c20:m5
|
def update(self):
|
if self._remap:<EOL><INDENT>self._rules.sort(key=lambda x: x.match_compare_key())<EOL>for rules in itervalues(self._rules_by_endpoint):<EOL><INDENT>rules.sort(key=lambda x: x.build_compare_key())<EOL><DEDENT>self._remap = False<EOL><DEDENT>
|
Called before matching and building to keep the compiled rules
in the correct order after things changed.
|
f5873:c20:m6
|
def dispatch(self, view_func, path_info=None, method=None,<EOL>catch_http_exceptions=False):
|
try:<EOL><INDENT>try:<EOL><INDENT>endpoint, args = self.match(path_info, method)<EOL><DEDENT>except RequestRedirect as e:<EOL><INDENT>return e<EOL><DEDENT>return view_func(endpoint, args)<EOL><DEDENT>except HTTPException as e:<EOL><INDENT>if catch_http_exceptions:<EOL><INDENT>return e<EOL><DEDENT>raise<EOL><DEDENT>
|
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 caught 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.wrappers import Request, Response
from werkzeug.wsgi import 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.
|
f5873:c21:m1
|
def match(self, path_info=None, method=None, return_rule=False,<EOL>query_args=None):
|
self.map.update()<EOL>if path_info is None:<EOL><INDENT>path_info = self.path_info<EOL><DEDENT>else:<EOL><INDENT>path_info = to_unicode(path_info, self.map.charset)<EOL><DEDENT>if query_args is None:<EOL><INDENT>query_args = self.query_args<EOL><DEDENT>method = (method or self.default_method).upper()<EOL>path = u'<STR_LIT>' % (self.map.host_matching and self.server_name or<EOL>self.subdomain, path_info.lstrip('<STR_LIT:/>'))<EOL>have_match_for = set()<EOL>for rule in self.map._rules:<EOL><INDENT>try:<EOL><INDENT>rv = rule.match(path)<EOL><DEDENT>except RequestSlash:<EOL><INDENT>raise RequestRedirect(self.make_redirect_url(<EOL>path_info + '<STR_LIT:/>', query_args))<EOL><DEDENT>except RequestAliasRedirect as e:<EOL><INDENT>raise RequestRedirect(self.make_alias_redirect_url(<EOL>path, rule.endpoint, e.matched_values, method, query_args))<EOL><DEDENT>if rv is None:<EOL><INDENT>continue<EOL><DEDENT>if rule.methods is not None and method not in rule.methods:<EOL><INDENT>have_match_for.update(rule.methods)<EOL>continue<EOL><DEDENT>if self.map.redirect_defaults:<EOL><INDENT>redirect_url = self.get_default_redirect(rule, method, rv,<EOL>query_args)<EOL>if redirect_url is not None:<EOL><INDENT>raise RequestRedirect(redirect_url)<EOL><DEDENT><DEDENT>if rule.redirect_to is not None:<EOL><INDENT>if isinstance(rule.redirect_to, string_types):<EOL><INDENT>def _handle_match(match):<EOL><INDENT>value = rv[match.group(<NUM_LIT:1>)]<EOL>return rule._converters[match.group(<NUM_LIT:1>)].to_url(value)<EOL><DEDENT>redirect_url = _simple_rule_re.sub(_handle_match,<EOL>rule.redirect_to)<EOL><DEDENT>else:<EOL><INDENT>redirect_url = rule.redirect_to(self, **rv)<EOL><DEDENT>raise RequestRedirect(str(urljoin('<STR_LIT>' % (<EOL>self.url_scheme,<EOL>self.subdomain and self.subdomain + '<STR_LIT:.>' or '<STR_LIT>',<EOL>self.server_name,<EOL>self.script_name<EOL>), redirect_url)))<EOL><DEDENT>if return_rule:<EOL><INDENT>return rule, rv<EOL><DEDENT>else:<EOL><INDENT>return rule.endpoint, rv<EOL><DEDENT><DEDENT>if have_match_for:<EOL><INDENT>raise MethodNotAllowed(valid_methods=list(have_match_for))<EOL><DEDENT>raise NotFound()<EOL>
|
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 not 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 from 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)`` if there is
a match (unless `return_rule` is True, in which case you get a tuple
in the form ``(rule, arguments)``)
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.
:param return_rule: return the rule that matched instead of just the
endpoint (defaults to `False`).
:param query_args: optional query arguments that are used for
automatic redirects as string or dictionary. It's
currently not possible to use the query arguments
for URL matching.
.. versionadded:: 0.6
`return_rule` was added.
.. versionadded:: 0.7
`query_args` was added.
.. versionchanged:: 0.8
`query_args` can now also be a string.
|
f5873:c21:m2
|
def allowed_methods(self, path_info=None):
|
try:<EOL><INDENT>self.match(path_info, method='<STR_LIT>')<EOL><DEDENT>except MethodNotAllowed as e:<EOL><INDENT>return e.valid_methods<EOL><DEDENT>except HTTPException as e:<EOL><INDENT>pass<EOL><DEDENT>return []<EOL>
|
Returns the valid methods that match for a given path.
.. versionadded:: 0.7
|
f5873:c21:m4
|
def get_host(self, domain_part):
|
if self.map.host_matching:<EOL><INDENT>if domain_part is None:<EOL><INDENT>return self.server_name<EOL><DEDENT>return to_unicode(domain_part, '<STR_LIT:ascii>')<EOL><DEDENT>subdomain = domain_part<EOL>if subdomain is None:<EOL><INDENT>subdomain = self.subdomain<EOL><DEDENT>else:<EOL><INDENT>subdomain = to_unicode(subdomain, '<STR_LIT:ascii>')<EOL><DEDENT>return (subdomain and subdomain + u'<STR_LIT:.>' or u'<STR_LIT>') + self.server_name<EOL>
|
Figures out the full host name for the given domain part. The
domain part is a subdomain in case host matching is disabled or
a full host name.
|
f5873:c21:m5
|
def get_default_redirect(self, rule, method, values, query_args):
|
assert self.map.redirect_defaults<EOL>for r in self.map._rules_by_endpoint[rule.endpoint]:<EOL><INDENT>if r is rule:<EOL><INDENT>break<EOL><DEDENT>if r.provides_defaults_for(rule) andr.suitable_for(values, method):<EOL><INDENT>values.update(r.defaults)<EOL>domain_part, path = r.build(values)<EOL>return self.make_redirect_url(<EOL>path, query_args, domain_part=domain_part)<EOL><DEDENT><DEDENT>
|
A helper that returns the URL to redirect to if it finds one.
This is used for default redirecting only.
:internal:
|
f5873:c21:m6
|
def make_redirect_url(self, path_info, query_args=None, domain_part=None):
|
suffix = '<STR_LIT>'<EOL>if query_args:<EOL><INDENT>suffix = '<STR_LIT:?>' + self.encode_query_args(query_args)<EOL><DEDENT>return str('<STR_LIT>' % (<EOL>self.url_scheme,<EOL>self.get_host(domain_part),<EOL>posixpath.join(self.script_name[:-<NUM_LIT:1>].lstrip('<STR_LIT:/>'),<EOL>url_quote(path_info.lstrip('<STR_LIT:/>'), self.map.charset,<EOL>safe='<STR_LIT>')),<EOL>suffix<EOL>))<EOL>
|
Creates a redirect URL.
:internal:
|
f5873:c21:m8
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.