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...
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 da...
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(se...
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...
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 charse...
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.defaul...
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>...
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_...
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, thre...
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 = f...
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>' % (<EO...
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 ...
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:?>', ...
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...
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 ...
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_certificat...
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 informat...
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, ...
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 N...
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 ...
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['...
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><...
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():<EO...
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 ....
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>', def...
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....
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>'))<...
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:na...
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 decodi...
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.char...
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. :...
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.getso...
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):<EO...
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['...
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><DE...
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(rul...
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><DE...
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, other...
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...
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 ke...
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 ...
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 pro...
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_LI...
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 excepti...
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>', '<S...
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...
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 di...
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_...
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 applica...
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(subdo...
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_redire...
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:/...
Creates a redirect URL. :internal:
f5873:c21:m8