├── .gitignore ├── dinp ├── flask │ ├── __init__.py │ ├── app.py │ ├── blueprints.py │ ├── config.py │ ├── ctx.py │ ├── debughelpers.py │ ├── exceptions.py │ ├── ext │ │ └── __init__.py │ ├── exthook.py │ ├── globals.py │ ├── helpers.py │ ├── logging.py │ ├── module.py │ ├── session.py │ ├── sessions.py │ ├── signals.py │ ├── templating.py │ ├── testing.py │ ├── testsuite │ │ ├── __init__.py │ │ ├── appctx.py │ │ ├── basic.py │ │ ├── blueprints.py │ │ ├── config.py │ │ ├── deprecations.py │ │ ├── examples.py │ │ ├── ext.py │ │ ├── helpers.py │ │ ├── regression.py │ │ ├── signals.py │ │ ├── static │ │ │ └── index.html │ │ ├── subclassing.py │ │ ├── templates │ │ │ ├── _macro.html │ │ │ ├── context_template.html │ │ │ ├── escaping_template.html │ │ │ ├── mail.txt │ │ │ ├── nested │ │ │ │ └── nested.txt │ │ │ ├── simple_template.html │ │ │ └── template_filter.html │ │ ├── templating.py │ │ ├── test_apps │ │ │ ├── blueprintapp │ │ │ │ ├── __init__.py │ │ │ │ └── apps │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── admin │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── static │ │ │ │ │ │ ├── css │ │ │ │ │ │ │ └── test.css │ │ │ │ │ │ └── test.txt │ │ │ │ │ └── templates │ │ │ │ │ │ └── admin │ │ │ │ │ │ └── index.html │ │ │ │ │ └── frontend │ │ │ │ │ ├── __init__.py │ │ │ │ │ └── templates │ │ │ │ │ └── frontend │ │ │ │ │ └── index.html │ │ │ ├── config_module_app.py │ │ │ ├── config_package_app │ │ │ │ └── __init__.py │ │ │ ├── flask_broken │ │ │ │ ├── __init__.py │ │ │ │ └── b.py │ │ │ ├── flask_newext_package │ │ │ │ ├── __init__.py │ │ │ │ └── submodule.py │ │ │ ├── flask_newext_simple.py │ │ │ ├── flaskext │ │ │ │ ├── __init__.py │ │ │ │ ├── oldext_package │ │ │ │ │ ├── __init__.py │ │ │ │ │ └── submodule.py │ │ │ │ └── oldext_simple.py │ │ │ ├── importerror.py │ │ │ ├── lib │ │ │ │ └── python2.5 │ │ │ │ │ └── site-packages │ │ │ │ │ ├── SiteEgg.egg │ │ │ │ │ ├── site_app.py │ │ │ │ │ └── site_package │ │ │ │ │ └── __init__.py │ │ │ ├── main_app.py │ │ │ ├── moduleapp │ │ │ │ ├── __init__.py │ │ │ │ └── apps │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── admin │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── static │ │ │ │ │ │ ├── css │ │ │ │ │ │ │ └── test.css │ │ │ │ │ │ └── test.txt │ │ │ │ │ └── templates │ │ │ │ │ │ └── index.html │ │ │ │ │ └── frontend │ │ │ │ │ ├── __init__.py │ │ │ │ │ └── templates │ │ │ │ │ └── index.html │ │ │ ├── path │ │ │ │ └── installed_package │ │ │ │ │ └── __init__.py │ │ │ └── subdomaintestmodule │ │ │ │ ├── __init__.py │ │ │ │ └── static │ │ │ │ └── hello.txt │ │ ├── testing.py │ │ └── views.py │ ├── views.py │ └── wrappers.py ├── jinja2 │ ├── __init__.py │ ├── _debugsupport.c │ ├── _markupsafe │ │ ├── __init__.py │ │ ├── _bundle.py │ │ ├── _constants.py │ │ ├── _native.py │ │ └── tests.py │ ├── _stringdefs.py │ ├── bccache.py │ ├── compiler.py │ ├── constants.py │ ├── debug.py │ ├── defaults.py │ ├── environment.py │ ├── exceptions.py │ ├── ext.py │ ├── filters.py │ ├── lexer.py │ ├── loaders.py │ ├── meta.py │ ├── nodes.py │ ├── optimizer.py │ ├── parser.py │ ├── runtime.py │ ├── sandbox.py │ ├── tests.py │ ├── testsuite │ │ ├── __init__.py │ │ ├── api.py │ │ ├── core_tags.py │ │ ├── debug.py │ │ ├── doctests.py │ │ ├── ext.py │ │ ├── filters.py │ │ ├── imports.py │ │ ├── inheritance.py │ │ ├── lexnparse.py │ │ ├── loader.py │ │ ├── regression.py │ │ ├── res │ │ │ ├── __init__.py │ │ │ └── templates │ │ │ │ ├── broken.html │ │ │ │ ├── foo │ │ │ │ └── test.html │ │ │ │ ├── syntaxerror.html │ │ │ │ └── test.html │ │ ├── security.py │ │ ├── tests.py │ │ └── utils.py │ ├── utils.py │ └── visitor.py └── werkzeug │ ├── __init__.py │ ├── _internal.py │ ├── contrib │ ├── __init__.py │ ├── atom.py │ ├── cache.py │ ├── fixers.py │ ├── iterio.py │ ├── jsrouting.py │ ├── kickstart.py │ ├── limiter.py │ ├── lint.py │ ├── profiler.py │ ├── securecookie.py │ ├── sessions.py │ ├── testtools.py │ └── wrappers.py │ ├── datastructures.py │ ├── debug │ ├── __init__.py │ ├── console.py │ ├── repr.py │ ├── shared │ │ ├── FONT_LICENSE │ │ ├── console.png │ │ ├── debugger.js │ │ ├── jquery.js │ │ ├── less.png │ │ ├── more.png │ │ ├── source.png │ │ ├── style.css │ │ └── ubuntu.ttf │ └── tbtools.py │ ├── exceptions.py │ ├── formparser.py │ ├── http.py │ ├── local.py │ ├── posixemulation.py │ ├── routing.py │ ├── script.py │ ├── security.py │ ├── serving.py │ ├── templates.py │ ├── test.py │ ├── testapp.py │ ├── testsuite │ ├── __init__.py │ ├── compat.py │ ├── contrib │ │ ├── __init__.py │ │ ├── cache.py │ │ ├── fixers.py │ │ ├── iterio.py │ │ ├── securecookie.py │ │ ├── sessions.py │ │ └── wrappers.py │ ├── datastructures.py │ ├── debug.py │ ├── exceptions.py │ ├── formparser.py │ ├── http.py │ ├── internal.py │ ├── local.py │ ├── multipart │ │ ├── collect.py │ │ ├── firefox3-2png1txt │ │ │ ├── file1.png │ │ │ ├── file2.png │ │ │ ├── request.txt │ │ │ └── text.txt │ │ ├── firefox3-2pnglongtext │ │ │ ├── file1.png │ │ │ ├── file2.png │ │ │ ├── request.txt │ │ │ └── text.txt │ │ ├── ie6-2png1txt │ │ │ ├── file1.png │ │ │ ├── file2.png │ │ │ ├── request.txt │ │ │ └── text.txt │ │ ├── ie7_full_path_request.txt │ │ ├── opera8-2png1txt │ │ │ ├── file1.png │ │ │ ├── file2.png │ │ │ ├── request.txt │ │ │ └── text.txt │ │ └── webkit3-2png1txt │ │ │ ├── file1.png │ │ │ ├── file2.png │ │ │ ├── request.txt │ │ │ └── text.txt │ ├── res │ │ └── test.txt │ ├── routing.py │ ├── security.py │ ├── serving.py │ ├── test.py │ ├── urls.py │ ├── utils.py │ ├── wrappers.py │ └── wsgi.py │ ├── urls.py │ ├── useragents.py │ ├── utils.py │ ├── wrappers.py │ └── wsgi.py └── wsgi.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | *.swo 3 | *.pyc 4 | *.bak 5 | *.log 6 | *~ 7 | env 8 | nohup.out 9 | -------------------------------------------------------------------------------- /dinp/flask/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask 4 | ~~~~~ 5 | 6 | A microframework based on Werkzeug. It's extensively documented 7 | and follows best practice patterns. 8 | 9 | :copyright: (c) 2011 by Armin Ronacher. 10 | :license: BSD, see LICENSE for more details. 11 | """ 12 | 13 | __version__ = '0.9' 14 | 15 | # utilities we import from Werkzeug and Jinja2 that are unused 16 | # in the module but are exported as public interface. 17 | from werkzeug.exceptions import abort 18 | from werkzeug.utils import redirect 19 | from jinja2 import Markup, escape 20 | 21 | from .app import Flask, Request, Response 22 | from .config import Config 23 | from .helpers import url_for, jsonify, json_available, flash, \ 24 | send_file, send_from_directory, get_flashed_messages, \ 25 | get_template_attribute, make_response, safe_join, \ 26 | stream_with_context 27 | from .globals import current_app, g, request, session, _request_ctx_stack, \ 28 | _app_ctx_stack 29 | from .ctx import has_request_context, has_app_context, \ 30 | after_this_request 31 | from .module import Module 32 | from .blueprints import Blueprint 33 | from .templating import render_template, render_template_string 34 | 35 | # the signals 36 | from .signals import signals_available, template_rendered, request_started, \ 37 | request_finished, got_request_exception, request_tearing_down 38 | 39 | # only import json if it's available 40 | if json_available: 41 | from .helpers import json 42 | 43 | # backwards compat, goes away in 1.0 44 | from .sessions import SecureCookieSession as Session 45 | -------------------------------------------------------------------------------- /dinp/flask/debughelpers.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.debughelpers 4 | ~~~~~~~~~~~~~~~~~~ 5 | 6 | Various helpers to make the development experience better. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | 12 | 13 | class DebugFilesKeyError(KeyError, AssertionError): 14 | """Raised from request.files during debugging. The idea is that it can 15 | provide a better error message than just a generic KeyError/BadRequest. 16 | """ 17 | 18 | def __init__(self, request, key): 19 | form_matches = request.form.getlist(key) 20 | buf = ['You tried to access the file "%s" in the request.files ' 21 | 'dictionary but it does not exist. The mimetype for the request ' 22 | 'is "%s" instead of "multipart/form-data" which means that no ' 23 | 'file contents were transmitted. To fix this error you should ' 24 | 'provide enctype="multipart/form-data" in your form.' % 25 | (key, request.mimetype)] 26 | if form_matches: 27 | buf.append('\n\nThe browser instead transmitted some file names. ' 28 | 'This was submitted: %s' % ', '.join('"%s"' % x 29 | for x in form_matches)) 30 | self.msg = ''.join(buf).encode('utf-8') 31 | 32 | def __str__(self): 33 | return self.msg 34 | 35 | 36 | class FormDataRoutingRedirect(AssertionError): 37 | """This exception is raised by Flask in debug mode if it detects a 38 | redirect caused by the routing system when the request method is not 39 | GET, HEAD or OPTIONS. Reasoning: form data will be dropped. 40 | """ 41 | 42 | def __init__(self, request): 43 | exc = request.routing_exception 44 | buf = ['A request was sent to this URL (%s) but a redirect was ' 45 | 'issued automatically by the routing system to "%s".' 46 | % (request.url, exc.new_url)] 47 | 48 | # In case just a slash was appended we can be extra helpful 49 | if request.base_url + '/' == exc.new_url.split('?')[0]: 50 | buf.append(' The URL was defined with a trailing slash so ' 51 | 'Flask will automatically redirect to the URL ' 52 | 'with the trailing slash if it was accessed ' 53 | 'without one.') 54 | 55 | buf.append(' Make sure to directly send your %s-request to this URL ' 56 | 'since we can\'t make browsers or HTTP clients redirect ' 57 | 'with form data reliably or without user interaction.' % 58 | request.method) 59 | buf.append('\n\nNote: this exception is only raised in debug mode') 60 | AssertionError.__init__(self, ''.join(buf).encode('utf-8')) 61 | 62 | 63 | def attach_enctype_error_multidict(request): 64 | """Since Flask 0.8 we're monkeypatching the files object in case a 65 | request is detected that does not use multipart form data but the files 66 | object is accessed. 67 | """ 68 | oldcls = request.files.__class__ 69 | class newcls(oldcls): 70 | def __getitem__(self, key): 71 | try: 72 | return oldcls.__getitem__(self, key) 73 | except KeyError, e: 74 | if key not in request.form: 75 | raise 76 | raise DebugFilesKeyError(request, key) 77 | newcls.__name__ = oldcls.__name__ 78 | newcls.__module__ = oldcls.__module__ 79 | request.files.__class__ = newcls 80 | -------------------------------------------------------------------------------- /dinp/flask/exceptions.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.exceptions 4 | ~~~~~~~~~~~~ 5 | 6 | Flask specific additions to :class:`~werkzeug.exceptions.HTTPException` 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | from werkzeug.exceptions import HTTPException, BadRequest 12 | from .helpers import json 13 | 14 | 15 | class JSONHTTPException(HTTPException): 16 | """A base class for HTTP exceptions with ``Content-Type: 17 | application/json``. 18 | 19 | The ``description`` attribute of this class must set to a string (*not* an 20 | HTML string) which describes the error. 21 | 22 | """ 23 | 24 | def get_body(self, environ): 25 | """Overrides :meth:`werkzeug.exceptions.HTTPException.get_body` to 26 | return the description of this error in JSON format instead of HTML. 27 | 28 | """ 29 | return json.dumps(dict(description=self.get_description(environ))) 30 | 31 | def get_headers(self, environ): 32 | """Returns a list of headers including ``Content-Type: 33 | application/json``. 34 | 35 | """ 36 | return [('Content-Type', 'application/json')] 37 | 38 | 39 | class JSONBadRequest(JSONHTTPException, BadRequest): 40 | """Represents an HTTP ``400 Bad Request`` error whose body contains an 41 | error message in JSON format instead of HTML format (as in the superclass). 42 | 43 | """ 44 | 45 | #: The description of the error which occurred as a string. 46 | description = ( 47 | 'The browser (or proxy) sent a request that this server could not ' 48 | 'understand.' 49 | ) 50 | -------------------------------------------------------------------------------- /dinp/flask/ext/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.ext 4 | ~~~~~~~~~ 5 | 6 | Redirect imports for extensions. This module basically makes it possible 7 | for us to transition from flaskext.foo to flask_foo without having to 8 | force all extensions to upgrade at the same time. 9 | 10 | When a user does ``from flask.ext.foo import bar`` it will attempt to 11 | import ``from flask_foo import bar`` first and when that fails it will 12 | try to import ``from flaskext.foo import bar``. 13 | 14 | We're switching from namespace packages because it was just too painful for 15 | everybody involved. 16 | 17 | :copyright: (c) 2011 by Armin Ronacher. 18 | :license: BSD, see LICENSE for more details. 19 | """ 20 | 21 | 22 | def setup(): 23 | from ..exthook import ExtensionImporter 24 | importer = ExtensionImporter(['flask_%s', 'flaskext.%s'], __name__) 25 | importer.install() 26 | 27 | 28 | setup() 29 | del setup 30 | -------------------------------------------------------------------------------- /dinp/flask/exthook.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.exthook 4 | ~~~~~~~~~~~~~ 5 | 6 | Redirect imports for extensions. This module basically makes it possible 7 | for us to transition from flaskext.foo to flask_foo without having to 8 | force all extensions to upgrade at the same time. 9 | 10 | When a user does ``from flask.ext.foo import bar`` it will attempt to 11 | import ``from flask_foo import bar`` first and when that fails it will 12 | try to import ``from flaskext.foo import bar``. 13 | 14 | We're switching from namespace packages because it was just too painful for 15 | everybody involved. 16 | 17 | This is used by `flask.ext`. 18 | 19 | :copyright: (c) 2011 by Armin Ronacher. 20 | :license: BSD, see LICENSE for more details. 21 | """ 22 | import sys 23 | import os 24 | 25 | 26 | class ExtensionImporter(object): 27 | """This importer redirects imports from this submodule to other locations. 28 | This makes it possible to transition from the old flaskext.name to the 29 | newer flask_name without people having a hard time. 30 | """ 31 | 32 | def __init__(self, module_choices, wrapper_module): 33 | self.module_choices = module_choices 34 | self.wrapper_module = wrapper_module 35 | self.prefix = wrapper_module + '.' 36 | self.prefix_cutoff = wrapper_module.count('.') + 1 37 | 38 | def __eq__(self, other): 39 | return self.__class__.__module__ == other.__class__.__module__ and \ 40 | self.__class__.__name__ == other.__class__.__name__ and \ 41 | self.wrapper_module == other.wrapper_module and \ 42 | self.module_choices == other.module_choices 43 | 44 | def __ne__(self, other): 45 | return not self.__eq__(other) 46 | 47 | def install(self): 48 | sys.meta_path[:] = [x for x in sys.meta_path if self != x] + [self] 49 | 50 | def find_module(self, fullname, path=None): 51 | if fullname.startswith(self.prefix): 52 | return self 53 | 54 | def load_module(self, fullname): 55 | if fullname in sys.modules: 56 | return sys.modules[fullname] 57 | modname = fullname.split('.', self.prefix_cutoff)[self.prefix_cutoff] 58 | for path in self.module_choices: 59 | realname = path % modname 60 | try: 61 | __import__(realname) 62 | except ImportError: 63 | exc_type, exc_value, tb = sys.exc_info() 64 | # since we only establish the entry in sys.modules at the 65 | # very this seems to be redundant, but if recursive imports 66 | # happen we will call into the move import a second time. 67 | # On the second invocation we still don't have an entry for 68 | # fullname in sys.modules, but we will end up with the same 69 | # fake module name and that import will succeed since this 70 | # one already has a temporary entry in the modules dict. 71 | # Since this one "succeeded" temporarily that second 72 | # invocation now will have created a fullname entry in 73 | # sys.modules which we have to kill. 74 | sys.modules.pop(fullname, None) 75 | 76 | # If it's an important traceback we reraise it, otherwise 77 | # we swallow it and try the next choice. The skipped frame 78 | # is the one from __import__ above which we don't care about 79 | if self.is_important_traceback(realname, tb): 80 | raise exc_type, exc_value, tb.tb_next 81 | continue 82 | module = sys.modules[fullname] = sys.modules[realname] 83 | if '.' not in modname: 84 | setattr(sys.modules[self.wrapper_module], modname, module) 85 | return module 86 | raise ImportError('No module named %s' % fullname) 87 | 88 | def is_important_traceback(self, important_module, tb): 89 | """Walks a traceback's frames and checks if any of the frames 90 | originated in the given important module. If that is the case then we 91 | were able to import the module itself but apparently something went 92 | wrong when the module was imported. (Eg: import of an import failed). 93 | """ 94 | while tb is not None: 95 | if self.is_important_frame(important_module, tb): 96 | return True 97 | tb = tb.tb_next 98 | return False 99 | 100 | def is_important_frame(self, important_module, tb): 101 | """Checks a single frame if it's important.""" 102 | g = tb.tb_frame.f_globals 103 | if '__name__' not in g: 104 | return False 105 | 106 | module_name = g['__name__'] 107 | 108 | # Python 2.7 Behavior. Modules are cleaned up late so the 109 | # name shows up properly here. Success! 110 | if module_name == important_module: 111 | return True 112 | 113 | # Some python verisons will will clean up modules so early that the 114 | # module name at that point is no longer set. Try guessing from 115 | # the filename then. 116 | filename = os.path.abspath(tb.tb_frame.f_code.co_filename) 117 | test_string = os.path.sep + important_module.replace('.', os.path.sep) 118 | return test_string + '.py' in filename or \ 119 | test_string + os.path.sep + '__init__.py' in filename 120 | -------------------------------------------------------------------------------- /dinp/flask/globals.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.globals 4 | ~~~~~~~~~~~~~ 5 | 6 | Defines all the global objects that are proxies to the current 7 | active context. 8 | 9 | :copyright: (c) 2011 by Armin Ronacher. 10 | :license: BSD, see LICENSE for more details. 11 | """ 12 | 13 | from functools import partial 14 | from werkzeug.local import LocalStack, LocalProxy 15 | 16 | def _lookup_object(name): 17 | top = _request_ctx_stack.top 18 | if top is None: 19 | raise RuntimeError('working outside of request context') 20 | return getattr(top, name) 21 | 22 | 23 | def _find_app(): 24 | top = _app_ctx_stack.top 25 | if top is None: 26 | raise RuntimeError('working outside of application context') 27 | return top.app 28 | 29 | 30 | # context locals 31 | _request_ctx_stack = LocalStack() 32 | _app_ctx_stack = LocalStack() 33 | current_app = LocalProxy(_find_app) 34 | request = LocalProxy(partial(_lookup_object, 'request')) 35 | session = LocalProxy(partial(_lookup_object, 'session')) 36 | g = LocalProxy(partial(_lookup_object, 'g')) 37 | -------------------------------------------------------------------------------- /dinp/flask/logging.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.logging 4 | ~~~~~~~~~~~~~ 5 | 6 | Implements the logging support for Flask. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | 12 | from __future__ import absolute_import 13 | 14 | from logging import getLogger, StreamHandler, Formatter, getLoggerClass, DEBUG 15 | 16 | 17 | def create_logger(app): 18 | """Creates a logger for the given application. This logger works 19 | similar to a regular Python logger but changes the effective logging 20 | level based on the application's debug flag. Furthermore this 21 | function also removes all attached handlers in case there was a 22 | logger with the log name before. 23 | """ 24 | Logger = getLoggerClass() 25 | 26 | class DebugLogger(Logger): 27 | def getEffectiveLevel(x): 28 | if x.level == 0 and app.debug: 29 | return DEBUG 30 | return Logger.getEffectiveLevel(x) 31 | 32 | class DebugHandler(StreamHandler): 33 | def emit(x, record): 34 | StreamHandler.emit(x, record) if app.debug else None 35 | 36 | handler = DebugHandler() 37 | handler.setLevel(DEBUG) 38 | handler.setFormatter(Formatter(app.debug_log_format)) 39 | logger = getLogger(app.logger_name) 40 | # just in case that was not a new logger, get rid of all the handlers 41 | # already attached to it. 42 | del logger.handlers[:] 43 | logger.__class__ = DebugLogger 44 | logger.addHandler(handler) 45 | return logger 46 | -------------------------------------------------------------------------------- /dinp/flask/module.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.module 4 | ~~~~~~~~~~~~ 5 | 6 | Implements a class that represents module blueprints. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | 12 | import os 13 | 14 | from .blueprints import Blueprint 15 | 16 | 17 | def blueprint_is_module(bp): 18 | """Used to figure out if something is actually a module""" 19 | return isinstance(bp, Module) 20 | 21 | 22 | class Module(Blueprint): 23 | """Deprecated module support. Until Flask 0.6 modules were a different 24 | name of the concept now available as blueprints in Flask. They are 25 | essentially doing the same but have some bad semantics for templates and 26 | static files that were fixed with blueprints. 27 | 28 | .. versionchanged:: 0.7 29 | Modules were deprecated in favor for blueprints. 30 | """ 31 | 32 | def __init__(self, import_name, name=None, url_prefix=None, 33 | static_path=None, subdomain=None): 34 | if name is None: 35 | assert '.' in import_name, 'name required if package name ' \ 36 | 'does not point to a submodule' 37 | name = import_name.rsplit('.', 1)[1] 38 | Blueprint.__init__(self, name, import_name, url_prefix=url_prefix, 39 | subdomain=subdomain, template_folder='templates') 40 | 41 | if os.path.isdir(os.path.join(self.root_path, 'static')): 42 | self._static_folder = 'static' 43 | -------------------------------------------------------------------------------- /dinp/flask/session.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.session 4 | ~~~~~~~~~~~~~ 5 | 6 | This module used to flask with the session global so we moved it 7 | over to flask.sessions 8 | 9 | :copyright: (c) 2011 by Armin Ronacher. 10 | :license: BSD, see LICENSE for more details. 11 | """ 12 | 13 | from warnings import warn 14 | warn(DeprecationWarning('please use flask.sessions instead')) 15 | 16 | from .sessions import SecureCookieSession, NullSession 17 | 18 | Session = SecureCookieSession 19 | _NullSession = NullSession 20 | -------------------------------------------------------------------------------- /dinp/flask/signals.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.signals 4 | ~~~~~~~~~~~~~ 5 | 6 | Implements signals based on blinker if available, otherwise 7 | falls silently back to a noop 8 | 9 | :copyright: (c) 2011 by Armin Ronacher. 10 | :license: BSD, see LICENSE for more details. 11 | """ 12 | signals_available = False 13 | try: 14 | from blinker import Namespace 15 | signals_available = True 16 | except ImportError: 17 | class Namespace(object): 18 | def signal(self, name, doc=None): 19 | return _FakeSignal(name, doc) 20 | 21 | class _FakeSignal(object): 22 | """If blinker is unavailable, create a fake class with the same 23 | interface that allows sending of signals but will fail with an 24 | error on anything else. Instead of doing anything on send, it 25 | will just ignore the arguments and do nothing instead. 26 | """ 27 | 28 | def __init__(self, name, doc=None): 29 | self.name = name 30 | self.__doc__ = doc 31 | def _fail(self, *args, **kwargs): 32 | raise RuntimeError('signalling support is unavailable ' 33 | 'because the blinker library is ' 34 | 'not installed.') 35 | send = lambda *a, **kw: None 36 | connect = disconnect = has_receivers_for = receivers_for = \ 37 | temporarily_connected_to = connected_to = _fail 38 | del _fail 39 | 40 | # the namespace for code signals. If you are not flask code, do 41 | # not put signals in here. Create your own namespace instead. 42 | _signals = Namespace() 43 | 44 | 45 | # core signals. For usage examples grep the sourcecode or consult 46 | # the API documentation in docs/api.rst as well as docs/signals.rst 47 | template_rendered = _signals.signal('template-rendered') 48 | request_started = _signals.signal('request-started') 49 | request_finished = _signals.signal('request-finished') 50 | request_tearing_down = _signals.signal('request-tearing-down') 51 | got_request_exception = _signals.signal('got-request-exception') 52 | appcontext_tearing_down = _signals.signal('appcontext-tearing-down') 53 | -------------------------------------------------------------------------------- /dinp/flask/templating.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.templating 4 | ~~~~~~~~~~~~~~~~ 5 | 6 | Implements the bridge to Jinja2. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import posixpath 12 | from jinja2 import BaseLoader, Environment as BaseEnvironment, \ 13 | TemplateNotFound 14 | 15 | from .globals import _request_ctx_stack 16 | from .signals import template_rendered 17 | from .module import blueprint_is_module 18 | 19 | 20 | def _default_template_ctx_processor(): 21 | """Default template context processor. Injects `request`, 22 | `session` and `g`. 23 | """ 24 | reqctx = _request_ctx_stack.top 25 | return dict( 26 | config=reqctx.app.config, 27 | request=reqctx.request, 28 | session=reqctx.session, 29 | g=reqctx.g 30 | ) 31 | 32 | 33 | class Environment(BaseEnvironment): 34 | """Works like a regular Jinja2 environment but has some additional 35 | knowledge of how Flask's blueprint works so that it can prepend the 36 | name of the blueprint to referenced templates if necessary. 37 | """ 38 | 39 | def __init__(self, app, **options): 40 | if 'loader' not in options: 41 | options['loader'] = app.create_global_jinja_loader() 42 | BaseEnvironment.__init__(self, **options) 43 | self.app = app 44 | 45 | 46 | class DispatchingJinjaLoader(BaseLoader): 47 | """A loader that looks for templates in the application and all 48 | the blueprint folders. 49 | """ 50 | 51 | def __init__(self, app): 52 | self.app = app 53 | 54 | def get_source(self, environment, template): 55 | for loader, local_name in self._iter_loaders(template): 56 | try: 57 | return loader.get_source(environment, local_name) 58 | except TemplateNotFound: 59 | pass 60 | 61 | raise TemplateNotFound(template) 62 | 63 | def _iter_loaders(self, template): 64 | loader = self.app.jinja_loader 65 | if loader is not None: 66 | yield loader, template 67 | 68 | # old style module based loaders in case we are dealing with a 69 | # blueprint that is an old style module 70 | try: 71 | module, local_name = posixpath.normpath(template).split('/', 1) 72 | blueprint = self.app.blueprints[module] 73 | if blueprint_is_module(blueprint): 74 | loader = blueprint.jinja_loader 75 | if loader is not None: 76 | yield loader, local_name 77 | except (ValueError, KeyError): 78 | pass 79 | 80 | for blueprint in self.app.blueprints.itervalues(): 81 | if blueprint_is_module(blueprint): 82 | continue 83 | loader = blueprint.jinja_loader 84 | if loader is not None: 85 | yield loader, template 86 | 87 | def list_templates(self): 88 | result = set() 89 | loader = self.app.jinja_loader 90 | if loader is not None: 91 | result.update(loader.list_templates()) 92 | 93 | for name, blueprint in self.app.blueprints.iteritems(): 94 | loader = blueprint.jinja_loader 95 | if loader is not None: 96 | for template in loader.list_templates(): 97 | prefix = '' 98 | if blueprint_is_module(blueprint): 99 | prefix = name + '/' 100 | result.add(prefix + template) 101 | 102 | return list(result) 103 | 104 | 105 | def _render(template, context, app): 106 | """Renders the template and fires the signal""" 107 | rv = template.render(context) 108 | template_rendered.send(app, template=template, context=context) 109 | return rv 110 | 111 | 112 | def render_template(template_name_or_list, **context): 113 | """Renders a template from the template folder with the given 114 | context. 115 | 116 | :param template_name_or_list: the name of the template to be 117 | rendered, or an iterable with template names 118 | the first one existing will be rendered 119 | :param context: the variables that should be available in the 120 | context of the template. 121 | """ 122 | ctx = _request_ctx_stack.top 123 | ctx.app.update_template_context(context) 124 | return _render(ctx.app.jinja_env.get_or_select_template(template_name_or_list), 125 | context, ctx.app) 126 | 127 | 128 | def render_template_string(source, **context): 129 | """Renders a template from the given template source string 130 | with the given context. 131 | 132 | :param template_name: the sourcecode of the template to be 133 | rendered 134 | :param context: the variables that should be available in the 135 | context of the template. 136 | """ 137 | ctx = _request_ctx_stack.top 138 | ctx.app.update_template_context(context) 139 | return _render(ctx.app.jinja_env.from_string(source), 140 | context, ctx.app) 141 | -------------------------------------------------------------------------------- /dinp/flask/testing.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.testing 4 | ~~~~~~~~~~~~~ 5 | 6 | Implements test support helpers. This module is lazily imported 7 | and usually not used in production environments. 8 | 9 | :copyright: (c) 2011 by Armin Ronacher. 10 | :license: BSD, see LICENSE for more details. 11 | """ 12 | 13 | from __future__ import with_statement 14 | 15 | from contextlib import contextmanager 16 | from werkzeug.test import Client, EnvironBuilder 17 | from flask import _request_ctx_stack 18 | 19 | 20 | def make_test_environ_builder(app, path='/', base_url=None, *args, **kwargs): 21 | """Creates a new test builder with some application defaults thrown in.""" 22 | http_host = app.config.get('SERVER_NAME') 23 | app_root = app.config.get('APPLICATION_ROOT') 24 | if base_url is None: 25 | base_url = 'http://%s/' % (http_host or 'localhost') 26 | if app_root: 27 | base_url += app_root.lstrip('/') 28 | return EnvironBuilder(path, base_url, *args, **kwargs) 29 | 30 | 31 | class FlaskClient(Client): 32 | """Works like a regular Werkzeug test client but has some knowledge about 33 | how Flask works to defer the cleanup of the request context stack to the 34 | end of a with body when used in a with statement. For general information 35 | about how to use this class refer to :class:`werkzeug.test.Client`. 36 | 37 | Basic usage is outlined in the :ref:`testing` chapter. 38 | """ 39 | 40 | preserve_context = False 41 | 42 | @contextmanager 43 | def session_transaction(self, *args, **kwargs): 44 | """When used in combination with a with statement this opens a 45 | session transaction. This can be used to modify the session that 46 | the test client uses. Once the with block is left the session is 47 | stored back. 48 | 49 | with client.session_transaction() as session: 50 | session['value'] = 42 51 | 52 | Internally this is implemented by going through a temporary test 53 | request context and since session handling could depend on 54 | request variables this function accepts the same arguments as 55 | :meth:`~flask.Flask.test_request_context` which are directly 56 | passed through. 57 | """ 58 | if self.cookie_jar is None: 59 | raise RuntimeError('Session transactions only make sense ' 60 | 'with cookies enabled.') 61 | app = self.application 62 | environ_overrides = kwargs.setdefault('environ_overrides', {}) 63 | self.cookie_jar.inject_wsgi(environ_overrides) 64 | outer_reqctx = _request_ctx_stack.top 65 | with app.test_request_context(*args, **kwargs) as c: 66 | sess = app.open_session(c.request) 67 | if sess is None: 68 | raise RuntimeError('Session backend did not open a session. ' 69 | 'Check the configuration') 70 | 71 | # Since we have to open a new request context for the session 72 | # handling we want to make sure that we hide out own context 73 | # from the caller. By pushing the original request context 74 | # (or None) on top of this and popping it we get exactly that 75 | # behavior. It's important to not use the push and pop 76 | # methods of the actual request context object since that would 77 | # mean that cleanup handlers are called 78 | _request_ctx_stack.push(outer_reqctx) 79 | try: 80 | yield sess 81 | finally: 82 | _request_ctx_stack.pop() 83 | 84 | resp = app.response_class() 85 | if not app.session_interface.is_null_session(sess): 86 | app.save_session(sess, resp) 87 | headers = resp.get_wsgi_headers(c.request.environ) 88 | self.cookie_jar.extract_wsgi(c.request.environ, headers) 89 | 90 | def open(self, *args, **kwargs): 91 | kwargs.setdefault('environ_overrides', {}) \ 92 | ['flask._preserve_context'] = self.preserve_context 93 | 94 | as_tuple = kwargs.pop('as_tuple', False) 95 | buffered = kwargs.pop('buffered', False) 96 | follow_redirects = kwargs.pop('follow_redirects', False) 97 | builder = make_test_environ_builder(self.application, *args, **kwargs) 98 | 99 | return Client.open(self, builder, 100 | as_tuple=as_tuple, 101 | buffered=buffered, 102 | follow_redirects=follow_redirects) 103 | 104 | def __enter__(self): 105 | if self.preserve_context: 106 | raise RuntimeError('Cannot nest client invocations') 107 | self.preserve_context = True 108 | return self 109 | 110 | def __exit__(self, exc_type, exc_value, tb): 111 | self.preserve_context = False 112 | 113 | # on exit we want to clean up earlier. Normally the request context 114 | # stays preserved until the next request in the same thread comes 115 | # in. See RequestGlobals.push() for the general behavior. 116 | top = _request_ctx_stack.top 117 | if top is not None and top.preserved: 118 | top.pop() 119 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/appctx.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.testsuite.appctx 4 | ~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Tests the application context. 7 | 8 | :copyright: (c) 2012 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | 12 | from __future__ import with_statement 13 | 14 | import flask 15 | import unittest 16 | from flask.testsuite import FlaskTestCase 17 | 18 | 19 | class AppContextTestCase(FlaskTestCase): 20 | 21 | def test_basic_url_generation(self): 22 | app = flask.Flask(__name__) 23 | app.config['SERVER_NAME'] = 'localhost' 24 | app.config['PREFERRED_URL_SCHEME'] = 'https' 25 | 26 | @app.route('/') 27 | def index(): 28 | pass 29 | 30 | with app.app_context(): 31 | rv = flask.url_for('index') 32 | self.assert_equal(rv, 'https://localhost/') 33 | 34 | def test_url_generation_requires_server_name(self): 35 | app = flask.Flask(__name__) 36 | with app.app_context(): 37 | with self.assert_raises(RuntimeError): 38 | flask.url_for('index') 39 | 40 | def test_url_generation_without_context_fails(self): 41 | with self.assert_raises(RuntimeError): 42 | flask.url_for('index') 43 | 44 | def test_request_context_means_app_context(self): 45 | app = flask.Flask(__name__) 46 | with app.test_request_context(): 47 | self.assert_equal(flask.current_app._get_current_object(), app) 48 | self.assert_equal(flask._app_ctx_stack.top, None) 49 | 50 | def test_app_context_provides_current_app(self): 51 | app = flask.Flask(__name__) 52 | with app.app_context(): 53 | self.assert_equal(flask.current_app._get_current_object(), app) 54 | self.assert_equal(flask._app_ctx_stack.top, None) 55 | 56 | def test_app_tearing_down(self): 57 | cleanup_stuff = [] 58 | app = flask.Flask(__name__) 59 | @app.teardown_appcontext 60 | def cleanup(exception): 61 | cleanup_stuff.append(exception) 62 | 63 | with app.app_context(): 64 | pass 65 | 66 | self.assert_equal(cleanup_stuff, [None]) 67 | 68 | def test_custom_request_globals_class(self): 69 | class CustomRequestGlobals(object): 70 | def __init__(self): 71 | self.spam = 'eggs' 72 | app = flask.Flask(__name__) 73 | app.request_globals_class = CustomRequestGlobals 74 | with app.test_request_context(): 75 | self.assert_equal( 76 | flask.render_template_string('{{ g.spam }}'), 'eggs') 77 | 78 | def test_context_refcounts(self): 79 | called = [] 80 | app = flask.Flask(__name__) 81 | @app.teardown_request 82 | def teardown_req(error=None): 83 | called.append('request') 84 | @app.teardown_appcontext 85 | def teardown_app(error=None): 86 | called.append('app') 87 | @app.route('/') 88 | def index(): 89 | with flask._app_ctx_stack.top: 90 | with flask._request_ctx_stack.top: 91 | pass 92 | self.assert_(flask._request_ctx_stack.request.environ 93 | ['werkzeug.request'] is not None) 94 | c = app.test_client() 95 | c.get('/') 96 | self.assertEqual(called, ['request', 'app']) 97 | 98 | 99 | def suite(): 100 | suite = unittest.TestSuite() 101 | suite.addTest(unittest.makeSuite(AppContextTestCase)) 102 | return suite 103 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/deprecations.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.testsuite.deprecations 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Tests deprecation support. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | 12 | from __future__ import with_statement 13 | 14 | import flask 15 | import unittest 16 | from flask.testsuite import FlaskTestCase, catch_warnings 17 | 18 | 19 | class DeprecationsTestCase(FlaskTestCase): 20 | 21 | def test_init_jinja_globals(self): 22 | class MyFlask(flask.Flask): 23 | def init_jinja_globals(self): 24 | self.jinja_env.globals['foo'] = '42' 25 | 26 | with catch_warnings() as log: 27 | app = MyFlask(__name__) 28 | @app.route('/') 29 | def foo(): 30 | return app.jinja_env.globals['foo'] 31 | 32 | c = app.test_client() 33 | self.assert_equal(c.get('/').data, '42') 34 | self.assert_equal(len(log), 1) 35 | self.assert_('init_jinja_globals' in str(log[0]['message'])) 36 | 37 | 38 | def suite(): 39 | suite = unittest.TestSuite() 40 | suite.addTest(unittest.makeSuite(DeprecationsTestCase)) 41 | return suite 42 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/examples.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.testsuite.examples 4 | ~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Tests the examples. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import os 12 | import unittest 13 | from flask.testsuite import add_to_path 14 | 15 | 16 | def setup_path(): 17 | example_path = os.path.join(os.path.dirname(__file__), 18 | os.pardir, os.pardir, 'examples') 19 | add_to_path(os.path.join(example_path, 'flaskr')) 20 | add_to_path(os.path.join(example_path, 'minitwit')) 21 | 22 | 23 | def suite(): 24 | setup_path() 25 | suite = unittest.TestSuite() 26 | try: 27 | from minitwit_tests import MiniTwitTestCase 28 | except ImportError: 29 | pass 30 | else: 31 | suite.addTest(unittest.makeSuite(MiniTwitTestCase)) 32 | try: 33 | from flaskr_tests import FlaskrTestCase 34 | except ImportError: 35 | pass 36 | else: 37 | suite.addTest(unittest.makeSuite(FlaskrTestCase)) 38 | return suite 39 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/ext.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.testsuite.ext 4 | ~~~~~~~~~~~~~~~~~~~ 5 | 6 | Tests the extension import thing. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | from __future__ import with_statement 12 | 13 | import sys 14 | import unittest 15 | from flask.testsuite import FlaskTestCase 16 | 17 | 18 | class ExtImportHookTestCase(FlaskTestCase): 19 | 20 | def setup(self): 21 | # we clear this out for various reasons. The most important one is 22 | # that a real flaskext could be in there which would disable our 23 | # fake package. Secondly we want to make sure that the flaskext 24 | # import hook does not break on reloading. 25 | for entry, value in sys.modules.items(): 26 | if (entry.startswith('flask.ext.') or 27 | entry.startswith('flask_') or 28 | entry.startswith('flaskext.') or 29 | entry == 'flaskext') and value is not None: 30 | sys.modules.pop(entry, None) 31 | from flask import ext 32 | reload(ext) 33 | 34 | # reloading must not add more hooks 35 | import_hooks = 0 36 | for item in sys.meta_path: 37 | cls = type(item) 38 | if cls.__module__ == 'flask.exthook' and \ 39 | cls.__name__ == 'ExtensionImporter': 40 | import_hooks += 1 41 | self.assert_equal(import_hooks, 1) 42 | 43 | def teardown(self): 44 | from flask import ext 45 | for key in ext.__dict__: 46 | self.assert_('.' not in key) 47 | 48 | def test_flaskext_new_simple_import_normal(self): 49 | from flask.ext.newext_simple import ext_id 50 | self.assert_equal(ext_id, 'newext_simple') 51 | 52 | def test_flaskext_new_simple_import_module(self): 53 | from flask.ext import newext_simple 54 | self.assert_equal(newext_simple.ext_id, 'newext_simple') 55 | self.assert_equal(newext_simple.__name__, 'flask_newext_simple') 56 | 57 | def test_flaskext_new_package_import_normal(self): 58 | from flask.ext.newext_package import ext_id 59 | self.assert_equal(ext_id, 'newext_package') 60 | 61 | def test_flaskext_new_package_import_module(self): 62 | from flask.ext import newext_package 63 | self.assert_equal(newext_package.ext_id, 'newext_package') 64 | self.assert_equal(newext_package.__name__, 'flask_newext_package') 65 | 66 | def test_flaskext_new_package_import_submodule_function(self): 67 | from flask.ext.newext_package.submodule import test_function 68 | self.assert_equal(test_function(), 42) 69 | 70 | def test_flaskext_new_package_import_submodule(self): 71 | from flask.ext.newext_package import submodule 72 | self.assert_equal(submodule.__name__, 'flask_newext_package.submodule') 73 | self.assert_equal(submodule.test_function(), 42) 74 | 75 | def test_flaskext_old_simple_import_normal(self): 76 | from flask.ext.oldext_simple import ext_id 77 | self.assert_equal(ext_id, 'oldext_simple') 78 | 79 | def test_flaskext_old_simple_import_module(self): 80 | from flask.ext import oldext_simple 81 | self.assert_equal(oldext_simple.ext_id, 'oldext_simple') 82 | self.assert_equal(oldext_simple.__name__, 'flaskext.oldext_simple') 83 | 84 | def test_flaskext_old_package_import_normal(self): 85 | from flask.ext.oldext_package import ext_id 86 | self.assert_equal(ext_id, 'oldext_package') 87 | 88 | def test_flaskext_old_package_import_module(self): 89 | from flask.ext import oldext_package 90 | self.assert_equal(oldext_package.ext_id, 'oldext_package') 91 | self.assert_equal(oldext_package.__name__, 'flaskext.oldext_package') 92 | 93 | def test_flaskext_old_package_import_submodule(self): 94 | from flask.ext.oldext_package import submodule 95 | self.assert_equal(submodule.__name__, 'flaskext.oldext_package.submodule') 96 | self.assert_equal(submodule.test_function(), 42) 97 | 98 | def test_flaskext_old_package_import_submodule_function(self): 99 | from flask.ext.oldext_package.submodule import test_function 100 | self.assert_equal(test_function(), 42) 101 | 102 | def test_flaskext_broken_package_no_module_caching(self): 103 | for x in xrange(2): 104 | with self.assert_raises(ImportError): 105 | import flask.ext.broken 106 | 107 | def test_no_error_swallowing(self): 108 | try: 109 | import flask.ext.broken 110 | except ImportError: 111 | exc_type, exc_value, tb = sys.exc_info() 112 | self.assert_(exc_type is ImportError) 113 | self.assert_equal(str(exc_value), 'No module named missing_module') 114 | self.assert_(tb.tb_frame.f_globals is globals()) 115 | 116 | next = tb.tb_next 117 | self.assert_('flask_broken/__init__.py' in next.tb_frame.f_code.co_filename) 118 | 119 | 120 | def suite(): 121 | suite = unittest.TestSuite() 122 | suite.addTest(unittest.makeSuite(ExtImportHookTestCase)) 123 | return suite 124 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/regression.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.testsuite.regression 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Tests regressions. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | 12 | from __future__ import with_statement 13 | 14 | import gc 15 | import sys 16 | import flask 17 | import threading 18 | import unittest 19 | from werkzeug.test import run_wsgi_app, create_environ 20 | from flask.testsuite import FlaskTestCase 21 | 22 | 23 | _gc_lock = threading.Lock() 24 | 25 | 26 | class _NoLeakAsserter(object): 27 | 28 | def __init__(self, testcase): 29 | self.testcase = testcase 30 | 31 | def __enter__(self): 32 | gc.disable() 33 | _gc_lock.acquire() 34 | loc = flask._request_ctx_stack._local 35 | 36 | # Force Python to track this dictionary at all times. 37 | # This is necessary since Python only starts tracking 38 | # dicts if they contain mutable objects. It's a horrible, 39 | # horrible hack but makes this kinda testable. 40 | loc.__storage__['FOOO'] = [1, 2, 3] 41 | 42 | gc.collect() 43 | self.old_objects = len(gc.get_objects()) 44 | 45 | def __exit__(self, exc_type, exc_value, tb): 46 | if not hasattr(sys, 'getrefcount'): 47 | gc.collect() 48 | new_objects = len(gc.get_objects()) 49 | if new_objects > self.old_objects: 50 | self.testcase.fail('Example code leaked') 51 | _gc_lock.release() 52 | gc.enable() 53 | 54 | 55 | class MemoryTestCase(FlaskTestCase): 56 | 57 | def assert_no_leak(self): 58 | return _NoLeakAsserter(self) 59 | 60 | def test_memory_consumption(self): 61 | app = flask.Flask(__name__) 62 | @app.route('/') 63 | def index(): 64 | return flask.render_template('simple_template.html', whiskey=42) 65 | 66 | def fire(): 67 | with app.test_client() as c: 68 | rv = c.get('/') 69 | self.assert_equal(rv.status_code, 200) 70 | self.assert_equal(rv.data, '

42

') 71 | 72 | # Trigger caches 73 | fire() 74 | 75 | # This test only works on CPython 2.7. 76 | if sys.version_info >= (2, 7) and \ 77 | not hasattr(sys, 'pypy_translation_info'): 78 | with self.assert_no_leak(): 79 | for x in xrange(10): 80 | fire() 81 | 82 | 83 | def suite(): 84 | suite = unittest.TestSuite() 85 | suite.addTest(unittest.makeSuite(MemoryTestCase)) 86 | return suite 87 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/signals.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.testsuite.signals 4 | ~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Signalling. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import flask 12 | import unittest 13 | from flask.testsuite import FlaskTestCase 14 | 15 | 16 | class SignalsTestCase(FlaskTestCase): 17 | 18 | def test_template_rendered(self): 19 | app = flask.Flask(__name__) 20 | 21 | @app.route('/') 22 | def index(): 23 | return flask.render_template('simple_template.html', whiskey=42) 24 | 25 | recorded = [] 26 | def record(sender, template, context): 27 | recorded.append((template, context)) 28 | 29 | flask.template_rendered.connect(record, app) 30 | try: 31 | app.test_client().get('/') 32 | self.assert_equal(len(recorded), 1) 33 | template, context = recorded[0] 34 | self.assert_equal(template.name, 'simple_template.html') 35 | self.assert_equal(context['whiskey'], 42) 36 | finally: 37 | flask.template_rendered.disconnect(record, app) 38 | 39 | def test_request_signals(self): 40 | app = flask.Flask(__name__) 41 | calls = [] 42 | 43 | def before_request_signal(sender): 44 | calls.append('before-signal') 45 | 46 | def after_request_signal(sender, response): 47 | self.assert_equal(response.data, 'stuff') 48 | calls.append('after-signal') 49 | 50 | @app.before_request 51 | def before_request_handler(): 52 | calls.append('before-handler') 53 | 54 | @app.after_request 55 | def after_request_handler(response): 56 | calls.append('after-handler') 57 | response.data = 'stuff' 58 | return response 59 | 60 | @app.route('/') 61 | def index(): 62 | calls.append('handler') 63 | return 'ignored anyway' 64 | 65 | flask.request_started.connect(before_request_signal, app) 66 | flask.request_finished.connect(after_request_signal, app) 67 | 68 | try: 69 | rv = app.test_client().get('/') 70 | self.assert_equal(rv.data, 'stuff') 71 | 72 | self.assert_equal(calls, ['before-signal', 'before-handler', 73 | 'handler', 'after-handler', 74 | 'after-signal']) 75 | finally: 76 | flask.request_started.disconnect(before_request_signal, app) 77 | flask.request_finished.disconnect(after_request_signal, app) 78 | 79 | def test_request_exception_signal(self): 80 | app = flask.Flask(__name__) 81 | recorded = [] 82 | 83 | @app.route('/') 84 | def index(): 85 | 1/0 86 | 87 | def record(sender, exception): 88 | recorded.append(exception) 89 | 90 | flask.got_request_exception.connect(record, app) 91 | try: 92 | self.assert_equal(app.test_client().get('/').status_code, 500) 93 | self.assert_equal(len(recorded), 1) 94 | self.assert_(isinstance(recorded[0], ZeroDivisionError)) 95 | finally: 96 | flask.got_request_exception.disconnect(record, app) 97 | 98 | 99 | def suite(): 100 | suite = unittest.TestSuite() 101 | if flask.signals_available: 102 | suite.addTest(unittest.makeSuite(SignalsTestCase)) 103 | return suite 104 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/static/index.html: -------------------------------------------------------------------------------- 1 |

Hello World!

2 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/subclassing.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.testsuite.subclassing 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Test that certain behavior of flask can be customized by 7 | subclasses. 8 | 9 | :copyright: (c) 2011 by Armin Ronacher. 10 | :license: BSD, see LICENSE for more details. 11 | """ 12 | import flask 13 | import unittest 14 | from StringIO import StringIO 15 | from logging import StreamHandler 16 | from flask.testsuite import FlaskTestCase 17 | 18 | 19 | class FlaskSubclassingTestCase(FlaskTestCase): 20 | 21 | def test_supressed_exception_logging(self): 22 | class SupressedFlask(flask.Flask): 23 | def log_exception(self, exc_info): 24 | pass 25 | 26 | out = StringIO() 27 | app = SupressedFlask(__name__) 28 | app.logger_name = 'flask_tests/test_supressed_exception_logging' 29 | app.logger.addHandler(StreamHandler(out)) 30 | 31 | @app.route('/') 32 | def index(): 33 | 1/0 34 | 35 | rv = app.test_client().get('/') 36 | self.assert_equal(rv.status_code, 500) 37 | self.assert_('Internal Server Error' in rv.data) 38 | 39 | err = out.getvalue() 40 | self.assert_equal(err, '') 41 | 42 | 43 | def suite(): 44 | suite = unittest.TestSuite() 45 | suite.addTest(unittest.makeSuite(FlaskSubclassingTestCase)) 46 | return suite 47 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/templates/_macro.html: -------------------------------------------------------------------------------- 1 | {% macro hello(name) %}Hello {{ name }}!{% endmacro %} 2 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/templates/context_template.html: -------------------------------------------------------------------------------- 1 |

{{ value }}|{{ injected_value }} 2 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/templates/escaping_template.html: -------------------------------------------------------------------------------- 1 | {{ text }} 2 | {{ html }} 3 | {% autoescape false %}{{ text }} 4 | {{ html }}{% endautoescape %} 5 | {% autoescape true %}{{ text }} 6 | {{ html }}{% endautoescape %} 7 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/templates/mail.txt: -------------------------------------------------------------------------------- 1 | {{ foo}} Mail 2 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/templates/nested/nested.txt: -------------------------------------------------------------------------------- 1 | I'm nested 2 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/templates/simple_template.html: -------------------------------------------------------------------------------- 1 |

{{ whiskey }}

2 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/templates/template_filter.html: -------------------------------------------------------------------------------- 1 | {{ value|super_reverse }} -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/blueprintapp/__init__.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | app = Flask(__name__) 4 | from blueprintapp.apps.admin import admin 5 | from blueprintapp.apps.frontend import frontend 6 | app.register_blueprint(admin) 7 | app.register_blueprint(frontend) 8 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/blueprintapp/apps/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dinp/dinp-demo-python-flask/3714bdbf5125c0ea48635ea70087cb58d73f54af/dinp/flask/testsuite/test_apps/blueprintapp/apps/__init__.py -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/blueprintapp/apps/admin/__init__.py: -------------------------------------------------------------------------------- 1 | from flask import Blueprint, render_template 2 | 3 | admin = Blueprint('admin', __name__, url_prefix='/admin', 4 | template_folder='templates', 5 | static_folder='static') 6 | 7 | 8 | @admin.route('/') 9 | def index(): 10 | return render_template('admin/index.html') 11 | 12 | 13 | @admin.route('/index2') 14 | def index2(): 15 | return render_template('./admin/index.html') 16 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/blueprintapp/apps/admin/static/css/test.css: -------------------------------------------------------------------------------- 1 | /* nested file */ 2 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/blueprintapp/apps/admin/static/test.txt: -------------------------------------------------------------------------------- 1 | Admin File 2 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/blueprintapp/apps/admin/templates/admin/index.html: -------------------------------------------------------------------------------- 1 | Hello from the Admin 2 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/blueprintapp/apps/frontend/__init__.py: -------------------------------------------------------------------------------- 1 | from flask import Blueprint, render_template 2 | 3 | frontend = Blueprint('frontend', __name__, template_folder='templates') 4 | 5 | 6 | @frontend.route('/') 7 | def index(): 8 | return render_template('frontend/index.html') 9 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/blueprintapp/apps/frontend/templates/frontend/index.html: -------------------------------------------------------------------------------- 1 | Hello from the Frontend 2 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/config_module_app.py: -------------------------------------------------------------------------------- 1 | import os 2 | import flask 3 | here = os.path.abspath(os.path.dirname(__file__)) 4 | app = flask.Flask(__name__) 5 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/config_package_app/__init__.py: -------------------------------------------------------------------------------- 1 | import os 2 | import flask 3 | here = os.path.abspath(os.path.dirname(__file__)) 4 | app = flask.Flask(__name__) 5 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/flask_broken/__init__.py: -------------------------------------------------------------------------------- 1 | import flask.ext.broken.b 2 | import missing_module 3 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/flask_broken/b.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dinp/dinp-demo-python-flask/3714bdbf5125c0ea48635ea70087cb58d73f54af/dinp/flask/testsuite/test_apps/flask_broken/b.py -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/flask_newext_package/__init__.py: -------------------------------------------------------------------------------- 1 | ext_id = 'newext_package' 2 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/flask_newext_package/submodule.py: -------------------------------------------------------------------------------- 1 | def test_function(): 2 | return 42 3 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/flask_newext_simple.py: -------------------------------------------------------------------------------- 1 | ext_id = 'newext_simple' 2 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/flaskext/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dinp/dinp-demo-python-flask/3714bdbf5125c0ea48635ea70087cb58d73f54af/dinp/flask/testsuite/test_apps/flaskext/__init__.py -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/flaskext/oldext_package/__init__.py: -------------------------------------------------------------------------------- 1 | ext_id = 'oldext_package' 2 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/flaskext/oldext_package/submodule.py: -------------------------------------------------------------------------------- 1 | def test_function(): 2 | return 42 3 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/flaskext/oldext_simple.py: -------------------------------------------------------------------------------- 1 | ext_id = 'oldext_simple' 2 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/importerror.py: -------------------------------------------------------------------------------- 1 | # NoImportsTestCase 2 | raise NotImplementedError 3 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/lib/python2.5/site-packages/SiteEgg.egg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dinp/dinp-demo-python-flask/3714bdbf5125c0ea48635ea70087cb58d73f54af/dinp/flask/testsuite/test_apps/lib/python2.5/site-packages/SiteEgg.egg -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/lib/python2.5/site-packages/site_app.py: -------------------------------------------------------------------------------- 1 | import flask 2 | 3 | app = flask.Flask(__name__) 4 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/lib/python2.5/site-packages/site_package/__init__.py: -------------------------------------------------------------------------------- 1 | import flask 2 | 3 | app = flask.Flask(__name__) 4 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/main_app.py: -------------------------------------------------------------------------------- 1 | import flask 2 | 3 | # Test Flask initialization with main module. 4 | app = flask.Flask('__main__') 5 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/moduleapp/__init__.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | app = Flask(__name__) 4 | from moduleapp.apps.admin import admin 5 | from moduleapp.apps.frontend import frontend 6 | app.register_module(admin) 7 | app.register_module(frontend) 8 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/moduleapp/apps/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dinp/dinp-demo-python-flask/3714bdbf5125c0ea48635ea70087cb58d73f54af/dinp/flask/testsuite/test_apps/moduleapp/apps/__init__.py -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/moduleapp/apps/admin/__init__.py: -------------------------------------------------------------------------------- 1 | from flask import Module, render_template 2 | 3 | 4 | admin = Module(__name__, url_prefix='/admin') 5 | 6 | 7 | @admin.route('/') 8 | def index(): 9 | return render_template('admin/index.html') 10 | 11 | 12 | @admin.route('/index2') 13 | def index2(): 14 | return render_template('./admin/index.html') 15 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/moduleapp/apps/admin/static/css/test.css: -------------------------------------------------------------------------------- 1 | /* nested file */ 2 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/moduleapp/apps/admin/static/test.txt: -------------------------------------------------------------------------------- 1 | Admin File 2 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/moduleapp/apps/admin/templates/index.html: -------------------------------------------------------------------------------- 1 | Hello from the Admin 2 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/moduleapp/apps/frontend/__init__.py: -------------------------------------------------------------------------------- 1 | from flask import Module, render_template 2 | 3 | 4 | frontend = Module(__name__) 5 | 6 | 7 | @frontend.route('/') 8 | def index(): 9 | return render_template('frontend/index.html') 10 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/moduleapp/apps/frontend/templates/index.html: -------------------------------------------------------------------------------- 1 | Hello from the Frontend 2 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/path/installed_package/__init__.py: -------------------------------------------------------------------------------- 1 | import flask 2 | 3 | app = flask.Flask(__name__) 4 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/subdomaintestmodule/__init__.py: -------------------------------------------------------------------------------- 1 | from flask import Module 2 | 3 | 4 | mod = Module(__name__, 'foo', subdomain='foo') 5 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/test_apps/subdomaintestmodule/static/hello.txt: -------------------------------------------------------------------------------- 1 | Hello Subdomain 2 | -------------------------------------------------------------------------------- /dinp/flask/testsuite/views.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.testsuite.views 4 | ~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Pluggable views. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import flask 12 | import flask.views 13 | import unittest 14 | from flask.testsuite import FlaskTestCase 15 | from werkzeug.http import parse_set_header 16 | 17 | 18 | class ViewTestCase(FlaskTestCase): 19 | 20 | def common_test(self, app): 21 | c = app.test_client() 22 | 23 | self.assert_equal(c.get('/').data, 'GET') 24 | self.assert_equal(c.post('/').data, 'POST') 25 | self.assert_equal(c.put('/').status_code, 405) 26 | meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow']) 27 | self.assert_equal(sorted(meths), ['GET', 'HEAD', 'OPTIONS', 'POST']) 28 | 29 | def test_basic_view(self): 30 | app = flask.Flask(__name__) 31 | 32 | class Index(flask.views.View): 33 | methods = ['GET', 'POST'] 34 | def dispatch_request(self): 35 | return flask.request.method 36 | 37 | app.add_url_rule('/', view_func=Index.as_view('index')) 38 | self.common_test(app) 39 | 40 | def test_method_based_view(self): 41 | app = flask.Flask(__name__) 42 | 43 | class Index(flask.views.MethodView): 44 | def get(self): 45 | return 'GET' 46 | def post(self): 47 | return 'POST' 48 | 49 | app.add_url_rule('/', view_func=Index.as_view('index')) 50 | 51 | self.common_test(app) 52 | 53 | def test_view_patching(self): 54 | app = flask.Flask(__name__) 55 | 56 | class Index(flask.views.MethodView): 57 | def get(self): 58 | 1/0 59 | def post(self): 60 | 1/0 61 | 62 | class Other(Index): 63 | def get(self): 64 | return 'GET' 65 | def post(self): 66 | return 'POST' 67 | 68 | view = Index.as_view('index') 69 | view.view_class = Other 70 | app.add_url_rule('/', view_func=view) 71 | self.common_test(app) 72 | 73 | def test_view_inheritance(self): 74 | app = flask.Flask(__name__) 75 | 76 | class Index(flask.views.MethodView): 77 | def get(self): 78 | return 'GET' 79 | def post(self): 80 | return 'POST' 81 | 82 | class BetterIndex(Index): 83 | def delete(self): 84 | return 'DELETE' 85 | 86 | app.add_url_rule('/', view_func=BetterIndex.as_view('index')) 87 | c = app.test_client() 88 | 89 | meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow']) 90 | self.assert_equal(sorted(meths), ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST']) 91 | 92 | def test_view_decorators(self): 93 | app = flask.Flask(__name__) 94 | 95 | def add_x_parachute(f): 96 | def new_function(*args, **kwargs): 97 | resp = flask.make_response(f(*args, **kwargs)) 98 | resp.headers['X-Parachute'] = 'awesome' 99 | return resp 100 | return new_function 101 | 102 | class Index(flask.views.View): 103 | decorators = [add_x_parachute] 104 | def dispatch_request(self): 105 | return 'Awesome' 106 | 107 | app.add_url_rule('/', view_func=Index.as_view('index')) 108 | c = app.test_client() 109 | rv = c.get('/') 110 | self.assert_equal(rv.headers['X-Parachute'], 'awesome') 111 | self.assert_equal(rv.data, 'Awesome') 112 | 113 | def test_implicit_head(self): 114 | app = flask.Flask(__name__) 115 | 116 | class Index(flask.views.MethodView): 117 | def get(self): 118 | return flask.Response('Blub', headers={ 119 | 'X-Method': flask.request.method 120 | }) 121 | 122 | app.add_url_rule('/', view_func=Index.as_view('index')) 123 | c = app.test_client() 124 | rv = c.get('/') 125 | self.assert_equal(rv.data, 'Blub') 126 | self.assert_equal(rv.headers['X-Method'], 'GET') 127 | rv = c.head('/') 128 | self.assert_equal(rv.data, '') 129 | self.assert_equal(rv.headers['X-Method'], 'HEAD') 130 | 131 | def test_explicit_head(self): 132 | app = flask.Flask(__name__) 133 | 134 | class Index(flask.views.MethodView): 135 | def get(self): 136 | return 'GET' 137 | def head(self): 138 | return flask.Response('', headers={'X-Method': 'HEAD'}) 139 | 140 | app.add_url_rule('/', view_func=Index.as_view('index')) 141 | c = app.test_client() 142 | rv = c.get('/') 143 | self.assert_equal(rv.data, 'GET') 144 | rv = c.head('/') 145 | self.assert_equal(rv.data, '') 146 | self.assert_equal(rv.headers['X-Method'], 'HEAD') 147 | 148 | 149 | def suite(): 150 | suite = unittest.TestSuite() 151 | suite.addTest(unittest.makeSuite(ViewTestCase)) 152 | return suite 153 | -------------------------------------------------------------------------------- /dinp/flask/views.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.views 4 | ~~~~~~~~~~~ 5 | 6 | This module provides class-based views inspired by the ones in Django. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | from .globals import request 12 | 13 | 14 | http_method_funcs = frozenset(['get', 'post', 'head', 'options', 15 | 'delete', 'put', 'trace', 'patch']) 16 | 17 | 18 | class View(object): 19 | """Alternative way to use view functions. A subclass has to implement 20 | :meth:`dispatch_request` which is called with the view arguments from 21 | the URL routing system. If :attr:`methods` is provided the methods 22 | do not have to be passed to the :meth:`~flask.Flask.add_url_rule` 23 | method explicitly:: 24 | 25 | class MyView(View): 26 | methods = ['GET'] 27 | 28 | def dispatch_request(self, name): 29 | return 'Hello %s!' % name 30 | 31 | app.add_url_rule('/hello/', view_func=MyView.as_view('myview')) 32 | 33 | When you want to decorate a pluggable view you will have to either do that 34 | when the view function is created (by wrapping the return value of 35 | :meth:`as_view`) or you can use the :attr:`decorators` attribute:: 36 | 37 | class SecretView(View): 38 | methods = ['GET'] 39 | decorators = [superuser_required] 40 | 41 | def dispatch_request(self): 42 | ... 43 | 44 | The decorators stored in the decorators list are applied one after another 45 | when the view function is created. Note that you can *not* use the class 46 | based decorators since those would decorate the view class and not the 47 | generated view function! 48 | """ 49 | 50 | #: A for which methods this pluggable view can handle. 51 | methods = None 52 | 53 | #: The canonical way to decorate class-based views is to decorate the 54 | #: return value of as_view(). However since this moves parts of the 55 | #: logic from the class declaration to the place where it's hooked 56 | #: into the routing system. 57 | #: 58 | #: You can place one or more decorators in this list and whenever the 59 | #: view function is created the result is automatically decorated. 60 | #: 61 | #: .. versionadded:: 0.8 62 | decorators = [] 63 | 64 | def dispatch_request(self): 65 | """Subclasses have to override this method to implement the 66 | actual view function code. This method is called with all 67 | the arguments from the URL rule. 68 | """ 69 | raise NotImplementedError() 70 | 71 | @classmethod 72 | def as_view(cls, name, *class_args, **class_kwargs): 73 | """Converts the class into an actual view function that can be used 74 | with the routing system. Internally this generates a function on the 75 | fly which will instantiate the :class:`View` on each request and call 76 | the :meth:`dispatch_request` method on it. 77 | 78 | The arguments passed to :meth:`as_view` are forwarded to the 79 | constructor of the class. 80 | """ 81 | def view(*args, **kwargs): 82 | self = view.view_class(*class_args, **class_kwargs) 83 | return self.dispatch_request(*args, **kwargs) 84 | 85 | if cls.decorators: 86 | view.__name__ = name 87 | view.__module__ = cls.__module__ 88 | for decorator in cls.decorators: 89 | view = decorator(view) 90 | 91 | # we attach the view class to the view function for two reasons: 92 | # first of all it allows us to easily figure out what class-based 93 | # view this thing came from, secondly it's also used for instantiating 94 | # the view class so you can actually replace it with something else 95 | # for testing purposes and debugging. 96 | view.view_class = cls 97 | view.__name__ = name 98 | view.__doc__ = cls.__doc__ 99 | view.__module__ = cls.__module__ 100 | view.methods = cls.methods 101 | return view 102 | 103 | 104 | class MethodViewType(type): 105 | 106 | def __new__(cls, name, bases, d): 107 | rv = type.__new__(cls, name, bases, d) 108 | if 'methods' not in d: 109 | methods = set(rv.methods or []) 110 | for key in d: 111 | if key in http_method_funcs: 112 | methods.add(key.upper()) 113 | # if we have no method at all in there we don't want to 114 | # add a method list. (This is for instance the case for 115 | # the baseclass or another subclass of a base method view 116 | # that does not introduce new methods). 117 | if methods: 118 | rv.methods = sorted(methods) 119 | return rv 120 | 121 | 122 | class MethodView(View): 123 | """Like a regular class-based view but that dispatches requests to 124 | particular methods. For instance if you implement a method called 125 | :meth:`get` it means you will response to ``'GET'`` requests and 126 | the :meth:`dispatch_request` implementation will automatically 127 | forward your request to that. Also :attr:`options` is set for you 128 | automatically:: 129 | 130 | class CounterAPI(MethodView): 131 | 132 | def get(self): 133 | return session.get('counter', 0) 134 | 135 | def post(self): 136 | session['counter'] = session.get('counter', 0) + 1 137 | return 'OK' 138 | 139 | app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter')) 140 | """ 141 | __metaclass__ = MethodViewType 142 | 143 | def dispatch_request(self, *args, **kwargs): 144 | meth = getattr(self, request.method.lower(), None) 145 | # if the request method is HEAD and we don't have a handler for it 146 | # retry with GET 147 | if meth is None and request.method == 'HEAD': 148 | meth = getattr(self, 'get', None) 149 | assert meth is not None, 'Unimplemented method %r' % request.method 150 | return meth(*args, **kwargs) 151 | -------------------------------------------------------------------------------- /dinp/flask/wrappers.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.wrappers 4 | ~~~~~~~~~~~~~~ 5 | 6 | Implements the WSGI wrappers (request and response). 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | 12 | from werkzeug.wrappers import Request as RequestBase, Response as ResponseBase 13 | from werkzeug.utils import cached_property 14 | 15 | from .exceptions import JSONBadRequest 16 | from .debughelpers import attach_enctype_error_multidict 17 | from .helpers import json, _assert_have_json 18 | from .globals import _request_ctx_stack 19 | 20 | 21 | class Request(RequestBase): 22 | """The request object used by default in Flask. Remembers the 23 | matched endpoint and view arguments. 24 | 25 | It is what ends up as :class:`~flask.request`. If you want to replace 26 | the request object used you can subclass this and set 27 | :attr:`~flask.Flask.request_class` to your subclass. 28 | 29 | The request object is a :class:`~werkzeug.wrappers.Request` subclass and 30 | provides all of the attributes Werkzeug defines plus a few Flask 31 | specific ones. 32 | """ 33 | 34 | #: the internal URL rule that matched the request. This can be 35 | #: useful to inspect which methods are allowed for the URL from 36 | #: a before/after handler (``request.url_rule.methods``) etc. 37 | #: 38 | #: .. versionadded:: 0.6 39 | url_rule = None 40 | 41 | #: a dict of view arguments that matched the request. If an exception 42 | #: happened when matching, this will be `None`. 43 | view_args = None 44 | 45 | #: if matching the URL failed, this is the exception that will be 46 | #: raised / was raised as part of the request handling. This is 47 | #: usually a :exc:`~werkzeug.exceptions.NotFound` exception or 48 | #: something similar. 49 | routing_exception = None 50 | 51 | # switched by the request context until 1.0 to opt in deprecated 52 | # module functionality 53 | _is_old_module = False 54 | 55 | @property 56 | def max_content_length(self): 57 | """Read-only view of the `MAX_CONTENT_LENGTH` config key.""" 58 | ctx = _request_ctx_stack.top 59 | if ctx is not None: 60 | return ctx.app.config['MAX_CONTENT_LENGTH'] 61 | 62 | @property 63 | def endpoint(self): 64 | """The endpoint that matched the request. This in combination with 65 | :attr:`view_args` can be used to reconstruct the same or a 66 | modified URL. If an exception happened when matching, this will 67 | be `None`. 68 | """ 69 | if self.url_rule is not None: 70 | return self.url_rule.endpoint 71 | 72 | @property 73 | def module(self): 74 | """The name of the current module if the request was dispatched 75 | to an actual module. This is deprecated functionality, use blueprints 76 | instead. 77 | """ 78 | from warnings import warn 79 | warn(DeprecationWarning('modules were deprecated in favor of ' 80 | 'blueprints. Use request.blueprint ' 81 | 'instead.'), stacklevel=2) 82 | if self._is_old_module: 83 | return self.blueprint 84 | 85 | @property 86 | def blueprint(self): 87 | """The name of the current blueprint""" 88 | if self.url_rule and '.' in self.url_rule.endpoint: 89 | return self.url_rule.endpoint.rsplit('.', 1)[0] 90 | 91 | @cached_property 92 | def json(self): 93 | """If the mimetype is `application/json` this will contain the 94 | parsed JSON data. Otherwise this will be `None`. 95 | 96 | This requires Python 2.6 or an installed version of simplejson. 97 | """ 98 | if __debug__: 99 | _assert_have_json() 100 | if self.mimetype == 'application/json': 101 | request_charset = self.mimetype_params.get('charset') 102 | try: 103 | if request_charset is not None: 104 | return json.loads(self.data, encoding=request_charset) 105 | return json.loads(self.data) 106 | except ValueError, e: 107 | return self.on_json_loading_failed(e) 108 | 109 | def on_json_loading_failed(self, e): 110 | """Called if decoding of the JSON data failed. The return value of 111 | this method is used by :attr:`json` when an error ocurred. The default 112 | implementation raises a :class:`JSONBadRequest`, which is a subclass of 113 | :class:`~werkzeug.exceptions.BadRequest` which sets the 114 | ``Content-Type`` to ``application/json`` and provides a JSON-formatted 115 | error description:: 116 | 117 | {"description": "The browser (or proxy) sent a request that \ 118 | this server could not understand."} 119 | 120 | .. versionchanged:: 0.9 121 | Return a :class:`JSONBadRequest` instead of a 122 | :class:`~werkzeug.exceptions.BadRequest` by default. 123 | 124 | .. versionadded:: 0.8 125 | """ 126 | raise JSONBadRequest() 127 | 128 | def _load_form_data(self): 129 | RequestBase._load_form_data(self) 130 | 131 | # in debug mode we're replacing the files multidict with an ad-hoc 132 | # subclass that raises a different error for key errors. 133 | ctx = _request_ctx_stack.top 134 | if ctx is not None and ctx.app.debug and \ 135 | self.mimetype != 'multipart/form-data' and not self.files: 136 | attach_enctype_error_multidict(self) 137 | 138 | 139 | class Response(ResponseBase): 140 | """The response object that is used by default in Flask. Works like the 141 | response object from Werkzeug but is set to have an HTML mimetype by 142 | default. Quite often you don't have to create this object yourself because 143 | :meth:`~flask.Flask.make_response` will take care of that for you. 144 | 145 | If you want to replace the response object used you can subclass this and 146 | set :attr:`~flask.Flask.response_class` to your subclass. 147 | """ 148 | default_mimetype = 'text/html' 149 | -------------------------------------------------------------------------------- /dinp/jinja2/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | jinja2 4 | ~~~~~~ 5 | 6 | Jinja2 is a template engine written in pure Python. It provides a 7 | Django inspired non-XML syntax but supports inline expressions and 8 | an optional sandboxed environment. 9 | 10 | Nutshell 11 | -------- 12 | 13 | Here a small example of a Jinja2 template:: 14 | 15 | {% extends 'base.html' %} 16 | {% block title %}Memberlist{% endblock %} 17 | {% block content %} 18 | 23 | {% endblock %} 24 | 25 | 26 | :copyright: (c) 2010 by the Jinja Team. 27 | :license: BSD, see LICENSE for more details. 28 | """ 29 | __docformat__ = 'restructuredtext en' 30 | __version__ = '2.6' 31 | 32 | # high level interface 33 | from jinja2.environment import Environment, Template 34 | 35 | # loaders 36 | from jinja2.loaders import BaseLoader, FileSystemLoader, PackageLoader, \ 37 | DictLoader, FunctionLoader, PrefixLoader, ChoiceLoader, \ 38 | ModuleLoader 39 | 40 | # bytecode caches 41 | from jinja2.bccache import BytecodeCache, FileSystemBytecodeCache, \ 42 | MemcachedBytecodeCache 43 | 44 | # undefined types 45 | from jinja2.runtime import Undefined, DebugUndefined, StrictUndefined 46 | 47 | # exceptions 48 | from jinja2.exceptions import TemplateError, UndefinedError, \ 49 | TemplateNotFound, TemplatesNotFound, TemplateSyntaxError, \ 50 | TemplateAssertionError 51 | 52 | # decorators and public utilities 53 | from jinja2.filters import environmentfilter, contextfilter, \ 54 | evalcontextfilter 55 | from jinja2.utils import Markup, escape, clear_caches, \ 56 | environmentfunction, evalcontextfunction, contextfunction, \ 57 | is_undefined 58 | 59 | __all__ = [ 60 | 'Environment', 'Template', 'BaseLoader', 'FileSystemLoader', 61 | 'PackageLoader', 'DictLoader', 'FunctionLoader', 'PrefixLoader', 62 | 'ChoiceLoader', 'BytecodeCache', 'FileSystemBytecodeCache', 63 | 'MemcachedBytecodeCache', 'Undefined', 'DebugUndefined', 64 | 'StrictUndefined', 'TemplateError', 'UndefinedError', 'TemplateNotFound', 65 | 'TemplatesNotFound', 'TemplateSyntaxError', 'TemplateAssertionError', 66 | 'ModuleLoader', 'environmentfilter', 'contextfilter', 'Markup', 'escape', 67 | 'environmentfunction', 'contextfunction', 'clear_caches', 'is_undefined', 68 | 'evalcontextfilter', 'evalcontextfunction' 69 | ] 70 | -------------------------------------------------------------------------------- /dinp/jinja2/_debugsupport.c: -------------------------------------------------------------------------------- 1 | /** 2 | * jinja2._debugsupport 3 | * ~~~~~~~~~~~~~~~~~~~~ 4 | * 5 | * C implementation of `tb_set_next`. 6 | * 7 | * :copyright: (c) 2010 by the Jinja Team. 8 | * :license: BSD. 9 | */ 10 | 11 | #include 12 | 13 | 14 | static PyObject* 15 | tb_set_next(PyObject *self, PyObject *args) 16 | { 17 | PyTracebackObject *tb, *old; 18 | PyObject *next; 19 | 20 | if (!PyArg_ParseTuple(args, "O!O:tb_set_next", &PyTraceBack_Type, &tb, &next)) 21 | return NULL; 22 | if (next == Py_None) 23 | next = NULL; 24 | else if (!PyTraceBack_Check(next)) { 25 | PyErr_SetString(PyExc_TypeError, 26 | "tb_set_next arg 2 must be traceback or None"); 27 | return NULL; 28 | } 29 | else 30 | Py_INCREF(next); 31 | 32 | old = tb->tb_next; 33 | tb->tb_next = (PyTracebackObject*)next; 34 | Py_XDECREF(old); 35 | 36 | Py_INCREF(Py_None); 37 | return Py_None; 38 | } 39 | 40 | static PyMethodDef module_methods[] = { 41 | {"tb_set_next", (PyCFunction)tb_set_next, METH_VARARGS, 42 | "Set the tb_next member of a traceback object."}, 43 | {NULL, NULL, 0, NULL} /* Sentinel */ 44 | }; 45 | 46 | 47 | #if PY_MAJOR_VERSION < 3 48 | 49 | #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */ 50 | #define PyMODINIT_FUNC void 51 | #endif 52 | PyMODINIT_FUNC 53 | init_debugsupport(void) 54 | { 55 | Py_InitModule3("jinja2._debugsupport", module_methods, ""); 56 | } 57 | 58 | #else /* Python 3.x module initialization */ 59 | 60 | static struct PyModuleDef module_definition = { 61 | PyModuleDef_HEAD_INIT, 62 | "jinja2._debugsupport", 63 | NULL, 64 | -1, 65 | module_methods, 66 | NULL, 67 | NULL, 68 | NULL, 69 | NULL 70 | }; 71 | 72 | PyMODINIT_FUNC 73 | PyInit__debugsupport(void) 74 | { 75 | return PyModule_Create(&module_definition); 76 | } 77 | 78 | #endif 79 | -------------------------------------------------------------------------------- /dinp/jinja2/_markupsafe/_bundle.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | jinja2._markupsafe._bundle 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | This script pulls in markupsafe from a source folder and 7 | bundles it with Jinja2. It does not pull in the speedups 8 | module though. 9 | 10 | :copyright: Copyright 2010 by the Jinja team, see AUTHORS. 11 | :license: BSD, see LICENSE for details. 12 | """ 13 | import sys 14 | import os 15 | import re 16 | 17 | 18 | def rewrite_imports(lines): 19 | for idx, line in enumerate(lines): 20 | new_line = re.sub(r'(import|from)\s+markupsafe\b', 21 | r'\1 jinja2._markupsafe', line) 22 | if new_line != line: 23 | lines[idx] = new_line 24 | 25 | 26 | def main(): 27 | if len(sys.argv) != 2: 28 | print 'error: only argument is path to markupsafe' 29 | sys.exit(1) 30 | basedir = os.path.dirname(__file__) 31 | markupdir = sys.argv[1] 32 | for filename in os.listdir(markupdir): 33 | if filename.endswith('.py'): 34 | f = open(os.path.join(markupdir, filename)) 35 | try: 36 | lines = list(f) 37 | finally: 38 | f.close() 39 | rewrite_imports(lines) 40 | f = open(os.path.join(basedir, filename), 'w') 41 | try: 42 | for line in lines: 43 | f.write(line) 44 | finally: 45 | f.close() 46 | 47 | 48 | if __name__ == '__main__': 49 | main() 50 | -------------------------------------------------------------------------------- /dinp/jinja2/_markupsafe/_constants.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | markupsafe._constants 4 | ~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Highlevel implementation of the Markup string. 7 | 8 | :copyright: (c) 2010 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | 12 | 13 | HTML_ENTITIES = { 14 | 'AElig': 198, 15 | 'Aacute': 193, 16 | 'Acirc': 194, 17 | 'Agrave': 192, 18 | 'Alpha': 913, 19 | 'Aring': 197, 20 | 'Atilde': 195, 21 | 'Auml': 196, 22 | 'Beta': 914, 23 | 'Ccedil': 199, 24 | 'Chi': 935, 25 | 'Dagger': 8225, 26 | 'Delta': 916, 27 | 'ETH': 208, 28 | 'Eacute': 201, 29 | 'Ecirc': 202, 30 | 'Egrave': 200, 31 | 'Epsilon': 917, 32 | 'Eta': 919, 33 | 'Euml': 203, 34 | 'Gamma': 915, 35 | 'Iacute': 205, 36 | 'Icirc': 206, 37 | 'Igrave': 204, 38 | 'Iota': 921, 39 | 'Iuml': 207, 40 | 'Kappa': 922, 41 | 'Lambda': 923, 42 | 'Mu': 924, 43 | 'Ntilde': 209, 44 | 'Nu': 925, 45 | 'OElig': 338, 46 | 'Oacute': 211, 47 | 'Ocirc': 212, 48 | 'Ograve': 210, 49 | 'Omega': 937, 50 | 'Omicron': 927, 51 | 'Oslash': 216, 52 | 'Otilde': 213, 53 | 'Ouml': 214, 54 | 'Phi': 934, 55 | 'Pi': 928, 56 | 'Prime': 8243, 57 | 'Psi': 936, 58 | 'Rho': 929, 59 | 'Scaron': 352, 60 | 'Sigma': 931, 61 | 'THORN': 222, 62 | 'Tau': 932, 63 | 'Theta': 920, 64 | 'Uacute': 218, 65 | 'Ucirc': 219, 66 | 'Ugrave': 217, 67 | 'Upsilon': 933, 68 | 'Uuml': 220, 69 | 'Xi': 926, 70 | 'Yacute': 221, 71 | 'Yuml': 376, 72 | 'Zeta': 918, 73 | 'aacute': 225, 74 | 'acirc': 226, 75 | 'acute': 180, 76 | 'aelig': 230, 77 | 'agrave': 224, 78 | 'alefsym': 8501, 79 | 'alpha': 945, 80 | 'amp': 38, 81 | 'and': 8743, 82 | 'ang': 8736, 83 | 'apos': 39, 84 | 'aring': 229, 85 | 'asymp': 8776, 86 | 'atilde': 227, 87 | 'auml': 228, 88 | 'bdquo': 8222, 89 | 'beta': 946, 90 | 'brvbar': 166, 91 | 'bull': 8226, 92 | 'cap': 8745, 93 | 'ccedil': 231, 94 | 'cedil': 184, 95 | 'cent': 162, 96 | 'chi': 967, 97 | 'circ': 710, 98 | 'clubs': 9827, 99 | 'cong': 8773, 100 | 'copy': 169, 101 | 'crarr': 8629, 102 | 'cup': 8746, 103 | 'curren': 164, 104 | 'dArr': 8659, 105 | 'dagger': 8224, 106 | 'darr': 8595, 107 | 'deg': 176, 108 | 'delta': 948, 109 | 'diams': 9830, 110 | 'divide': 247, 111 | 'eacute': 233, 112 | 'ecirc': 234, 113 | 'egrave': 232, 114 | 'empty': 8709, 115 | 'emsp': 8195, 116 | 'ensp': 8194, 117 | 'epsilon': 949, 118 | 'equiv': 8801, 119 | 'eta': 951, 120 | 'eth': 240, 121 | 'euml': 235, 122 | 'euro': 8364, 123 | 'exist': 8707, 124 | 'fnof': 402, 125 | 'forall': 8704, 126 | 'frac12': 189, 127 | 'frac14': 188, 128 | 'frac34': 190, 129 | 'frasl': 8260, 130 | 'gamma': 947, 131 | 'ge': 8805, 132 | 'gt': 62, 133 | 'hArr': 8660, 134 | 'harr': 8596, 135 | 'hearts': 9829, 136 | 'hellip': 8230, 137 | 'iacute': 237, 138 | 'icirc': 238, 139 | 'iexcl': 161, 140 | 'igrave': 236, 141 | 'image': 8465, 142 | 'infin': 8734, 143 | 'int': 8747, 144 | 'iota': 953, 145 | 'iquest': 191, 146 | 'isin': 8712, 147 | 'iuml': 239, 148 | 'kappa': 954, 149 | 'lArr': 8656, 150 | 'lambda': 955, 151 | 'lang': 9001, 152 | 'laquo': 171, 153 | 'larr': 8592, 154 | 'lceil': 8968, 155 | 'ldquo': 8220, 156 | 'le': 8804, 157 | 'lfloor': 8970, 158 | 'lowast': 8727, 159 | 'loz': 9674, 160 | 'lrm': 8206, 161 | 'lsaquo': 8249, 162 | 'lsquo': 8216, 163 | 'lt': 60, 164 | 'macr': 175, 165 | 'mdash': 8212, 166 | 'micro': 181, 167 | 'middot': 183, 168 | 'minus': 8722, 169 | 'mu': 956, 170 | 'nabla': 8711, 171 | 'nbsp': 160, 172 | 'ndash': 8211, 173 | 'ne': 8800, 174 | 'ni': 8715, 175 | 'not': 172, 176 | 'notin': 8713, 177 | 'nsub': 8836, 178 | 'ntilde': 241, 179 | 'nu': 957, 180 | 'oacute': 243, 181 | 'ocirc': 244, 182 | 'oelig': 339, 183 | 'ograve': 242, 184 | 'oline': 8254, 185 | 'omega': 969, 186 | 'omicron': 959, 187 | 'oplus': 8853, 188 | 'or': 8744, 189 | 'ordf': 170, 190 | 'ordm': 186, 191 | 'oslash': 248, 192 | 'otilde': 245, 193 | 'otimes': 8855, 194 | 'ouml': 246, 195 | 'para': 182, 196 | 'part': 8706, 197 | 'permil': 8240, 198 | 'perp': 8869, 199 | 'phi': 966, 200 | 'pi': 960, 201 | 'piv': 982, 202 | 'plusmn': 177, 203 | 'pound': 163, 204 | 'prime': 8242, 205 | 'prod': 8719, 206 | 'prop': 8733, 207 | 'psi': 968, 208 | 'quot': 34, 209 | 'rArr': 8658, 210 | 'radic': 8730, 211 | 'rang': 9002, 212 | 'raquo': 187, 213 | 'rarr': 8594, 214 | 'rceil': 8969, 215 | 'rdquo': 8221, 216 | 'real': 8476, 217 | 'reg': 174, 218 | 'rfloor': 8971, 219 | 'rho': 961, 220 | 'rlm': 8207, 221 | 'rsaquo': 8250, 222 | 'rsquo': 8217, 223 | 'sbquo': 8218, 224 | 'scaron': 353, 225 | 'sdot': 8901, 226 | 'sect': 167, 227 | 'shy': 173, 228 | 'sigma': 963, 229 | 'sigmaf': 962, 230 | 'sim': 8764, 231 | 'spades': 9824, 232 | 'sub': 8834, 233 | 'sube': 8838, 234 | 'sum': 8721, 235 | 'sup': 8835, 236 | 'sup1': 185, 237 | 'sup2': 178, 238 | 'sup3': 179, 239 | 'supe': 8839, 240 | 'szlig': 223, 241 | 'tau': 964, 242 | 'there4': 8756, 243 | 'theta': 952, 244 | 'thetasym': 977, 245 | 'thinsp': 8201, 246 | 'thorn': 254, 247 | 'tilde': 732, 248 | 'times': 215, 249 | 'trade': 8482, 250 | 'uArr': 8657, 251 | 'uacute': 250, 252 | 'uarr': 8593, 253 | 'ucirc': 251, 254 | 'ugrave': 249, 255 | 'uml': 168, 256 | 'upsih': 978, 257 | 'upsilon': 965, 258 | 'uuml': 252, 259 | 'weierp': 8472, 260 | 'xi': 958, 261 | 'yacute': 253, 262 | 'yen': 165, 263 | 'yuml': 255, 264 | 'zeta': 950, 265 | 'zwj': 8205, 266 | 'zwnj': 8204 267 | } 268 | -------------------------------------------------------------------------------- /dinp/jinja2/_markupsafe/_native.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | markupsafe._native 4 | ~~~~~~~~~~~~~~~~~~ 5 | 6 | Native Python implementation the C module is not compiled. 7 | 8 | :copyright: (c) 2010 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | from jinja2._markupsafe import Markup 12 | 13 | 14 | def escape(s): 15 | """Convert the characters &, <, >, ' and " in string s to HTML-safe 16 | sequences. Use this if you need to display text that might contain 17 | such characters in HTML. Marks return value as markup string. 18 | """ 19 | if hasattr(s, '__html__'): 20 | return s.__html__() 21 | return Markup(unicode(s) 22 | .replace('&', '&') 23 | .replace('>', '>') 24 | .replace('<', '<') 25 | .replace("'", ''') 26 | .replace('"', '"') 27 | ) 28 | 29 | 30 | def escape_silent(s): 31 | """Like :func:`escape` but converts `None` into an empty 32 | markup string. 33 | """ 34 | if s is None: 35 | return Markup() 36 | return escape(s) 37 | 38 | 39 | def soft_unicode(s): 40 | """Make a string unicode if it isn't already. That way a markup 41 | string is not converted back to unicode. 42 | """ 43 | if not isinstance(s, unicode): 44 | s = unicode(s) 45 | return s 46 | -------------------------------------------------------------------------------- /dinp/jinja2/_markupsafe/tests.py: -------------------------------------------------------------------------------- 1 | import gc 2 | import unittest 3 | from jinja2._markupsafe import Markup, escape, escape_silent 4 | 5 | 6 | class MarkupTestCase(unittest.TestCase): 7 | 8 | def test_markup_operations(self): 9 | # adding two strings should escape the unsafe one 10 | unsafe = '' 11 | safe = Markup('username') 12 | assert unsafe + safe == unicode(escape(unsafe)) + unicode(safe) 13 | 14 | # string interpolations are safe to use too 15 | assert Markup('%s') % '' == \ 16 | '<bad user>' 17 | assert Markup('%(username)s') % { 18 | 'username': '' 19 | } == '<bad user>' 20 | 21 | # an escaped object is markup too 22 | assert type(Markup('foo') + 'bar') is Markup 23 | 24 | # and it implements __html__ by returning itself 25 | x = Markup("foo") 26 | assert x.__html__() is x 27 | 28 | # it also knows how to treat __html__ objects 29 | class Foo(object): 30 | def __html__(self): 31 | return 'awesome' 32 | def __unicode__(self): 33 | return 'awesome' 34 | assert Markup(Foo()) == 'awesome' 35 | assert Markup('%s') % Foo() == \ 36 | 'awesome' 37 | 38 | # escaping and unescaping 39 | assert escape('"<>&\'') == '"<>&'' 40 | assert Markup("Foo & Bar").striptags() == "Foo & Bar" 41 | assert Markup("<test>").unescape() == "" 42 | 43 | def test_all_set(self): 44 | import jinja2._markupsafe as markup 45 | for item in markup.__all__: 46 | getattr(markup, item) 47 | 48 | def test_escape_silent(self): 49 | assert escape_silent(None) == Markup() 50 | assert escape(None) == Markup(None) 51 | assert escape_silent('') == Markup(u'<foo>') 52 | 53 | 54 | class MarkupLeakTestCase(unittest.TestCase): 55 | 56 | def test_markup_leaks(self): 57 | counts = set() 58 | for count in xrange(20): 59 | for item in xrange(1000): 60 | escape("foo") 61 | escape("") 62 | escape(u"foo") 63 | escape(u"") 64 | counts.add(len(gc.get_objects())) 65 | assert len(counts) == 1, 'ouch, c extension seems to leak objects' 66 | 67 | 68 | def suite(): 69 | suite = unittest.TestSuite() 70 | suite.addTest(unittest.makeSuite(MarkupTestCase)) 71 | 72 | # this test only tests the c extension 73 | if not hasattr(escape, 'func_code'): 74 | suite.addTest(unittest.makeSuite(MarkupLeakTestCase)) 75 | 76 | return suite 77 | 78 | 79 | if __name__ == '__main__': 80 | unittest.main(defaultTest='suite') 81 | -------------------------------------------------------------------------------- /dinp/jinja2/constants.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | jinja.constants 4 | ~~~~~~~~~~~~~~~ 5 | 6 | Various constants. 7 | 8 | :copyright: (c) 2010 by the Jinja Team. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | 12 | 13 | #: list of lorem ipsum words used by the lipsum() helper function 14 | LOREM_IPSUM_WORDS = u'''\ 15 | a ac accumsan ad adipiscing aenean aliquam aliquet amet ante aptent arcu at 16 | auctor augue bibendum blandit class commodo condimentum congue consectetuer 17 | consequat conubia convallis cras cubilia cum curabitur curae cursus dapibus 18 | diam dictum dictumst dignissim dis dolor donec dui duis egestas eget eleifend 19 | elementum elit enim erat eros est et etiam eu euismod facilisi facilisis fames 20 | faucibus felis fermentum feugiat fringilla fusce gravida habitant habitasse hac 21 | hendrerit hymenaeos iaculis id imperdiet in inceptos integer interdum ipsum 22 | justo lacinia lacus laoreet lectus leo libero ligula litora lobortis lorem 23 | luctus maecenas magna magnis malesuada massa mattis mauris metus mi molestie 24 | mollis montes morbi mus nam nascetur natoque nec neque netus nibh nisi nisl non 25 | nonummy nostra nulla nullam nunc odio orci ornare parturient pede pellentesque 26 | penatibus per pharetra phasellus placerat platea porta porttitor posuere 27 | potenti praesent pretium primis proin pulvinar purus quam quis quisque rhoncus 28 | ridiculus risus rutrum sagittis sapien scelerisque sed sem semper senectus sit 29 | sociis sociosqu sodales sollicitudin suscipit suspendisse taciti tellus tempor 30 | tempus tincidunt torquent tortor tristique turpis ullamcorper ultrices 31 | ultricies urna ut varius vehicula vel velit venenatis vestibulum vitae vivamus 32 | viverra volutpat vulputate''' 33 | -------------------------------------------------------------------------------- /dinp/jinja2/defaults.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | jinja2.defaults 4 | ~~~~~~~~~~~~~~~ 5 | 6 | Jinja default filters and tags. 7 | 8 | :copyright: (c) 2010 by the Jinja Team. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | from jinja2.utils import generate_lorem_ipsum, Cycler, Joiner 12 | 13 | 14 | # defaults for the parser / lexer 15 | BLOCK_START_STRING = '{%' 16 | BLOCK_END_STRING = '%}' 17 | VARIABLE_START_STRING = '{{' 18 | VARIABLE_END_STRING = '}}' 19 | COMMENT_START_STRING = '{#' 20 | COMMENT_END_STRING = '#}' 21 | LINE_STATEMENT_PREFIX = None 22 | LINE_COMMENT_PREFIX = None 23 | TRIM_BLOCKS = False 24 | NEWLINE_SEQUENCE = '\n' 25 | 26 | 27 | # default filters, tests and namespace 28 | from jinja2.filters import FILTERS as DEFAULT_FILTERS 29 | from jinja2.tests import TESTS as DEFAULT_TESTS 30 | DEFAULT_NAMESPACE = { 31 | 'range': xrange, 32 | 'dict': lambda **kw: kw, 33 | 'lipsum': generate_lorem_ipsum, 34 | 'cycler': Cycler, 35 | 'joiner': Joiner 36 | } 37 | 38 | 39 | # export all constants 40 | __all__ = tuple(x for x in locals().keys() if x.isupper()) 41 | -------------------------------------------------------------------------------- /dinp/jinja2/exceptions.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | jinja2.exceptions 4 | ~~~~~~~~~~~~~~~~~ 5 | 6 | Jinja exceptions. 7 | 8 | :copyright: (c) 2010 by the Jinja Team. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | 12 | 13 | class TemplateError(Exception): 14 | """Baseclass for all template errors.""" 15 | 16 | def __init__(self, message=None): 17 | if message is not None: 18 | message = unicode(message).encode('utf-8') 19 | Exception.__init__(self, message) 20 | 21 | @property 22 | def message(self): 23 | if self.args: 24 | message = self.args[0] 25 | if message is not None: 26 | return message.decode('utf-8', 'replace') 27 | 28 | 29 | class TemplateNotFound(IOError, LookupError, TemplateError): 30 | """Raised if a template does not exist.""" 31 | 32 | # looks weird, but removes the warning descriptor that just 33 | # bogusly warns us about message being deprecated 34 | message = None 35 | 36 | def __init__(self, name, message=None): 37 | IOError.__init__(self) 38 | if message is None: 39 | message = name 40 | self.message = message 41 | self.name = name 42 | self.templates = [name] 43 | 44 | def __str__(self): 45 | return self.message.encode('utf-8') 46 | 47 | # unicode goes after __str__ because we configured 2to3 to rename 48 | # __unicode__ to __str__. because the 2to3 tree is not designed to 49 | # remove nodes from it, we leave the above __str__ around and let 50 | # it override at runtime. 51 | def __unicode__(self): 52 | return self.message 53 | 54 | 55 | class TemplatesNotFound(TemplateNotFound): 56 | """Like :class:`TemplateNotFound` but raised if multiple templates 57 | are selected. This is a subclass of :class:`TemplateNotFound` 58 | exception, so just catching the base exception will catch both. 59 | 60 | .. versionadded:: 2.2 61 | """ 62 | 63 | def __init__(self, names=(), message=None): 64 | if message is None: 65 | message = u'non of the templates given were found: ' + \ 66 | u', '.join(map(unicode, names)) 67 | TemplateNotFound.__init__(self, names and names[-1] or None, message) 68 | self.templates = list(names) 69 | 70 | 71 | class TemplateSyntaxError(TemplateError): 72 | """Raised to tell the user that there is a problem with the template.""" 73 | 74 | def __init__(self, message, lineno, name=None, filename=None): 75 | TemplateError.__init__(self, message) 76 | self.lineno = lineno 77 | self.name = name 78 | self.filename = filename 79 | self.source = None 80 | 81 | # this is set to True if the debug.translate_syntax_error 82 | # function translated the syntax error into a new traceback 83 | self.translated = False 84 | 85 | def __str__(self): 86 | return unicode(self).encode('utf-8') 87 | 88 | # unicode goes after __str__ because we configured 2to3 to rename 89 | # __unicode__ to __str__. because the 2to3 tree is not designed to 90 | # remove nodes from it, we leave the above __str__ around and let 91 | # it override at runtime. 92 | def __unicode__(self): 93 | # for translated errors we only return the message 94 | if self.translated: 95 | return self.message 96 | 97 | # otherwise attach some stuff 98 | location = 'line %d' % self.lineno 99 | name = self.filename or self.name 100 | if name: 101 | location = 'File "%s", %s' % (name, location) 102 | lines = [self.message, ' ' + location] 103 | 104 | # if the source is set, add the line to the output 105 | if self.source is not None: 106 | try: 107 | line = self.source.splitlines()[self.lineno - 1] 108 | except IndexError: 109 | line = None 110 | if line: 111 | lines.append(' ' + line.strip()) 112 | 113 | return u'\n'.join(lines) 114 | 115 | 116 | class TemplateAssertionError(TemplateSyntaxError): 117 | """Like a template syntax error, but covers cases where something in the 118 | template caused an error at compile time that wasn't necessarily caused 119 | by a syntax error. However it's a direct subclass of 120 | :exc:`TemplateSyntaxError` and has the same attributes. 121 | """ 122 | 123 | 124 | class TemplateRuntimeError(TemplateError): 125 | """A generic runtime error in the template engine. Under some situations 126 | Jinja may raise this exception. 127 | """ 128 | 129 | 130 | class UndefinedError(TemplateRuntimeError): 131 | """Raised if a template tries to operate on :class:`Undefined`.""" 132 | 133 | 134 | class SecurityError(TemplateRuntimeError): 135 | """Raised if a template tries to do something insecure if the 136 | sandbox is enabled. 137 | """ 138 | 139 | 140 | class FilterArgumentError(TemplateRuntimeError): 141 | """This error is raised if a filter was called with inappropriate 142 | arguments 143 | """ 144 | -------------------------------------------------------------------------------- /dinp/jinja2/meta.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | jinja2.meta 4 | ~~~~~~~~~~~ 5 | 6 | This module implements various functions that exposes information about 7 | templates that might be interesting for various kinds of applications. 8 | 9 | :copyright: (c) 2010 by the Jinja Team, see AUTHORS for more details. 10 | :license: BSD, see LICENSE for more details. 11 | """ 12 | from jinja2 import nodes 13 | from jinja2.compiler import CodeGenerator 14 | 15 | 16 | class TrackingCodeGenerator(CodeGenerator): 17 | """We abuse the code generator for introspection.""" 18 | 19 | def __init__(self, environment): 20 | CodeGenerator.__init__(self, environment, '', 21 | '') 22 | self.undeclared_identifiers = set() 23 | 24 | def write(self, x): 25 | """Don't write.""" 26 | 27 | def pull_locals(self, frame): 28 | """Remember all undeclared identifiers.""" 29 | self.undeclared_identifiers.update(frame.identifiers.undeclared) 30 | 31 | 32 | def find_undeclared_variables(ast): 33 | """Returns a set of all variables in the AST that will be looked up from 34 | the context at runtime. Because at compile time it's not known which 35 | variables will be used depending on the path the execution takes at 36 | runtime, all variables are returned. 37 | 38 | >>> from jinja2 import Environment, meta 39 | >>> env = Environment() 40 | >>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}') 41 | >>> meta.find_undeclared_variables(ast) 42 | set(['bar']) 43 | 44 | .. admonition:: Implementation 45 | 46 | Internally the code generator is used for finding undeclared variables. 47 | This is good to know because the code generator might raise a 48 | :exc:`TemplateAssertionError` during compilation and as a matter of 49 | fact this function can currently raise that exception as well. 50 | """ 51 | codegen = TrackingCodeGenerator(ast.environment) 52 | codegen.visit(ast) 53 | return codegen.undeclared_identifiers 54 | 55 | 56 | def find_referenced_templates(ast): 57 | """Finds all the referenced templates from the AST. This will return an 58 | iterator over all the hardcoded template extensions, inclusions and 59 | imports. If dynamic inheritance or inclusion is used, `None` will be 60 | yielded. 61 | 62 | >>> from jinja2 import Environment, meta 63 | >>> env = Environment() 64 | >>> ast = env.parse('{% extends "layout.html" %}{% include helper %}') 65 | >>> list(meta.find_referenced_templates(ast)) 66 | ['layout.html', None] 67 | 68 | This function is useful for dependency tracking. For example if you want 69 | to rebuild parts of the website after a layout template has changed. 70 | """ 71 | for node in ast.find_all((nodes.Extends, nodes.FromImport, nodes.Import, 72 | nodes.Include)): 73 | if not isinstance(node.template, nodes.Const): 74 | # a tuple with some non consts in there 75 | if isinstance(node.template, (nodes.Tuple, nodes.List)): 76 | for template_name in node.template.items: 77 | # something const, only yield the strings and ignore 78 | # non-string consts that really just make no sense 79 | if isinstance(template_name, nodes.Const): 80 | if isinstance(template_name.value, basestring): 81 | yield template_name.value 82 | # something dynamic in there 83 | else: 84 | yield None 85 | # something dynamic we don't know about here 86 | else: 87 | yield None 88 | continue 89 | # constant is a basestring, direct template name 90 | if isinstance(node.template.value, basestring): 91 | yield node.template.value 92 | # a tuple or list (latter *should* not happen) made of consts, 93 | # yield the consts that are strings. We could warn here for 94 | # non string values 95 | elif isinstance(node, nodes.Include) and \ 96 | isinstance(node.template.value, (tuple, list)): 97 | for template_name in node.template.value: 98 | if isinstance(template_name, basestring): 99 | yield template_name 100 | # something else we don't care about, we could warn here 101 | else: 102 | yield None 103 | -------------------------------------------------------------------------------- /dinp/jinja2/optimizer.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | jinja2.optimizer 4 | ~~~~~~~~~~~~~~~~ 5 | 6 | The jinja optimizer is currently trying to constant fold a few expressions 7 | and modify the AST in place so that it should be easier to evaluate it. 8 | 9 | Because the AST does not contain all the scoping information and the 10 | compiler has to find that out, we cannot do all the optimizations we 11 | want. For example loop unrolling doesn't work because unrolled loops would 12 | have a different scoping. 13 | 14 | The solution would be a second syntax tree that has the scoping rules stored. 15 | 16 | :copyright: (c) 2010 by the Jinja Team. 17 | :license: BSD. 18 | """ 19 | from jinja2 import nodes 20 | from jinja2.visitor import NodeTransformer 21 | 22 | 23 | def optimize(node, environment): 24 | """The context hint can be used to perform an static optimization 25 | based on the context given.""" 26 | optimizer = Optimizer(environment) 27 | return optimizer.visit(node) 28 | 29 | 30 | class Optimizer(NodeTransformer): 31 | 32 | def __init__(self, environment): 33 | self.environment = environment 34 | 35 | def visit_If(self, node): 36 | """Eliminate dead code.""" 37 | # do not optimize ifs that have a block inside so that it doesn't 38 | # break super(). 39 | if node.find(nodes.Block) is not None: 40 | return self.generic_visit(node) 41 | try: 42 | val = self.visit(node.test).as_const() 43 | except nodes.Impossible: 44 | return self.generic_visit(node) 45 | if val: 46 | body = node.body 47 | else: 48 | body = node.else_ 49 | result = [] 50 | for node in body: 51 | result.extend(self.visit_list(node)) 52 | return result 53 | 54 | def fold(self, node): 55 | """Do constant folding.""" 56 | node = self.generic_visit(node) 57 | try: 58 | return nodes.Const.from_untrusted(node.as_const(), 59 | lineno=node.lineno, 60 | environment=self.environment) 61 | except nodes.Impossible: 62 | return node 63 | 64 | visit_Add = visit_Sub = visit_Mul = visit_Div = visit_FloorDiv = \ 65 | visit_Pow = visit_Mod = visit_And = visit_Or = visit_Pos = visit_Neg = \ 66 | visit_Not = visit_Compare = visit_Getitem = visit_Getattr = visit_Call = \ 67 | visit_Filter = visit_Test = visit_CondExpr = fold 68 | del fold 69 | -------------------------------------------------------------------------------- /dinp/jinja2/tests.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | jinja2.tests 4 | ~~~~~~~~~~~~ 5 | 6 | Jinja test functions. Used with the "is" operator. 7 | 8 | :copyright: (c) 2010 by the Jinja Team. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import re 12 | from jinja2.runtime import Undefined 13 | 14 | try: 15 | from collections import Mapping as MappingType 16 | except ImportError: 17 | import UserDict 18 | MappingType = (UserDict.UserDict, UserDict.DictMixin, dict) 19 | 20 | # nose, nothing here to test 21 | __test__ = False 22 | 23 | 24 | number_re = re.compile(r'^-?\d+(\.\d+)?$') 25 | regex_type = type(number_re) 26 | 27 | 28 | try: 29 | test_callable = callable 30 | except NameError: 31 | def test_callable(x): 32 | return hasattr(x, '__call__') 33 | 34 | 35 | def test_odd(value): 36 | """Return true if the variable is odd.""" 37 | return value % 2 == 1 38 | 39 | 40 | def test_even(value): 41 | """Return true if the variable is even.""" 42 | return value % 2 == 0 43 | 44 | 45 | def test_divisibleby(value, num): 46 | """Check if a variable is divisible by a number.""" 47 | return value % num == 0 48 | 49 | 50 | def test_defined(value): 51 | """Return true if the variable is defined: 52 | 53 | .. sourcecode:: jinja 54 | 55 | {% if variable is defined %} 56 | value of variable: {{ variable }} 57 | {% else %} 58 | variable is not defined 59 | {% endif %} 60 | 61 | See the :func:`default` filter for a simple way to set undefined 62 | variables. 63 | """ 64 | return not isinstance(value, Undefined) 65 | 66 | 67 | def test_undefined(value): 68 | """Like :func:`defined` but the other way round.""" 69 | return isinstance(value, Undefined) 70 | 71 | 72 | def test_none(value): 73 | """Return true if the variable is none.""" 74 | return value is None 75 | 76 | 77 | def test_lower(value): 78 | """Return true if the variable is lowercased.""" 79 | return unicode(value).islower() 80 | 81 | 82 | def test_upper(value): 83 | """Return true if the variable is uppercased.""" 84 | return unicode(value).isupper() 85 | 86 | 87 | def test_string(value): 88 | """Return true if the object is a string.""" 89 | return isinstance(value, basestring) 90 | 91 | 92 | def test_mapping(value): 93 | """Return true if the object is a mapping (dict etc.). 94 | 95 | .. versionadded:: 2.6 96 | """ 97 | return isinstance(value, MappingType) 98 | 99 | 100 | def test_number(value): 101 | """Return true if the variable is a number.""" 102 | return isinstance(value, (int, long, float, complex)) 103 | 104 | 105 | def test_sequence(value): 106 | """Return true if the variable is a sequence. Sequences are variables 107 | that are iterable. 108 | """ 109 | try: 110 | len(value) 111 | value.__getitem__ 112 | except: 113 | return False 114 | return True 115 | 116 | 117 | def test_sameas(value, other): 118 | """Check if an object points to the same memory address than another 119 | object: 120 | 121 | .. sourcecode:: jinja 122 | 123 | {% if foo.attribute is sameas false %} 124 | the foo attribute really is the `False` singleton 125 | {% endif %} 126 | """ 127 | return value is other 128 | 129 | 130 | def test_iterable(value): 131 | """Check if it's possible to iterate over an object.""" 132 | try: 133 | iter(value) 134 | except TypeError: 135 | return False 136 | return True 137 | 138 | 139 | def test_escaped(value): 140 | """Check if the value is escaped.""" 141 | return hasattr(value, '__html__') 142 | 143 | 144 | TESTS = { 145 | 'odd': test_odd, 146 | 'even': test_even, 147 | 'divisibleby': test_divisibleby, 148 | 'defined': test_defined, 149 | 'undefined': test_undefined, 150 | 'none': test_none, 151 | 'lower': test_lower, 152 | 'upper': test_upper, 153 | 'string': test_string, 154 | 'mapping': test_mapping, 155 | 'number': test_number, 156 | 'sequence': test_sequence, 157 | 'iterable': test_iterable, 158 | 'callable': test_callable, 159 | 'sameas': test_sameas, 160 | 'escaped': test_escaped 161 | } 162 | -------------------------------------------------------------------------------- /dinp/jinja2/testsuite/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | jinja2.testsuite 4 | ~~~~~~~~~~~~~~~~ 5 | 6 | All the unittests of Jinja2. These tests can be executed by 7 | either running run-tests.py using multiple Python versions at 8 | the same time. 9 | 10 | :copyright: (c) 2010 by the Jinja Team. 11 | :license: BSD, see LICENSE for more details. 12 | """ 13 | import os 14 | import re 15 | import sys 16 | import unittest 17 | from traceback import format_exception 18 | from jinja2 import loaders 19 | 20 | 21 | here = os.path.dirname(os.path.abspath(__file__)) 22 | 23 | dict_loader = loaders.DictLoader({ 24 | 'justdict.html': 'FOO' 25 | }) 26 | package_loader = loaders.PackageLoader('jinja2.testsuite.res', 'templates') 27 | filesystem_loader = loaders.FileSystemLoader(here + '/res/templates') 28 | function_loader = loaders.FunctionLoader({'justfunction.html': 'FOO'}.get) 29 | choice_loader = loaders.ChoiceLoader([dict_loader, package_loader]) 30 | prefix_loader = loaders.PrefixLoader({ 31 | 'a': filesystem_loader, 32 | 'b': dict_loader 33 | }) 34 | 35 | 36 | class JinjaTestCase(unittest.TestCase): 37 | 38 | ### use only these methods for testing. If you need standard 39 | ### unittest method, wrap them! 40 | 41 | def setup(self): 42 | pass 43 | 44 | def teardown(self): 45 | pass 46 | 47 | def setUp(self): 48 | self.setup() 49 | 50 | def tearDown(self): 51 | self.teardown() 52 | 53 | def assert_equal(self, a, b): 54 | return self.assertEqual(a, b) 55 | 56 | def assert_raises(self, *args, **kwargs): 57 | return self.assertRaises(*args, **kwargs) 58 | 59 | def assert_traceback_matches(self, callback, expected_tb): 60 | try: 61 | callback() 62 | except Exception, e: 63 | tb = format_exception(*sys.exc_info()) 64 | if re.search(expected_tb.strip(), ''.join(tb)) is None: 65 | raise self.fail('Traceback did not match:\n\n%s\nexpected:\n%s' 66 | % (''.join(tb), expected_tb)) 67 | else: 68 | self.fail('Expected exception') 69 | 70 | 71 | def suite(): 72 | from jinja2.testsuite import ext, filters, tests, core_tags, \ 73 | loader, inheritance, imports, lexnparse, security, api, \ 74 | regression, debug, utils, doctests 75 | suite = unittest.TestSuite() 76 | suite.addTest(ext.suite()) 77 | suite.addTest(filters.suite()) 78 | suite.addTest(tests.suite()) 79 | suite.addTest(core_tags.suite()) 80 | suite.addTest(loader.suite()) 81 | suite.addTest(inheritance.suite()) 82 | suite.addTest(imports.suite()) 83 | suite.addTest(lexnparse.suite()) 84 | suite.addTest(security.suite()) 85 | suite.addTest(api.suite()) 86 | suite.addTest(regression.suite()) 87 | suite.addTest(debug.suite()) 88 | suite.addTest(utils.suite()) 89 | 90 | # doctests will not run on python 3 currently. Too many issues 91 | # with that, do not test that on that platform. 92 | if sys.version_info < (3, 0): 93 | suite.addTest(doctests.suite()) 94 | 95 | return suite 96 | -------------------------------------------------------------------------------- /dinp/jinja2/testsuite/debug.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | jinja2.testsuite.debug 4 | ~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Tests the debug system. 7 | 8 | :copyright: (c) 2010 by the Jinja Team. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import sys 12 | import unittest 13 | 14 | from jinja2.testsuite import JinjaTestCase, filesystem_loader 15 | 16 | from jinja2 import Environment, TemplateSyntaxError 17 | 18 | env = Environment(loader=filesystem_loader) 19 | 20 | 21 | class DebugTestCase(JinjaTestCase): 22 | 23 | if sys.version_info[:2] != (2, 4): 24 | def test_runtime_error(self): 25 | def test(): 26 | tmpl.render(fail=lambda: 1 / 0) 27 | tmpl = env.get_template('broken.html') 28 | self.assert_traceback_matches(test, r''' 29 | File ".*?broken.html", line 2, in (top-level template code|) 30 | \{\{ fail\(\) \}\} 31 | File ".*?debug.pyc?", line \d+, in 32 | tmpl\.render\(fail=lambda: 1 / 0\) 33 | ZeroDivisionError: (int(eger)? )?division (or modulo )?by zero 34 | ''') 35 | 36 | def test_syntax_error(self): 37 | # XXX: the .*? is necessary for python3 which does not hide 38 | # some of the stack frames we don't want to show. Not sure 39 | # what's up with that, but that is not that critical. Should 40 | # be fixed though. 41 | self.assert_traceback_matches(lambda: env.get_template('syntaxerror.html'), r'''(?sm) 42 | File ".*?syntaxerror.html", line 4, in (template|) 43 | \{% endif %\}.*? 44 | (jinja2\.exceptions\.)?TemplateSyntaxError: Encountered unknown tag 'endif'. Jinja was looking for the following tags: 'endfor' or 'else'. The innermost block that needs to be closed is 'for'. 45 | ''') 46 | 47 | def test_regular_syntax_error(self): 48 | def test(): 49 | raise TemplateSyntaxError('wtf', 42) 50 | self.assert_traceback_matches(test, r''' 51 | File ".*debug.pyc?", line \d+, in test 52 | raise TemplateSyntaxError\('wtf', 42\) 53 | (jinja2\.exceptions\.)?TemplateSyntaxError: wtf 54 | line 42''') 55 | 56 | 57 | def suite(): 58 | suite = unittest.TestSuite() 59 | suite.addTest(unittest.makeSuite(DebugTestCase)) 60 | return suite 61 | -------------------------------------------------------------------------------- /dinp/jinja2/testsuite/doctests.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | jinja2.testsuite.doctests 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | The doctests. Collects all tests we want to test from 7 | the Jinja modules. 8 | 9 | :copyright: (c) 2010 by the Jinja Team. 10 | :license: BSD, see LICENSE for more details. 11 | """ 12 | import unittest 13 | import doctest 14 | 15 | 16 | def suite(): 17 | from jinja2 import utils, sandbox, runtime, meta, loaders, \ 18 | ext, environment, bccache, nodes 19 | suite = unittest.TestSuite() 20 | suite.addTest(doctest.DocTestSuite(utils)) 21 | suite.addTest(doctest.DocTestSuite(sandbox)) 22 | suite.addTest(doctest.DocTestSuite(runtime)) 23 | suite.addTest(doctest.DocTestSuite(meta)) 24 | suite.addTest(doctest.DocTestSuite(loaders)) 25 | suite.addTest(doctest.DocTestSuite(ext)) 26 | suite.addTest(doctest.DocTestSuite(environment)) 27 | suite.addTest(doctest.DocTestSuite(bccache)) 28 | suite.addTest(doctest.DocTestSuite(nodes)) 29 | return suite 30 | -------------------------------------------------------------------------------- /dinp/jinja2/testsuite/imports.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | jinja2.testsuite.imports 4 | ~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Tests the import features (with includes). 7 | 8 | :copyright: (c) 2010 by the Jinja Team. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import unittest 12 | 13 | from jinja2.testsuite import JinjaTestCase 14 | 15 | from jinja2 import Environment, DictLoader 16 | from jinja2.exceptions import TemplateNotFound, TemplatesNotFound 17 | 18 | 19 | test_env = Environment(loader=DictLoader(dict( 20 | module='{% macro test() %}[{{ foo }}|{{ bar }}]{% endmacro %}', 21 | header='[{{ foo }}|{{ 23 }}]', 22 | o_printer='({{ o }})' 23 | ))) 24 | test_env.globals['bar'] = 23 25 | 26 | 27 | class ImportsTestCase(JinjaTestCase): 28 | 29 | def test_context_imports(self): 30 | t = test_env.from_string('{% import "module" as m %}{{ m.test() }}') 31 | assert t.render(foo=42) == '[|23]' 32 | t = test_env.from_string('{% import "module" as m without context %}{{ m.test() }}') 33 | assert t.render(foo=42) == '[|23]' 34 | t = test_env.from_string('{% import "module" as m with context %}{{ m.test() }}') 35 | assert t.render(foo=42) == '[42|23]' 36 | t = test_env.from_string('{% from "module" import test %}{{ test() }}') 37 | assert t.render(foo=42) == '[|23]' 38 | t = test_env.from_string('{% from "module" import test without context %}{{ test() }}') 39 | assert t.render(foo=42) == '[|23]' 40 | t = test_env.from_string('{% from "module" import test with context %}{{ test() }}') 41 | assert t.render(foo=42) == '[42|23]' 42 | 43 | def test_trailing_comma(self): 44 | test_env.from_string('{% from "foo" import bar, baz with context %}') 45 | test_env.from_string('{% from "foo" import bar, baz, with context %}') 46 | test_env.from_string('{% from "foo" import bar, with context %}') 47 | test_env.from_string('{% from "foo" import bar, with, context %}') 48 | test_env.from_string('{% from "foo" import bar, with with context %}') 49 | 50 | def test_exports(self): 51 | m = test_env.from_string(''' 52 | {% macro toplevel() %}...{% endmacro %} 53 | {% macro __private() %}...{% endmacro %} 54 | {% set variable = 42 %} 55 | {% for item in [1] %} 56 | {% macro notthere() %}{% endmacro %} 57 | {% endfor %} 58 | ''').module 59 | assert m.toplevel() == '...' 60 | assert not hasattr(m, '__missing') 61 | assert m.variable == 42 62 | assert not hasattr(m, 'notthere') 63 | 64 | 65 | class IncludesTestCase(JinjaTestCase): 66 | 67 | def test_context_include(self): 68 | t = test_env.from_string('{% include "header" %}') 69 | assert t.render(foo=42) == '[42|23]' 70 | t = test_env.from_string('{% include "header" with context %}') 71 | assert t.render(foo=42) == '[42|23]' 72 | t = test_env.from_string('{% include "header" without context %}') 73 | assert t.render(foo=42) == '[|23]' 74 | 75 | def test_choice_includes(self): 76 | t = test_env.from_string('{% include ["missing", "header"] %}') 77 | assert t.render(foo=42) == '[42|23]' 78 | 79 | t = test_env.from_string('{% include ["missing", "missing2"] ignore missing %}') 80 | assert t.render(foo=42) == '' 81 | 82 | t = test_env.from_string('{% include ["missing", "missing2"] %}') 83 | self.assert_raises(TemplateNotFound, t.render) 84 | try: 85 | t.render() 86 | except TemplatesNotFound, e: 87 | assert e.templates == ['missing', 'missing2'] 88 | assert e.name == 'missing2' 89 | else: 90 | assert False, 'thou shalt raise' 91 | 92 | def test_includes(t, **ctx): 93 | ctx['foo'] = 42 94 | assert t.render(ctx) == '[42|23]' 95 | 96 | t = test_env.from_string('{% include ["missing", "header"] %}') 97 | test_includes(t) 98 | t = test_env.from_string('{% include x %}') 99 | test_includes(t, x=['missing', 'header']) 100 | t = test_env.from_string('{% include [x, "header"] %}') 101 | test_includes(t, x='missing') 102 | t = test_env.from_string('{% include x %}') 103 | test_includes(t, x='header') 104 | t = test_env.from_string('{% include x %}') 105 | test_includes(t, x='header') 106 | t = test_env.from_string('{% include [x] %}') 107 | test_includes(t, x='header') 108 | 109 | def test_include_ignoring_missing(self): 110 | t = test_env.from_string('{% include "missing" %}') 111 | self.assert_raises(TemplateNotFound, t.render) 112 | for extra in '', 'with context', 'without context': 113 | t = test_env.from_string('{% include "missing" ignore missing ' + 114 | extra + ' %}') 115 | assert t.render() == '' 116 | 117 | def test_context_include_with_overrides(self): 118 | env = Environment(loader=DictLoader(dict( 119 | main="{% for item in [1, 2, 3] %}{% include 'item' %}{% endfor %}", 120 | item="{{ item }}" 121 | ))) 122 | assert env.get_template("main").render() == "123" 123 | 124 | def test_unoptimized_scopes(self): 125 | t = test_env.from_string(""" 126 | {% macro outer(o) %} 127 | {% macro inner() %} 128 | {% include "o_printer" %} 129 | {% endmacro %} 130 | {{ inner() }} 131 | {% endmacro %} 132 | {{ outer("FOO") }} 133 | """) 134 | assert t.render().strip() == '(FOO)' 135 | 136 | 137 | def suite(): 138 | suite = unittest.TestSuite() 139 | suite.addTest(unittest.makeSuite(ImportsTestCase)) 140 | suite.addTest(unittest.makeSuite(IncludesTestCase)) 141 | return suite 142 | -------------------------------------------------------------------------------- /dinp/jinja2/testsuite/res/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dinp/dinp-demo-python-flask/3714bdbf5125c0ea48635ea70087cb58d73f54af/dinp/jinja2/testsuite/res/__init__.py -------------------------------------------------------------------------------- /dinp/jinja2/testsuite/res/templates/broken.html: -------------------------------------------------------------------------------- 1 | Before 2 | {{ fail() }} 3 | After 4 | -------------------------------------------------------------------------------- /dinp/jinja2/testsuite/res/templates/foo/test.html: -------------------------------------------------------------------------------- 1 | FOO 2 | -------------------------------------------------------------------------------- /dinp/jinja2/testsuite/res/templates/syntaxerror.html: -------------------------------------------------------------------------------- 1 | Foo 2 | {% for item in broken %} 3 | ... 4 | {% endif %} 5 | -------------------------------------------------------------------------------- /dinp/jinja2/testsuite/res/templates/test.html: -------------------------------------------------------------------------------- 1 | BAR 2 | -------------------------------------------------------------------------------- /dinp/jinja2/testsuite/tests.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | jinja2.testsuite.tests 4 | ~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Who tests the tests? 7 | 8 | :copyright: (c) 2010 by the Jinja Team. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import unittest 12 | from jinja2.testsuite import JinjaTestCase 13 | 14 | from jinja2 import Markup, Environment 15 | 16 | env = Environment() 17 | 18 | 19 | class TestsTestCase(JinjaTestCase): 20 | 21 | def test_defined(self): 22 | tmpl = env.from_string('{{ missing is defined }}|{{ true is defined }}') 23 | assert tmpl.render() == 'False|True' 24 | 25 | def test_even(self): 26 | tmpl = env.from_string('''{{ 1 is even }}|{{ 2 is even }}''') 27 | assert tmpl.render() == 'False|True' 28 | 29 | def test_odd(self): 30 | tmpl = env.from_string('''{{ 1 is odd }}|{{ 2 is odd }}''') 31 | assert tmpl.render() == 'True|False' 32 | 33 | def test_lower(self): 34 | tmpl = env.from_string('''{{ "foo" is lower }}|{{ "FOO" is lower }}''') 35 | assert tmpl.render() == 'True|False' 36 | 37 | def test_typechecks(self): 38 | tmpl = env.from_string(''' 39 | {{ 42 is undefined }} 40 | {{ 42 is defined }} 41 | {{ 42 is none }} 42 | {{ none is none }} 43 | {{ 42 is number }} 44 | {{ 42 is string }} 45 | {{ "foo" is string }} 46 | {{ "foo" is sequence }} 47 | {{ [1] is sequence }} 48 | {{ range is callable }} 49 | {{ 42 is callable }} 50 | {{ range(5) is iterable }} 51 | {{ {} is mapping }} 52 | {{ mydict is mapping }} 53 | {{ [] is mapping }} 54 | ''') 55 | class MyDict(dict): 56 | pass 57 | assert tmpl.render(mydict=MyDict()).split() == [ 58 | 'False', 'True', 'False', 'True', 'True', 'False', 59 | 'True', 'True', 'True', 'True', 'False', 'True', 60 | 'True', 'True', 'False' 61 | ] 62 | 63 | def test_sequence(self): 64 | tmpl = env.from_string( 65 | '{{ [1, 2, 3] is sequence }}|' 66 | '{{ "foo" is sequence }}|' 67 | '{{ 42 is sequence }}' 68 | ) 69 | assert tmpl.render() == 'True|True|False' 70 | 71 | def test_upper(self): 72 | tmpl = env.from_string('{{ "FOO" is upper }}|{{ "foo" is upper }}') 73 | assert tmpl.render() == 'True|False' 74 | 75 | def test_sameas(self): 76 | tmpl = env.from_string('{{ foo is sameas false }}|' 77 | '{{ 0 is sameas false }}') 78 | assert tmpl.render(foo=False) == 'True|False' 79 | 80 | def test_no_paren_for_arg1(self): 81 | tmpl = env.from_string('{{ foo is sameas none }}') 82 | assert tmpl.render(foo=None) == 'True' 83 | 84 | def test_escaped(self): 85 | env = Environment(autoescape=True) 86 | tmpl = env.from_string('{{ x is escaped }}|{{ y is escaped }}') 87 | assert tmpl.render(x='foo', y=Markup('foo')) == 'False|True' 88 | 89 | 90 | def suite(): 91 | suite = unittest.TestSuite() 92 | suite.addTest(unittest.makeSuite(TestsTestCase)) 93 | return suite 94 | -------------------------------------------------------------------------------- /dinp/jinja2/testsuite/utils.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | jinja2.testsuite.utils 4 | ~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Tests utilities jinja uses. 7 | 8 | :copyright: (c) 2010 by the Jinja Team. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import gc 12 | import unittest 13 | 14 | import pickle 15 | 16 | from jinja2.testsuite import JinjaTestCase 17 | 18 | from jinja2.utils import LRUCache, escape, object_type_repr 19 | 20 | 21 | class LRUCacheTestCase(JinjaTestCase): 22 | 23 | def test_simple(self): 24 | d = LRUCache(3) 25 | d["a"] = 1 26 | d["b"] = 2 27 | d["c"] = 3 28 | d["a"] 29 | d["d"] = 4 30 | assert len(d) == 3 31 | assert 'a' in d and 'c' in d and 'd' in d and 'b' not in d 32 | 33 | def test_pickleable(self): 34 | cache = LRUCache(2) 35 | cache["foo"] = 42 36 | cache["bar"] = 23 37 | cache["foo"] 38 | 39 | for protocol in range(3): 40 | copy = pickle.loads(pickle.dumps(cache, protocol)) 41 | assert copy.capacity == cache.capacity 42 | assert copy._mapping == cache._mapping 43 | assert copy._queue == cache._queue 44 | 45 | 46 | class HelpersTestCase(JinjaTestCase): 47 | 48 | def test_object_type_repr(self): 49 | class X(object): 50 | pass 51 | self.assert_equal(object_type_repr(42), 'int object') 52 | self.assert_equal(object_type_repr([]), 'list object') 53 | self.assert_equal(object_type_repr(X()), 54 | 'jinja2.testsuite.utils.X object') 55 | self.assert_equal(object_type_repr(None), 'None') 56 | self.assert_equal(object_type_repr(Ellipsis), 'Ellipsis') 57 | 58 | 59 | class MarkupLeakTestCase(JinjaTestCase): 60 | 61 | def test_markup_leaks(self): 62 | counts = set() 63 | for count in xrange(20): 64 | for item in xrange(1000): 65 | escape("foo") 66 | escape("") 67 | escape(u"foo") 68 | escape(u"") 69 | counts.add(len(gc.get_objects())) 70 | assert len(counts) == 1, 'ouch, c extension seems to leak objects' 71 | 72 | 73 | def suite(): 74 | suite = unittest.TestSuite() 75 | suite.addTest(unittest.makeSuite(LRUCacheTestCase)) 76 | suite.addTest(unittest.makeSuite(HelpersTestCase)) 77 | 78 | # this test only tests the c extension 79 | if not hasattr(escape, 'func_code'): 80 | suite.addTest(unittest.makeSuite(MarkupLeakTestCase)) 81 | 82 | return suite 83 | -------------------------------------------------------------------------------- /dinp/jinja2/visitor.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | jinja2.visitor 4 | ~~~~~~~~~~~~~~ 5 | 6 | This module implements a visitor for the nodes. 7 | 8 | :copyright: (c) 2010 by the Jinja Team. 9 | :license: BSD. 10 | """ 11 | from jinja2.nodes import Node 12 | 13 | 14 | class NodeVisitor(object): 15 | """Walks the abstract syntax tree and call visitor functions for every 16 | node found. The visitor functions may return values which will be 17 | forwarded by the `visit` method. 18 | 19 | Per default the visitor functions for the nodes are ``'visit_'`` + 20 | class name of the node. So a `TryFinally` node visit function would 21 | be `visit_TryFinally`. This behavior can be changed by overriding 22 | the `get_visitor` function. If no visitor function exists for a node 23 | (return value `None`) the `generic_visit` visitor is used instead. 24 | """ 25 | 26 | def get_visitor(self, node): 27 | """Return the visitor function for this node or `None` if no visitor 28 | exists for this node. In that case the generic visit function is 29 | used instead. 30 | """ 31 | method = 'visit_' + node.__class__.__name__ 32 | return getattr(self, method, None) 33 | 34 | def visit(self, node, *args, **kwargs): 35 | """Visit a node.""" 36 | f = self.get_visitor(node) 37 | if f is not None: 38 | return f(node, *args, **kwargs) 39 | return self.generic_visit(node, *args, **kwargs) 40 | 41 | def generic_visit(self, node, *args, **kwargs): 42 | """Called if no explicit visitor function exists for a node.""" 43 | for node in node.iter_child_nodes(): 44 | self.visit(node, *args, **kwargs) 45 | 46 | 47 | class NodeTransformer(NodeVisitor): 48 | """Walks the abstract syntax tree and allows modifications of nodes. 49 | 50 | The `NodeTransformer` will walk the AST and use the return value of the 51 | visitor functions to replace or remove the old node. If the return 52 | value of the visitor function is `None` the node will be removed 53 | from the previous location otherwise it's replaced with the return 54 | value. The return value may be the original node in which case no 55 | replacement takes place. 56 | """ 57 | 58 | def generic_visit(self, node, *args, **kwargs): 59 | for field, old_value in node.iter_fields(): 60 | if isinstance(old_value, list): 61 | new_values = [] 62 | for value in old_value: 63 | if isinstance(value, Node): 64 | value = self.visit(value, *args, **kwargs) 65 | if value is None: 66 | continue 67 | elif not isinstance(value, Node): 68 | new_values.extend(value) 69 | continue 70 | new_values.append(value) 71 | old_value[:] = new_values 72 | elif isinstance(old_value, Node): 73 | new_node = self.visit(old_value, *args, **kwargs) 74 | if new_node is None: 75 | delattr(node, field) 76 | else: 77 | setattr(node, field, new_node) 78 | return node 79 | 80 | def visit_list(self, node, *args, **kwargs): 81 | """As transformers may return lists in some places this method 82 | can be used to enforce a list as return value. 83 | """ 84 | rv = self.visit(node, *args, **kwargs) 85 | if not isinstance(rv, list): 86 | rv = [rv] 87 | return rv 88 | -------------------------------------------------------------------------------- /dinp/werkzeug/contrib/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.contrib 4 | ~~~~~~~~~~~~~~~~ 5 | 6 | Contains user-submitted code that other users may find useful, but which 7 | is not part of the Werkzeug core. Anyone can write code for inclusion in 8 | the `contrib` package. All modules in this package are distributed as an 9 | add-on library and thus are not part of Werkzeug itself. 10 | 11 | This file itself is mostly for informational purposes and to tell the 12 | Python interpreter that `contrib` is a package. 13 | 14 | :copyright: (c) 2011 by the Werkzeug Team, see AUTHORS for more details. 15 | :license: BSD, see LICENSE for more details. 16 | """ 17 | -------------------------------------------------------------------------------- /dinp/werkzeug/contrib/limiter.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.contrib.limiter 4 | ~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | A middleware that limits incoming data. This works around problems with 7 | Trac_ or Django_ because those directly stream into the memory. 8 | 9 | .. _Trac: http://trac.edgewall.org/ 10 | .. _Django: http://www.djangoproject.com/ 11 | 12 | :copyright: (c) 2011 by the Werkzeug Team, see AUTHORS for more details. 13 | :license: BSD, see LICENSE for more details. 14 | """ 15 | from warnings import warn 16 | 17 | from werkzeug.wsgi import LimitedStream 18 | 19 | 20 | class StreamLimitMiddleware(object): 21 | """Limits the input stream to a given number of bytes. This is useful if 22 | you have a WSGI application that reads form data into memory (django for 23 | example) and you don't want users to harm the server by uploading tons of 24 | data. 25 | 26 | Default is 10MB 27 | """ 28 | 29 | def __init__(self, app, maximum_size=1024 * 1024 * 10): 30 | self.app = app 31 | self.maximum_size = maximum_size 32 | 33 | def __call__(self, environ, start_response): 34 | limit = min(self.maximum_size, int(environ.get('CONTENT_LENGTH') or 0)) 35 | environ['wsgi.input'] = LimitedStream(environ['wsgi.input'], limit) 36 | return self.app(environ, start_response) 37 | -------------------------------------------------------------------------------- /dinp/werkzeug/contrib/profiler.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.contrib.profiler 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | This module provides a simple WSGI profiler middleware for finding 7 | bottlenecks in web application. It uses the :mod:`profile` or 8 | :mod:`cProfile` module to do the profiling and writes the stats to the 9 | stream provided (defaults to stderr). 10 | 11 | Example usage:: 12 | 13 | from werkzeug.contrib.profiler import ProfilerMiddleware 14 | app = ProfilerMiddleware(app) 15 | 16 | :copyright: (c) 2011 by the Werkzeug Team, see AUTHORS for more details. 17 | :license: BSD, see LICENSE for more details. 18 | """ 19 | import sys 20 | try: 21 | try: 22 | from cProfile import Profile 23 | except ImportError: 24 | from profile import Profile 25 | from pstats import Stats 26 | available = True 27 | except ImportError: 28 | available = False 29 | 30 | 31 | class MergeStream(object): 32 | """An object that redirects `write` calls to multiple streams. 33 | Use this to log to both `sys.stdout` and a file:: 34 | 35 | f = open('profiler.log', 'w') 36 | stream = MergeStream(sys.stdout, f) 37 | profiler = ProfilerMiddleware(app, stream) 38 | """ 39 | 40 | def __init__(self, *streams): 41 | if not streams: 42 | raise TypeError('at least one stream must be given') 43 | self.streams = streams 44 | 45 | def write(self, data): 46 | for stream in self.streams: 47 | stream.write(data) 48 | 49 | 50 | class ProfilerMiddleware(object): 51 | """Simple profiler middleware. Wraps a WSGI application and profiles 52 | a request. This intentionally buffers the response so that timings are 53 | more exact. 54 | 55 | For the exact meaning of `sort_by` and `restrictions` consult the 56 | :mod:`profile` documentation. 57 | 58 | :param app: the WSGI application to profile. 59 | :param stream: the stream for the profiled stats. defaults to stderr. 60 | :param sort_by: a tuple of columns to sort the result by. 61 | :param restrictions: a tuple of profiling strictions. 62 | """ 63 | 64 | def __init__(self, app, stream=None, 65 | sort_by=('time', 'calls'), restrictions=()): 66 | if not available: 67 | raise RuntimeError('the profiler is not available because ' 68 | 'profile or pstat is not installed.') 69 | self._app = app 70 | self._stream = stream or sys.stdout 71 | self._sort_by = sort_by 72 | self._restrictions = restrictions 73 | 74 | def __call__(self, environ, start_response): 75 | response_body = [] 76 | 77 | def catching_start_response(status, headers, exc_info=None): 78 | start_response(status, headers, exc_info) 79 | return response_body.append 80 | 81 | def runapp(): 82 | appiter = self._app(environ, catching_start_response) 83 | response_body.extend(appiter) 84 | if hasattr(appiter, 'close'): 85 | appiter.close() 86 | 87 | p = Profile() 88 | p.runcall(runapp) 89 | body = ''.join(response_body) 90 | stats = Stats(p, stream=self._stream) 91 | stats.sort_stats(*self._sort_by) 92 | 93 | self._stream.write('-' * 80) 94 | self._stream.write('\nPATH: %r\n' % environ.get('PATH_INFO')) 95 | stats.print_stats(*self._restrictions) 96 | self._stream.write('-' * 80 + '\n\n') 97 | 98 | return [body] 99 | 100 | 101 | def make_action(app_factory, hostname='localhost', port=5000, 102 | threaded=False, processes=1, stream=None, 103 | sort_by=('time', 'calls'), restrictions=()): 104 | """Return a new callback for :mod:`werkzeug.script` that starts a local 105 | server with the profiler enabled. 106 | 107 | :: 108 | 109 | from werkzeug.contrib import profiler 110 | action_profile = profiler.make_action(make_app) 111 | """ 112 | def action(hostname=('h', hostname), port=('p', port), 113 | threaded=threaded, processes=processes): 114 | """Start a new development server.""" 115 | from werkzeug.serving import run_simple 116 | app = ProfilerMiddleware(app_factory(), stream, sort_by, restrictions) 117 | run_simple(hostname, port, app, False, None, threaded, processes) 118 | return action 119 | -------------------------------------------------------------------------------- /dinp/werkzeug/contrib/testtools.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.contrib.testtools 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | This module implements extended wrappers for simplified testing. 7 | 8 | `TestResponse` 9 | A response wrapper which adds various cached attributes for 10 | simplified assertions on various content types. 11 | 12 | :copyright: (c) 2011 by the Werkzeug Team, see AUTHORS for more details. 13 | :license: BSD, see LICENSE for more details. 14 | """ 15 | from werkzeug.utils import cached_property, import_string 16 | from werkzeug.wrappers import Response 17 | 18 | from warnings import warn 19 | warn(DeprecationWarning('werkzeug.contrib.testtools is deprecated and ' 20 | 'will be removed with Werkzeug 1.0')) 21 | 22 | 23 | class ContentAccessors(object): 24 | """ 25 | A mixin class for response objects that provides a couple of useful 26 | accessors for unittesting. 27 | """ 28 | 29 | def xml(self): 30 | """Get an etree if possible.""" 31 | if 'xml' not in self.mimetype: 32 | raise AttributeError( 33 | 'Not a XML response (Content-Type: %s)' 34 | % self.mimetype) 35 | for module in ['xml.etree.ElementTree', 'ElementTree', 36 | 'elementtree.ElementTree']: 37 | etree = import_string(module, silent=True) 38 | if etree is not None: 39 | return etree.XML(self.body) 40 | raise RuntimeError('You must have ElementTree installed ' 41 | 'to use TestResponse.xml') 42 | xml = cached_property(xml) 43 | 44 | def lxml(self): 45 | """Get an lxml etree if possible.""" 46 | if ('html' not in self.mimetype and 'xml' not in self.mimetype): 47 | raise AttributeError('Not an HTML/XML response') 48 | from lxml import etree 49 | try: 50 | from lxml.html import fromstring 51 | except ImportError: 52 | fromstring = etree.HTML 53 | if self.mimetype=='text/html': 54 | return fromstring(self.data) 55 | return etree.XML(self.data) 56 | lxml = cached_property(lxml) 57 | 58 | def json(self): 59 | """Get the result of simplejson.loads if possible.""" 60 | if 'json' not in self.mimetype: 61 | raise AttributeError('Not a JSON response') 62 | try: 63 | from simplejson import loads 64 | except ImportError: 65 | from json import loads 66 | return loads(self.data) 67 | json = cached_property(json) 68 | 69 | 70 | class TestResponse(Response, ContentAccessors): 71 | """Pass this to `werkzeug.test.Client` for easier unittesting.""" 72 | -------------------------------------------------------------------------------- /dinp/werkzeug/debug/console.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.debug.console 4 | ~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Interactive console support. 7 | 8 | :copyright: (c) 2011 by the Werkzeug Team, see AUTHORS for more details. 9 | :license: BSD. 10 | """ 11 | import sys 12 | import code 13 | from types import CodeType 14 | from werkzeug.utils import escape 15 | from werkzeug.local import Local 16 | from werkzeug.debug.repr import debug_repr, dump, helper 17 | 18 | 19 | _local = Local() 20 | 21 | 22 | class HTMLStringO(object): 23 | """A StringO version that HTML escapes on write.""" 24 | 25 | def __init__(self): 26 | self._buffer = [] 27 | 28 | def isatty(self): 29 | return False 30 | 31 | def close(self): 32 | pass 33 | 34 | def flush(self): 35 | pass 36 | 37 | def seek(self, n, mode=0): 38 | pass 39 | 40 | def readline(self): 41 | if len(self._buffer) == 0: 42 | return '' 43 | ret = self._buffer[0] 44 | del self._buffer[0] 45 | return ret 46 | 47 | def reset(self): 48 | val = ''.join(self._buffer) 49 | del self._buffer[:] 50 | return val 51 | 52 | def _write(self, x): 53 | if isinstance(x, str): 54 | x = x.decode('utf-8', 'replace') 55 | self._buffer.append(x) 56 | 57 | def write(self, x): 58 | self._write(escape(x)) 59 | 60 | def writelines(self, x): 61 | self._write(escape(''.join(x))) 62 | 63 | 64 | class ThreadedStream(object): 65 | """Thread-local wrapper for sys.stdout for the interactive console.""" 66 | 67 | def push(): 68 | if not isinstance(sys.stdout, ThreadedStream): 69 | sys.stdout = ThreadedStream() 70 | _local.stream = HTMLStringO() 71 | push = staticmethod(push) 72 | 73 | def fetch(): 74 | try: 75 | stream = _local.stream 76 | except AttributeError: 77 | return '' 78 | return stream.reset() 79 | fetch = staticmethod(fetch) 80 | 81 | def displayhook(obj): 82 | try: 83 | stream = _local.stream 84 | except AttributeError: 85 | return _displayhook(obj) 86 | # stream._write bypasses escaping as debug_repr is 87 | # already generating HTML for us. 88 | if obj is not None: 89 | stream._write(debug_repr(obj)) 90 | displayhook = staticmethod(displayhook) 91 | 92 | def __setattr__(self, name, value): 93 | raise AttributeError('read only attribute %s' % name) 94 | 95 | def __dir__(self): 96 | return dir(sys.__stdout__) 97 | 98 | def __getattribute__(self, name): 99 | if name == '__members__': 100 | return dir(sys.__stdout__) 101 | try: 102 | stream = _local.stream 103 | except AttributeError: 104 | stream = sys.__stdout__ 105 | return getattr(stream, name) 106 | 107 | def __repr__(self): 108 | return repr(sys.__stdout__) 109 | 110 | 111 | # add the threaded stream as display hook 112 | _displayhook = sys.displayhook 113 | sys.displayhook = ThreadedStream.displayhook 114 | 115 | 116 | class _ConsoleLoader(object): 117 | 118 | def __init__(self): 119 | self._storage = {} 120 | 121 | def register(self, code, source): 122 | self._storage[id(code)] = source 123 | # register code objects of wrapped functions too. 124 | for var in code.co_consts: 125 | if isinstance(var, CodeType): 126 | self._storage[id(var)] = source 127 | 128 | def get_source_by_code(self, code): 129 | try: 130 | return self._storage[id(code)] 131 | except KeyError: 132 | pass 133 | 134 | 135 | def _wrap_compiler(console): 136 | compile = console.compile 137 | def func(source, filename, symbol): 138 | code = compile(source, filename, symbol) 139 | console.loader.register(code, source) 140 | return code 141 | console.compile = func 142 | 143 | 144 | class _InteractiveConsole(code.InteractiveInterpreter): 145 | 146 | def __init__(self, globals, locals): 147 | code.InteractiveInterpreter.__init__(self, locals) 148 | self.globals = dict(globals) 149 | self.globals['dump'] = dump 150 | self.globals['help'] = helper 151 | self.globals['__loader__'] = self.loader = _ConsoleLoader() 152 | self.more = False 153 | self.buffer = [] 154 | _wrap_compiler(self) 155 | 156 | def runsource(self, source): 157 | source = source.rstrip() + '\n' 158 | ThreadedStream.push() 159 | prompt = self.more and '... ' or '>>> ' 160 | try: 161 | source_to_eval = ''.join(self.buffer + [source]) 162 | if code.InteractiveInterpreter.runsource(self, 163 | source_to_eval, '', 'single'): 164 | self.more = True 165 | self.buffer.append(source) 166 | else: 167 | self.more = False 168 | del self.buffer[:] 169 | finally: 170 | output = ThreadedStream.fetch() 171 | return prompt + source + output 172 | 173 | def runcode(self, code): 174 | try: 175 | exec code in self.globals, self.locals 176 | except Exception: 177 | self.showtraceback() 178 | 179 | def showtraceback(self): 180 | from werkzeug.debug.tbtools import get_current_traceback 181 | tb = get_current_traceback(skip=1) 182 | sys.stdout._write(tb.render_summary()) 183 | 184 | def showsyntaxerror(self, filename=None): 185 | from werkzeug.debug.tbtools import get_current_traceback 186 | tb = get_current_traceback(skip=4) 187 | sys.stdout._write(tb.render_summary()) 188 | 189 | def write(self, data): 190 | sys.stdout.write(data) 191 | 192 | 193 | class Console(object): 194 | """An interactive console.""" 195 | 196 | def __init__(self, globals=None, locals=None): 197 | if locals is None: 198 | locals = {} 199 | if globals is None: 200 | globals = {} 201 | self._ipy = _InteractiveConsole(globals, locals) 202 | 203 | def eval(self, code): 204 | old_sys_stdout = sys.stdout 205 | try: 206 | return self._ipy.runsource(code) 207 | finally: 208 | sys.stdout = old_sys_stdout 209 | -------------------------------------------------------------------------------- /dinp/werkzeug/debug/shared/FONT_LICENSE: -------------------------------------------------------------------------------- 1 | ------------------------------- 2 | UBUNTU FONT LICENCE Version 1.0 3 | ------------------------------- 4 | 5 | PREAMBLE 6 | This licence allows the licensed fonts to be used, studied, modified and 7 | redistributed freely. The fonts, including any derivative works, can be 8 | bundled, embedded, and redistributed provided the terms of this licence 9 | are met. The fonts and derivatives, however, cannot be released under 10 | any other licence. The requirement for fonts to remain under this 11 | licence does not require any document created using the fonts or their 12 | derivatives to be published under this licence, as long as the primary 13 | purpose of the document is not to be a vehicle for the distribution of 14 | the fonts. 15 | 16 | DEFINITIONS 17 | "Font Software" refers to the set of files released by the Copyright 18 | Holder(s) under this licence and clearly marked as such. This may 19 | include source files, build scripts and documentation. 20 | 21 | "Original Version" refers to the collection of Font Software components 22 | as received under this licence. 23 | 24 | "Modified Version" refers to any derivative made by adding to, deleting, 25 | or substituting -- in part or in whole -- any of the components of the 26 | Original Version, by changing formats or by porting the Font Software to 27 | a new environment. 28 | 29 | "Copyright Holder(s)" refers to all individuals and companies who have a 30 | copyright ownership of the Font Software. 31 | 32 | "Substantially Changed" refers to Modified Versions which can be easily 33 | identified as dissimilar to the Font Software by users of the Font 34 | Software comparing the Original Version with the Modified Version. 35 | 36 | To "Propagate" a work means to do anything with it that, without 37 | permission, would make you directly or secondarily liable for 38 | infringement under applicable copyright law, except executing it on a 39 | computer or modifying a private copy. Propagation includes copying, 40 | distribution (with or without modification and with or without charging 41 | a redistribution fee), making available to the public, and in some 42 | countries other activities as well. 43 | 44 | PERMISSION & CONDITIONS 45 | This licence does not grant any rights under trademark law and all such 46 | rights are reserved. 47 | 48 | Permission is hereby granted, free of charge, to any person obtaining a 49 | copy of the Font Software, to propagate the Font Software, subject to 50 | the below conditions: 51 | 52 | 1) Each copy of the Font Software must contain the above copyright 53 | notice and this licence. These can be included either as stand-alone 54 | text files, human-readable headers or in the appropriate machine- 55 | readable metadata fields within text or binary files as long as those 56 | fields can be easily viewed by the user. 57 | 58 | 2) The font name complies with the following: 59 | (a) The Original Version must retain its name, unmodified. 60 | (b) Modified Versions which are Substantially Changed must be renamed to 61 | avoid use of the name of the Original Version or similar names entirely. 62 | (c) Modified Versions which are not Substantially Changed must be 63 | renamed to both (i) retain the name of the Original Version and (ii) add 64 | additional naming elements to distinguish the Modified Version from the 65 | Original Version. The name of such Modified Versions must be the name of 66 | the Original Version, with "derivative X" where X represents the name of 67 | the new work, appended to that name. 68 | 69 | 3) The name(s) of the Copyright Holder(s) and any contributor to the 70 | Font Software shall not be used to promote, endorse or advertise any 71 | Modified Version, except (i) as required by this licence, (ii) to 72 | acknowledge the contribution(s) of the Copyright Holder(s) or (iii) with 73 | their explicit written permission. 74 | 75 | 4) The Font Software, modified or unmodified, in part or in whole, must 76 | be distributed entirely under this licence, and must not be distributed 77 | under any other licence. The requirement for fonts to remain under this 78 | licence does not affect any document created using the Font Software, 79 | except any version of the Font Software extracted from a document 80 | created using the Font Software may only be distributed under this 81 | licence. 82 | 83 | TERMINATION 84 | This licence becomes null and void if any of the above conditions are 85 | not met. 86 | 87 | DISCLAIMER 88 | THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 89 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF 90 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF 91 | COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE 92 | COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 93 | INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL 94 | DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 95 | FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER 96 | DEALINGS IN THE FONT SOFTWARE. 97 | -------------------------------------------------------------------------------- /dinp/werkzeug/debug/shared/console.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dinp/dinp-demo-python-flask/3714bdbf5125c0ea48635ea70087cb58d73f54af/dinp/werkzeug/debug/shared/console.png -------------------------------------------------------------------------------- /dinp/werkzeug/debug/shared/less.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dinp/dinp-demo-python-flask/3714bdbf5125c0ea48635ea70087cb58d73f54af/dinp/werkzeug/debug/shared/less.png -------------------------------------------------------------------------------- /dinp/werkzeug/debug/shared/more.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dinp/dinp-demo-python-flask/3714bdbf5125c0ea48635ea70087cb58d73f54af/dinp/werkzeug/debug/shared/more.png -------------------------------------------------------------------------------- /dinp/werkzeug/debug/shared/source.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dinp/dinp-demo-python-flask/3714bdbf5125c0ea48635ea70087cb58d73f54af/dinp/werkzeug/debug/shared/source.png -------------------------------------------------------------------------------- /dinp/werkzeug/debug/shared/ubuntu.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dinp/dinp-demo-python-flask/3714bdbf5125c0ea48635ea70087cb58d73f54af/dinp/werkzeug/debug/shared/ubuntu.ttf -------------------------------------------------------------------------------- /dinp/werkzeug/posixemulation.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | r""" 3 | werkzeug.posixemulation 4 | ~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Provides a POSIX emulation for some features that are relevant to 7 | web applications. The main purpose is to simplify support for 8 | systems such as Windows NT that are not 100% POSIX compatible. 9 | 10 | Currently this only implements a :func:`rename` function that 11 | follows POSIX semantics. Eg: if the target file already exists it 12 | will be replaced without asking. 13 | 14 | This module was introduced in 0.6.1 and is not a public interface. 15 | It might become one in later versions of Werkzeug. 16 | 17 | :copyright: (c) 2011 by the Werkzeug Team, see AUTHORS for more details. 18 | :license: BSD, see LICENSE for more details. 19 | """ 20 | import sys 21 | import os 22 | import errno 23 | import time 24 | import random 25 | 26 | 27 | can_rename_open_file = False 28 | if os.name == 'nt': # pragma: no cover 29 | _rename = lambda src, dst: False 30 | _rename_atomic = lambda src, dst: False 31 | 32 | try: 33 | import ctypes 34 | 35 | _MOVEFILE_REPLACE_EXISTING = 0x1 36 | _MOVEFILE_WRITE_THROUGH = 0x8 37 | _MoveFileEx = ctypes.windll.kernel32.MoveFileExW 38 | 39 | def _rename(src, dst): 40 | if not isinstance(src, unicode): 41 | src = unicode(src, sys.getfilesystemencoding()) 42 | if not isinstance(dst, unicode): 43 | dst = unicode(dst, sys.getfilesystemencoding()) 44 | if _rename_atomic(src, dst): 45 | return True 46 | retry = 0 47 | rv = False 48 | while not rv and retry < 100: 49 | rv = _MoveFileEx(src, dst, _MOVEFILE_REPLACE_EXISTING | 50 | _MOVEFILE_WRITE_THROUGH) 51 | if not rv: 52 | time.sleep(0.001) 53 | retry += 1 54 | return rv 55 | 56 | # new in Vista and Windows Server 2008 57 | _CreateTransaction = ctypes.windll.ktmw32.CreateTransaction 58 | _CommitTransaction = ctypes.windll.ktmw32.CommitTransaction 59 | _MoveFileTransacted = ctypes.windll.kernel32.MoveFileTransactedW 60 | _CloseHandle = ctypes.windll.kernel32.CloseHandle 61 | can_rename_open_file = True 62 | 63 | def _rename_atomic(src, dst): 64 | ta = _CreateTransaction(None, 0, 0, 0, 0, 1000, 'Werkzeug rename') 65 | if ta == -1: 66 | return False 67 | try: 68 | retry = 0 69 | rv = False 70 | while not rv and retry < 100: 71 | rv = _MoveFileTransacted(src, dst, None, None, 72 | _MOVEFILE_REPLACE_EXISTING | 73 | _MOVEFILE_WRITE_THROUGH, ta) 74 | if rv: 75 | rv = _CommitTransaction(ta) 76 | break 77 | else: 78 | time.sleep(0.001) 79 | retry += 1 80 | return rv 81 | finally: 82 | _CloseHandle(ta) 83 | except Exception: 84 | pass 85 | 86 | def rename(src, dst): 87 | # Try atomic or pseudo-atomic rename 88 | if _rename(src, dst): 89 | return 90 | # Fall back to "move away and replace" 91 | try: 92 | os.rename(src, dst) 93 | except OSError, e: 94 | if e.errno != errno.EEXIST: 95 | raise 96 | old = "%s-%08x" % (dst, random.randint(0, sys.maxint)) 97 | os.rename(dst, old) 98 | os.rename(src, dst) 99 | try: 100 | os.unlink(old) 101 | except Exception: 102 | pass 103 | else: 104 | rename = os.rename 105 | can_rename_open_file = True 106 | -------------------------------------------------------------------------------- /dinp/werkzeug/security.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.security 4 | ~~~~~~~~~~~~~~~~~ 5 | 6 | Security related helpers such as secure password hashing tools. 7 | 8 | :copyright: (c) 2011 by the Werkzeug Team, see AUTHORS for more details. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import os 12 | import hmac 13 | import posixpath 14 | from itertools import izip 15 | from random import SystemRandom 16 | 17 | # because the API of hmac changed with the introduction of the 18 | # new hashlib module, we have to support both. This sets up a 19 | # mapping to the digest factory functions and the digest modules 20 | # (or factory functions with changed API) 21 | try: 22 | from hashlib import sha1, md5 23 | _hash_funcs = _hash_mods = {'sha1': sha1, 'md5': md5} 24 | _sha1_mod = sha1 25 | _md5_mod = md5 26 | except ImportError: 27 | import sha as _sha1_mod, md5 as _md5_mod 28 | _hash_mods = {'sha1': _sha1_mod, 'md5': _md5_mod} 29 | _hash_funcs = {'sha1': _sha1_mod.new, 'md5': _md5_mod.new} 30 | 31 | 32 | SALT_CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' 33 | 34 | 35 | _sys_rng = SystemRandom() 36 | _os_alt_seps = list(sep for sep in [os.path.sep, os.path.altsep] 37 | if sep not in (None, '/')) 38 | 39 | 40 | def safe_str_cmp(a, b): 41 | """This function compares strings in somewhat constant time. This 42 | requires that the length of at least one string is known in advance. 43 | 44 | Returns `True` if the two strings are equal or `False` if they are not. 45 | 46 | .. versionadded:: 0.7 47 | """ 48 | if len(a) != len(b): 49 | return False 50 | rv = 0 51 | for x, y in izip(a, b): 52 | rv |= ord(x) ^ ord(y) 53 | return rv == 0 54 | 55 | 56 | def gen_salt(length): 57 | """Generate a random string of SALT_CHARS with specified ``length``.""" 58 | if length <= 0: 59 | raise ValueError('requested salt of length <= 0') 60 | return ''.join(_sys_rng.choice(SALT_CHARS) for _ in xrange(length)) 61 | 62 | 63 | def _hash_internal(method, salt, password): 64 | """Internal password hash helper. Supports plaintext without salt, 65 | unsalted and salted passwords. In case salted passwords are used 66 | hmac is used. 67 | """ 68 | if method == 'plain': 69 | return password 70 | if salt: 71 | if method not in _hash_mods: 72 | return None 73 | if isinstance(salt, unicode): 74 | salt = salt.encode('utf-8') 75 | h = hmac.new(salt, None, _hash_mods[method]) 76 | else: 77 | if method not in _hash_funcs: 78 | return None 79 | h = _hash_funcs[method]() 80 | if isinstance(password, unicode): 81 | password = password.encode('utf-8') 82 | h.update(password) 83 | return h.hexdigest() 84 | 85 | 86 | def generate_password_hash(password, method='sha1', salt_length=8): 87 | """Hash a password with the given method and salt with with a string of 88 | the given length. The format of the string returned includes the method 89 | that was used so that :func:`check_password_hash` can check the hash. 90 | 91 | The format for the hashed string looks like this:: 92 | 93 | method$salt$hash 94 | 95 | This method can **not** generate unsalted passwords but it is possible 96 | to set the method to plain to enforce plaintext passwords. If a salt 97 | is used, hmac is used internally to salt the password. 98 | 99 | :param password: the password to hash 100 | :param method: the hash method to use (``'md5'`` or ``'sha1'``) 101 | :param salt_length: the lengt of the salt in letters 102 | """ 103 | salt = method != 'plain' and gen_salt(salt_length) or '' 104 | h = _hash_internal(method, salt, password) 105 | if h is None: 106 | raise TypeError('invalid method %r' % method) 107 | return '%s$%s$%s' % (method, salt, h) 108 | 109 | 110 | def check_password_hash(pwhash, password): 111 | """check a password against a given salted and hashed password value. 112 | In order to support unsalted legacy passwords this method supports 113 | plain text passwords, md5 and sha1 hashes (both salted and unsalted). 114 | 115 | Returns `True` if the password matched, `False` otherwise. 116 | 117 | :param pwhash: a hashed string like returned by 118 | :func:`generate_password_hash` 119 | :param password: the plaintext password to compare against the hash 120 | """ 121 | if pwhash.count('$') < 2: 122 | return False 123 | method, salt, hashval = pwhash.split('$', 2) 124 | return safe_str_cmp(_hash_internal(method, salt, password), hashval) 125 | 126 | 127 | def safe_join(directory, filename): 128 | """Safely join `directory` and `filename`. If this cannot be done, 129 | this function returns ``None``. 130 | 131 | :param directory: the base directory. 132 | :param filename: the untrusted filename relative to that directory. 133 | """ 134 | filename = posixpath.normpath(filename) 135 | for sep in _os_alt_seps: 136 | if sep in filename: 137 | return None 138 | if os.path.isabs(filename) or filename.startswith('../'): 139 | return None 140 | return os.path.join(directory, filename) 141 | -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.testsuite 4 | ~~~~~~~~~~~~~~~~~~ 5 | 6 | Contains all test Werkzeug tests. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | 12 | from __future__ import with_statement 13 | 14 | import unittest 15 | from werkzeug.utils import import_string, find_modules 16 | 17 | 18 | def iter_suites(package): 19 | """Yields all testsuites.""" 20 | for module in find_modules(package, include_packages=True): 21 | mod = import_string(module) 22 | if hasattr(mod, 'suite'): 23 | yield mod.suite() 24 | 25 | 26 | def find_all_tests(suite): 27 | """Yields all the tests and their names from a given suite.""" 28 | suites = [suite] 29 | while suites: 30 | s = suites.pop() 31 | try: 32 | suites.extend(s) 33 | except TypeError: 34 | yield s, '%s.%s.%s' % ( 35 | s.__class__.__module__, 36 | s.__class__.__name__, 37 | s._testMethodName 38 | ) 39 | 40 | 41 | class WerkzeugTestCase(unittest.TestCase): 42 | """Baseclass for all the tests that Werkzeug uses. Use these 43 | methods for testing instead of the camelcased ones in the 44 | baseclass for consistency. 45 | """ 46 | 47 | def setup(self): 48 | pass 49 | 50 | def teardown(self): 51 | pass 52 | 53 | def setUp(self): 54 | self.setup() 55 | 56 | def tearDown(self): 57 | unittest.TestCase.tearDown(self) 58 | self.teardown() 59 | 60 | def assert_equal(self, x, y): 61 | return self.assertEqual(x, y) 62 | 63 | def assert_not_equal(self, x, y): 64 | return self.assertNotEqual(x, y) 65 | 66 | def assert_raises(self, exc_type, callable=None, *args, **kwargs): 67 | catcher = _ExceptionCatcher(self, exc_type) 68 | if callable is None: 69 | return catcher 70 | with catcher: 71 | callable(*args, **kwargs) 72 | 73 | 74 | class _ExceptionCatcher(object): 75 | 76 | def __init__(self, test_case, exc_type): 77 | self.test_case = test_case 78 | self.exc_type = exc_type 79 | 80 | def __enter__(self): 81 | return self 82 | 83 | def __exit__(self, exc_type, exc_value, tb): 84 | exception_name = self.exc_type.__name__ 85 | if exc_type is None: 86 | self.test_case.fail('Expected exception of type %r' % 87 | exception_name) 88 | elif not issubclass(exc_type, self.exc_type): 89 | raise exc_type, exc_value, tb 90 | return True 91 | 92 | 93 | class BetterLoader(unittest.TestLoader): 94 | """A nicer loader that solves two problems. First of all we are setting 95 | up tests from different sources and we're doing this programmatically 96 | which breaks the default loading logic so this is required anyways. 97 | Secondly this loader has a nicer interpolation for test names than the 98 | default one so you can just do ``run-tests.py ViewTestCase`` and it 99 | will work. 100 | """ 101 | 102 | def getRootSuite(self): 103 | return suite() 104 | 105 | def loadTestsFromName(self, name, module=None): 106 | root = self.getRootSuite() 107 | if name == 'suite': 108 | return root 109 | 110 | all_tests = [] 111 | for testcase, testname in find_all_tests(root): 112 | if testname == name or \ 113 | testname.endswith('.' + name) or \ 114 | ('.' + name + '.') in testname or \ 115 | testname.startswith(name + '.'): 116 | all_tests.append(testcase) 117 | 118 | if not all_tests: 119 | raise LookupError('could not find test case for "%s"' % name) 120 | 121 | if len(all_tests) == 1: 122 | return all_tests[0] 123 | rv = unittest.TestSuite() 124 | for test in all_tests: 125 | rv.addTest(test) 126 | return rv 127 | 128 | 129 | def suite(): 130 | """A testsuite that has all the Flask tests. You can use this 131 | function to integrate the Flask tests into your own testsuite 132 | in case you want to test that monkeypatches to Flask do not 133 | break it. 134 | """ 135 | suite = unittest.TestSuite() 136 | for other_suite in iter_suites(__name__): 137 | suite.addTest(other_suite) 138 | return suite 139 | 140 | 141 | def main(): 142 | """Runs the testsuite as command line application.""" 143 | try: 144 | unittest.main(testLoader=BetterLoader(), defaultTest='suite') 145 | except Exception, e: 146 | print 'Error: %s' % e 147 | -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/compat.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.testsuite.compat 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Ensure that old stuff does not break on update. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import unittest 12 | import warnings 13 | from werkzeug.testsuite import WerkzeugTestCase 14 | 15 | from werkzeug.wrappers import Response 16 | from werkzeug.test import create_environ 17 | 18 | 19 | class CompatTestCase(WerkzeugTestCase): 20 | 21 | def test_old_imports(self): 22 | from werkzeug.utils import Headers, MultiDict, CombinedMultiDict, \ 23 | Headers, EnvironHeaders 24 | from werkzeug.http import Accept, MIMEAccept, CharsetAccept, \ 25 | LanguageAccept, ETags, HeaderSet, WWWAuthenticate, \ 26 | Authorization 27 | 28 | def test_exposed_werkzeug_mod(self): 29 | import werkzeug 30 | for key in werkzeug.__all__: 31 | # deprecated, skip it 32 | if key in ('templates', 'Template'): 33 | continue 34 | getattr(werkzeug, key) 35 | 36 | def test_fix_headers_in_response(self): 37 | # ignore some warnings werkzeug emits for backwards compat 38 | for msg in ['called into deprecated fix_headers', 39 | 'fix_headers changed behavior']: 40 | warnings.filterwarnings('ignore', message=msg, 41 | category=DeprecationWarning) 42 | 43 | class MyResponse(Response): 44 | def fix_headers(self, environ): 45 | Response.fix_headers(self, environ) 46 | self.headers['x-foo'] = "meh" 47 | myresp = MyResponse('Foo') 48 | resp = Response.from_app(myresp, create_environ(method='GET')) 49 | assert resp.headers['x-foo'] == 'meh' 50 | assert resp.data == 'Foo' 51 | 52 | warnings.resetwarnings() 53 | 54 | 55 | def suite(): 56 | suite = unittest.TestSuite() 57 | suite.addTest(unittest.makeSuite(CompatTestCase)) 58 | return suite 59 | -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/contrib/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.testsuite.contrib 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Tests the contrib modules. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import unittest 12 | from werkzeug.testsuite import iter_suites 13 | 14 | 15 | def suite(): 16 | suite = unittest.TestSuite() 17 | for other_suite in iter_suites(__name__): 18 | suite.addTest(other_suite) 19 | return suite 20 | -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/contrib/cache.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.testsuite.cache 4 | ~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Tests the cache system 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import os 12 | import time 13 | import unittest 14 | import tempfile 15 | import shutil 16 | 17 | from werkzeug.testsuite import WerkzeugTestCase 18 | from werkzeug.contrib import cache 19 | 20 | try: 21 | import redis 22 | except ImportError: 23 | redis = None 24 | 25 | 26 | class SimpleCacheTestCase(WerkzeugTestCase): 27 | 28 | def test_get_dict(self): 29 | c = cache.SimpleCache() 30 | c.set('a', 'a') 31 | c.set('b', 'b') 32 | d = c.get_dict('a', 'b') 33 | assert 'a' in d 34 | assert 'a' == d['a'] 35 | assert 'b' in d 36 | assert 'b' == d['b'] 37 | 38 | def test_set_many(self): 39 | c = cache.SimpleCache() 40 | c.set_many({0: 0, 1: 1, 2: 4}) 41 | assert c.get(2) == 4 42 | c.set_many((i, i*i) for i in xrange(3)) 43 | assert c.get(2) == 4 44 | 45 | 46 | class FileSystemCacheTestCase(WerkzeugTestCase): 47 | 48 | def test_set_get(self): 49 | tmp_dir = tempfile.mkdtemp() 50 | try: 51 | c = cache.FileSystemCache(cache_dir=tmp_dir) 52 | for i in range(3): 53 | c.set(str(i), i * i) 54 | for i in range(3): 55 | result = c.get(str(i)) 56 | assert result == i * i 57 | finally: 58 | shutil.rmtree(tmp_dir) 59 | 60 | def test_filesystemcache_prune(self): 61 | THRESHOLD = 13 62 | tmp_dir = tempfile.mkdtemp() 63 | c = cache.FileSystemCache(cache_dir=tmp_dir, threshold=THRESHOLD) 64 | for i in range(2 * THRESHOLD): 65 | c.set(str(i), i) 66 | cache_files = os.listdir(tmp_dir) 67 | shutil.rmtree(tmp_dir) 68 | assert len(cache_files) <= THRESHOLD 69 | 70 | 71 | def test_filesystemcache_clear(self): 72 | tmp_dir = tempfile.mkdtemp() 73 | c = cache.FileSystemCache(cache_dir=tmp_dir) 74 | c.set('foo', 'bar') 75 | cache_files = os.listdir(tmp_dir) 76 | assert len(cache_files) == 1 77 | c.clear() 78 | cache_files = os.listdir(tmp_dir) 79 | assert len(cache_files) == 0 80 | shutil.rmtree(tmp_dir) 81 | 82 | 83 | class RedisCacheTestCase(WerkzeugTestCase): 84 | 85 | def make_cache(self): 86 | return cache.RedisCache(key_prefix='werkzeug-test-case:') 87 | 88 | def teardown(self): 89 | self.make_cache().clear() 90 | 91 | def test_compat(self): 92 | c = self.make_cache() 93 | c._client.set(c.key_prefix + 'foo', 'Awesome') 94 | self.assert_equal(c.get('foo'), 'Awesome') 95 | c._client.set(c.key_prefix + 'foo', '42') 96 | self.assert_equal(c.get('foo'), 42) 97 | 98 | def test_get_set(self): 99 | c = self.make_cache() 100 | c.set('foo', ['bar']) 101 | assert c.get('foo') == ['bar'] 102 | 103 | def test_get_many(self): 104 | c = self.make_cache() 105 | c.set('foo', ['bar']) 106 | c.set('spam', 'eggs') 107 | assert c.get_many('foo', 'spam') == [['bar'], 'eggs'] 108 | 109 | def test_set_many(self): 110 | c = self.make_cache() 111 | c.set_many({'foo': 'bar', 'spam': ['eggs']}) 112 | assert c.get('foo') == 'bar' 113 | assert c.get('spam') == ['eggs'] 114 | 115 | def test_expire(self): 116 | c = self.make_cache() 117 | c.set('foo', 'bar', 1) 118 | time.sleep(2) 119 | assert c.get('foo') is None 120 | 121 | def test_add(self): 122 | c = self.make_cache() 123 | # sanity check that add() works like set() 124 | c.add('foo', 'bar') 125 | assert c.get('foo') == 'bar' 126 | c.add('foo', 'qux') 127 | assert c.get('foo') == 'bar' 128 | 129 | def test_delete(self): 130 | c = self.make_cache() 131 | c.add('foo', 'bar') 132 | assert c.get('foo') == 'bar' 133 | c.delete('foo') 134 | assert c.get('foo') is None 135 | 136 | def test_delete_many(self): 137 | c = self.make_cache() 138 | c.add('foo', 'bar') 139 | c.add('spam', 'eggs') 140 | c.delete_many('foo', 'spam') 141 | assert c.get('foo') is None 142 | assert c.get('spam') is None 143 | 144 | def test_inc_dec(self): 145 | c = self.make_cache() 146 | c.set('foo', 1) 147 | assert c.inc('foo') == 2 148 | assert c.dec('foo') == 1 149 | c.delete('foo') 150 | 151 | 152 | def test_true_false(self): 153 | c = self.make_cache() 154 | c.set('foo', True) 155 | assert c.get('foo') == True 156 | c.set('bar', False) 157 | assert c.get('bar') == False 158 | 159 | 160 | def suite(): 161 | suite = unittest.TestSuite() 162 | suite.addTest(unittest.makeSuite(SimpleCacheTestCase)) 163 | suite.addTest(unittest.makeSuite(FileSystemCacheTestCase)) 164 | if redis is not None: 165 | suite.addTest(unittest.makeSuite(RedisCacheTestCase)) 166 | return suite 167 | -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/contrib/iterio.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.testsuite.iterio 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Tests the iterio object. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import unittest 12 | 13 | from werkzeug.testsuite import WerkzeugTestCase 14 | from werkzeug.contrib.iterio import IterIO, greenlet 15 | 16 | 17 | class IterOTestSuite(WerkzeugTestCase): 18 | 19 | def test_basic(self): 20 | io = IterIO(["Hello", "World", "1", "2", "3"]) 21 | assert io.tell() == 0 22 | assert io.read(2) == "He" 23 | assert io.tell() == 2 24 | assert io.read(3) == "llo" 25 | assert io.tell() == 5 26 | io.seek(0) 27 | assert io.read(5) == "Hello" 28 | assert io.tell() == 5 29 | assert io._buf == "Hello" 30 | assert io.read() == "World123" 31 | assert io.tell() == 13 32 | io.close() 33 | assert io.closed 34 | 35 | io = IterIO(["Hello\n", "World!"]) 36 | assert io.readline() == 'Hello\n' 37 | assert io._buf == 'Hello\n' 38 | assert io.read() == 'World!' 39 | assert io._buf == 'Hello\nWorld!' 40 | assert io.tell() == 12 41 | io.seek(0) 42 | assert io.readlines() == ['Hello\n', 'World!'] 43 | 44 | io = IterIO(["foo\n", "bar"]) 45 | io.seek(-4, 2) 46 | assert io.read(4) == '\nbar' 47 | 48 | self.assert_raises(IOError, io.seek, 2, 100) 49 | io.close() 50 | self.assert_raises(ValueError, io.read) 51 | 52 | 53 | class IterITestSuite(WerkzeugTestCase): 54 | 55 | def test_basic(self): 56 | def producer(out): 57 | out.write('1\n') 58 | out.write('2\n') 59 | out.flush() 60 | out.write('3\n') 61 | iterable = IterIO(producer) 62 | self.assert_equal(iterable.next(), '1\n2\n') 63 | self.assert_equal(iterable.next(), '3\n') 64 | self.assert_raises(StopIteration, iterable.next) 65 | 66 | 67 | def suite(): 68 | suite = unittest.TestSuite() 69 | suite.addTest(unittest.makeSuite(IterOTestSuite)) 70 | if greenlet is not None: 71 | suite.addTest(unittest.makeSuite(IterITestSuite)) 72 | return suite 73 | -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/contrib/securecookie.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.testsuite.securecookie 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Tests the secure cookie. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import unittest 12 | 13 | from werkzeug.testsuite import WerkzeugTestCase 14 | 15 | from werkzeug.utils import parse_cookie 16 | from werkzeug.wrappers import Request, Response 17 | from werkzeug.contrib.securecookie import SecureCookie 18 | 19 | 20 | class SecureCookieTestCase(WerkzeugTestCase): 21 | 22 | def test_basic_support(self): 23 | c = SecureCookie(secret_key='foo') 24 | assert c.new 25 | print c.modified, c.should_save 26 | assert not c.modified 27 | assert not c.should_save 28 | c['x'] = 42 29 | assert c.modified 30 | assert c.should_save 31 | s = c.serialize() 32 | 33 | c2 = SecureCookie.unserialize(s, 'foo') 34 | assert c is not c2 35 | assert not c2.new 36 | assert not c2.modified 37 | assert not c2.should_save 38 | assert c2 == c 39 | 40 | c3 = SecureCookie.unserialize(s, 'wrong foo') 41 | assert not c3.modified 42 | assert not c3.new 43 | assert c3 == {} 44 | 45 | def test_wrapper_support(self): 46 | req = Request.from_values() 47 | resp = Response() 48 | c = SecureCookie.load_cookie(req, secret_key='foo') 49 | assert c.new 50 | c['foo'] = 42 51 | assert c.secret_key == 'foo' 52 | c.save_cookie(resp) 53 | 54 | req = Request.from_values(headers={ 55 | 'Cookie': 'session="%s"' % parse_cookie(resp.headers['set-cookie'])['session'] 56 | }) 57 | c2 = SecureCookie.load_cookie(req, secret_key='foo') 58 | assert not c2.new 59 | assert c2 == c 60 | 61 | 62 | def suite(): 63 | suite = unittest.TestSuite() 64 | suite.addTest(unittest.makeSuite(SecureCookieTestCase)) 65 | return suite 66 | -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/contrib/sessions.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.testsuite.sessions 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Added tests for the sessions. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import unittest 12 | import shutil 13 | 14 | from werkzeug.testsuite import WerkzeugTestCase 15 | 16 | from werkzeug.contrib.sessions import FilesystemSessionStore 17 | 18 | from tempfile import mkdtemp, gettempdir 19 | 20 | 21 | class SessionTestCase(WerkzeugTestCase): 22 | 23 | def setup(self): 24 | self.session_folder = mkdtemp() 25 | 26 | def teardown(self): 27 | shutil.rmtree(self.session_folder) 28 | 29 | def test_default_tempdir(self): 30 | store = FilesystemSessionStore() 31 | assert store.path == gettempdir() 32 | 33 | def test_basic_fs_sessions(self): 34 | store = FilesystemSessionStore(self.session_folder) 35 | x = store.new() 36 | assert x.new 37 | assert not x.modified 38 | x['foo'] = [1, 2, 3] 39 | assert x.modified 40 | store.save(x) 41 | 42 | x2 = store.get(x.sid) 43 | assert not x2.new 44 | assert not x2.modified 45 | assert x2 is not x 46 | assert x2 == x 47 | x2['test'] = 3 48 | assert x2.modified 49 | assert not x2.new 50 | store.save(x2) 51 | 52 | x = store.get(x.sid) 53 | store.delete(x) 54 | x2 = store.get(x.sid) 55 | # the session is not new when it was used previously. 56 | assert not x2.new 57 | 58 | def test_renewing_fs_session(self): 59 | store = FilesystemSessionStore(self.session_folder, renew_missing=True) 60 | x = store.new() 61 | store.save(x) 62 | store.delete(x) 63 | x2 = store.get(x.sid) 64 | assert x2.new 65 | 66 | def test_fs_session_lising(self): 67 | store = FilesystemSessionStore(self.session_folder, renew_missing=True) 68 | sessions = set() 69 | for x in xrange(10): 70 | sess = store.new() 71 | store.save(sess) 72 | sessions.add(sess.sid) 73 | 74 | listed_sessions = set(store.list()) 75 | assert sessions == listed_sessions 76 | 77 | 78 | def suite(): 79 | suite = unittest.TestSuite() 80 | suite.addTest(unittest.makeSuite(SessionTestCase)) 81 | return suite 82 | -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/contrib/wrappers.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.testsuite.contrib.wrappers 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Added tests for the sessions. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | 12 | from __future__ import with_statement 13 | 14 | import unittest 15 | 16 | from werkzeug.testsuite import WerkzeugTestCase 17 | 18 | from werkzeug.contrib import wrappers 19 | from werkzeug import routing 20 | from werkzeug.wrappers import Request, Response 21 | 22 | 23 | class WrappersTestCase(WerkzeugTestCase): 24 | 25 | def test_reverse_slash_behavior(self): 26 | class MyRequest(wrappers.ReverseSlashBehaviorRequestMixin, Request): 27 | pass 28 | req = MyRequest.from_values('/foo/bar', 'http://example.com/test') 29 | assert req.url == 'http://example.com/test/foo/bar' 30 | assert req.path == 'foo/bar' 31 | assert req.script_root == '/test/' 32 | 33 | # make sure the routing system works with the slashes in 34 | # reverse order as well. 35 | map = routing.Map([routing.Rule('/foo/bar', endpoint='foo')]) 36 | adapter = map.bind_to_environ(req.environ) 37 | assert adapter.match() == ('foo', {}) 38 | adapter = map.bind(req.host, req.script_root) 39 | assert adapter.match(req.path) == ('foo', {}) 40 | 41 | def test_dynamic_charset_request_mixin(self): 42 | class MyRequest(wrappers.DynamicCharsetRequestMixin, Request): 43 | pass 44 | env = {'CONTENT_TYPE': 'text/html'} 45 | req = MyRequest(env) 46 | assert req.charset == 'latin1' 47 | 48 | env = {'CONTENT_TYPE': 'text/html; charset=utf-8'} 49 | req = MyRequest(env) 50 | assert req.charset == 'utf-8' 51 | 52 | env = {'CONTENT_TYPE': 'application/octet-stream'} 53 | req = MyRequest(env) 54 | assert req.charset == 'latin1' 55 | assert req.url_charset == 'latin1' 56 | 57 | MyRequest.url_charset = 'utf-8' 58 | env = {'CONTENT_TYPE': 'application/octet-stream'} 59 | req = MyRequest(env) 60 | assert req.charset == 'latin1' 61 | assert req.url_charset == 'utf-8' 62 | 63 | def return_ascii(x): 64 | return "ascii" 65 | env = {'CONTENT_TYPE': 'text/plain; charset=x-weird-charset'} 66 | req = MyRequest(env) 67 | req.unknown_charset = return_ascii 68 | assert req.charset == 'ascii' 69 | assert req.url_charset == 'utf-8' 70 | 71 | def test_dynamic_charset_response_mixin(self): 72 | class MyResponse(wrappers.DynamicCharsetResponseMixin, Response): 73 | default_charset = 'utf-7' 74 | resp = MyResponse(mimetype='text/html') 75 | assert resp.charset == 'utf-7' 76 | resp.charset = 'utf-8' 77 | assert resp.charset == 'utf-8' 78 | assert resp.mimetype == 'text/html' 79 | assert resp.mimetype_params == {'charset': 'utf-8'} 80 | resp.mimetype_params['charset'] = 'iso-8859-15' 81 | assert resp.charset == 'iso-8859-15' 82 | resp.data = u'Hällo Wörld' 83 | assert ''.join(resp.iter_encoded()) == \ 84 | u'Hällo Wörld'.encode('iso-8859-15') 85 | del resp.headers['content-type'] 86 | try: 87 | resp.charset = 'utf-8' 88 | except TypeError, e: 89 | pass 90 | else: 91 | assert False, 'expected type error on charset setting without ct' 92 | 93 | 94 | def suite(): 95 | suite = unittest.TestSuite() 96 | suite.addTest(unittest.makeSuite(WrappersTestCase)) 97 | return suite 98 | -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/exceptions.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.testsuite.exceptions 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | The tests for the exception classes. 7 | 8 | TODO: 9 | 10 | - This is undertested. HTML is never checked 11 | 12 | :copyright: (c) 2011 by Armin Ronacher. 13 | :license: BSD, see LICENSE for more details. 14 | """ 15 | import unittest 16 | 17 | from werkzeug.testsuite import WerkzeugTestCase 18 | 19 | from werkzeug import exceptions 20 | from werkzeug.wrappers import Response 21 | 22 | 23 | class ExceptionsTestCase(WerkzeugTestCase): 24 | 25 | def test_proxy_exception(self): 26 | orig_resp = Response('Hello World') 27 | try: 28 | exceptions.abort(orig_resp) 29 | except exceptions.HTTPException, e: 30 | resp = e.get_response({}) 31 | else: 32 | self.fail('exception not raised') 33 | self.assert_(resp is orig_resp) 34 | self.assert_equal(resp.data, 'Hello World') 35 | 36 | def test_aborter(self): 37 | abort = exceptions.abort 38 | self.assert_raises(exceptions.BadRequest, abort, 400) 39 | self.assert_raises(exceptions.Unauthorized, abort, 401) 40 | self.assert_raises(exceptions.Forbidden, abort, 403) 41 | self.assert_raises(exceptions.NotFound, abort, 404) 42 | self.assert_raises(exceptions.MethodNotAllowed, abort, 405, ['GET', 'HEAD']) 43 | self.assert_raises(exceptions.NotAcceptable, abort, 406) 44 | self.assert_raises(exceptions.RequestTimeout, abort, 408) 45 | self.assert_raises(exceptions.Gone, abort, 410) 46 | self.assert_raises(exceptions.LengthRequired, abort, 411) 47 | self.assert_raises(exceptions.PreconditionFailed, abort, 412) 48 | self.assert_raises(exceptions.RequestEntityTooLarge, abort, 413) 49 | self.assert_raises(exceptions.RequestURITooLarge, abort, 414) 50 | self.assert_raises(exceptions.UnsupportedMediaType, abort, 415) 51 | self.assert_raises(exceptions.InternalServerError, abort, 500) 52 | self.assert_raises(exceptions.NotImplemented, abort, 501) 53 | self.assert_raises(exceptions.BadGateway, abort, 502) 54 | self.assert_raises(exceptions.ServiceUnavailable, abort, 503) 55 | 56 | myabort = exceptions.Aborter({1: exceptions.NotFound}) 57 | self.assert_raises(LookupError, myabort, 404) 58 | self.assert_raises(exceptions.NotFound, myabort, 1) 59 | 60 | myabort = exceptions.Aborter(extra={1: exceptions.NotFound}) 61 | self.assert_raises(exceptions.NotFound, myabort, 404) 62 | self.assert_raises(exceptions.NotFound, myabort, 1) 63 | 64 | def test_exception_repr(self): 65 | exc = exceptions.NotFound() 66 | self.assert_equal(unicode(exc), '404: Not Found') 67 | self.assert_equal(repr(exc), "") 68 | 69 | exc = exceptions.NotFound('Not There') 70 | self.assert_equal(unicode(exc), '404: Not There') 71 | self.assert_equal(repr(exc), "") 72 | 73 | def test_special_exceptions(self): 74 | exc = exceptions.MethodNotAllowed(['GET', 'HEAD', 'POST']) 75 | h = dict(exc.get_headers({})) 76 | self.assert_equal(h['Allow'], 'GET, HEAD, POST') 77 | self.assert_('The method DELETE is not allowed' in exc.get_description({ 78 | 'REQUEST_METHOD': 'DELETE' 79 | })) 80 | 81 | 82 | def suite(): 83 | suite = unittest.TestSuite() 84 | suite.addTest(unittest.makeSuite(ExceptionsTestCase)) 85 | return suite 86 | -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/internal.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.testsuite.internal 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Internal tests. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import unittest 12 | 13 | from datetime import datetime 14 | from warnings import filterwarnings, resetwarnings 15 | 16 | from werkzeug.testsuite import WerkzeugTestCase 17 | from werkzeug.wrappers import Request, Response 18 | 19 | from werkzeug import _internal as internal 20 | from werkzeug.test import create_environ 21 | 22 | 23 | class InternalTestCase(WerkzeugTestCase): 24 | 25 | def test_date_to_unix(self): 26 | assert internal._date_to_unix(datetime(1970, 1, 1)) == 0 27 | assert internal._date_to_unix(datetime(1970, 1, 1, 1, 0, 0)) == 3600 28 | assert internal._date_to_unix(datetime(1970, 1, 1, 1, 1, 1)) == 3661 29 | x = datetime(2010, 2, 15, 16, 15, 39) 30 | assert internal._date_to_unix(x) == 1266250539 31 | 32 | def test_easteregg(self): 33 | req = Request.from_values('/?macgybarchakku') 34 | resp = Response.force_type(internal._easteregg(None), req) 35 | assert 'About Werkzeug' in resp.data 36 | assert 'the Swiss Army knife of Python web development' in resp.data 37 | 38 | def test_wrapper_internals(self): 39 | req = Request.from_values(data={'foo': 'bar'}, method='POST') 40 | req._load_form_data() 41 | assert req.form.to_dict() == {'foo': 'bar'} 42 | 43 | # second call does not break 44 | req._load_form_data() 45 | assert req.form.to_dict() == {'foo': 'bar'} 46 | 47 | # check reprs 48 | assert repr(req) == "" 49 | resp = Response() 50 | assert repr(resp) == '' 51 | resp.data = 'Hello World!' 52 | assert repr(resp) == '' 53 | resp.response = iter(['Test']) 54 | assert repr(resp) == '' 55 | 56 | # unicode data does not set content length 57 | response = Response([u'Hällo Wörld']) 58 | headers = response.get_wsgi_headers(create_environ()) 59 | assert 'Content-Length' not in headers 60 | 61 | response = Response(['Hällo Wörld']) 62 | headers = response.get_wsgi_headers(create_environ()) 63 | assert 'Content-Length' in headers 64 | 65 | # check for internal warnings 66 | filterwarnings('error', category=Warning) 67 | response = Response() 68 | environ = create_environ() 69 | response.response = 'What the...?' 70 | self.assert_raises(Warning, lambda: list(response.iter_encoded())) 71 | self.assert_raises(Warning, lambda: list(response.get_app_iter(environ))) 72 | response.direct_passthrough = True 73 | self.assert_raises(Warning, lambda: list(response.iter_encoded())) 74 | self.assert_raises(Warning, lambda: list(response.get_app_iter(environ))) 75 | resetwarnings() 76 | 77 | 78 | def suite(): 79 | suite = unittest.TestSuite() 80 | suite.addTest(unittest.makeSuite(InternalTestCase)) 81 | return suite 82 | -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/local.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.testsuite.local 4 | ~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Local and local proxy tests. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import time 12 | import unittest 13 | from threading import Thread 14 | 15 | from werkzeug.testsuite import WerkzeugTestCase 16 | 17 | from werkzeug import local 18 | 19 | 20 | class LocalTestCase(WerkzeugTestCase): 21 | 22 | def test_basic_local(self): 23 | l = local.Local() 24 | l.foo = 0 25 | values = [] 26 | def value_setter(idx): 27 | time.sleep(0.01 * idx) 28 | l.foo = idx 29 | time.sleep(0.02) 30 | values.append(l.foo) 31 | threads = [Thread(target=value_setter, args=(x,)) 32 | for x in [1, 2, 3]] 33 | for thread in threads: 34 | thread.start() 35 | time.sleep(0.2) 36 | assert sorted(values) == [1, 2, 3] 37 | 38 | def delfoo(): 39 | del l.foo 40 | delfoo() 41 | self.assert_raises(AttributeError, lambda: l.foo) 42 | self.assert_raises(AttributeError, delfoo) 43 | 44 | local.release_local(l) 45 | 46 | def test_local_release(self): 47 | loc = local.Local() 48 | loc.foo = 42 49 | local.release_local(loc) 50 | assert not hasattr(loc, 'foo') 51 | 52 | ls = local.LocalStack() 53 | ls.push(42) 54 | local.release_local(ls) 55 | assert ls.top is None 56 | 57 | def test_local_proxy(self): 58 | foo = [] 59 | ls = local.LocalProxy(lambda: foo) 60 | ls.append(42) 61 | ls.append(23) 62 | ls[1:] = [1, 2, 3] 63 | assert foo == [42, 1, 2, 3] 64 | assert repr(foo) == repr(ls) 65 | assert foo[0] == 42 66 | foo += [1] 67 | assert list(foo) == [42, 1, 2, 3, 1] 68 | 69 | def test_local_stack(self): 70 | ident = local.get_ident() 71 | 72 | ls = local.LocalStack() 73 | assert ident not in ls._local.__storage__ 74 | assert ls.top is None 75 | ls.push(42) 76 | assert ident in ls._local.__storage__ 77 | assert ls.top == 42 78 | ls.push(23) 79 | assert ls.top == 23 80 | ls.pop() 81 | assert ls.top == 42 82 | ls.pop() 83 | assert ls.top is None 84 | assert ls.pop() is None 85 | assert ls.pop() is None 86 | 87 | proxy = ls() 88 | ls.push([1, 2]) 89 | assert proxy == [1, 2] 90 | ls.push((1, 2)) 91 | assert proxy == (1, 2) 92 | ls.pop() 93 | ls.pop() 94 | assert repr(proxy) == '' 95 | 96 | assert ident not in ls._local.__storage__ 97 | 98 | def test_local_proxies_with_callables(self): 99 | foo = 42 100 | ls = local.LocalProxy(lambda: foo) 101 | assert ls == 42 102 | foo = [23] 103 | ls.append(42) 104 | assert ls == [23, 42] 105 | assert foo == [23, 42] 106 | 107 | def test_custom_idents(self): 108 | ident = 0 109 | loc = local.Local() 110 | stack = local.LocalStack() 111 | mgr = local.LocalManager([loc, stack], ident_func=lambda: ident) 112 | 113 | loc.foo = 42 114 | stack.push({'foo': 42}) 115 | ident = 1 116 | loc.foo = 23 117 | stack.push({'foo': 23}) 118 | ident = 0 119 | assert loc.foo == 42 120 | assert stack.top['foo'] == 42 121 | stack.pop() 122 | assert stack.top is None 123 | ident = 1 124 | assert loc.foo == 23 125 | assert stack.top['foo'] == 23 126 | stack.pop() 127 | assert stack.top is None 128 | 129 | 130 | def suite(): 131 | suite = unittest.TestSuite() 132 | suite.addTest(unittest.makeSuite(LocalTestCase)) 133 | return suite 134 | -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/multipart/collect.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Hacky helper application to collect form data. 4 | """ 5 | from werkzeug.serving import run_simple 6 | from werkzeug.wrappers import Request, Response 7 | 8 | 9 | def copy_stream(request): 10 | from os import mkdir 11 | from time import time 12 | folder = 'request-%d' % time() 13 | mkdir(folder) 14 | environ = request.environ 15 | f = file(folder + '/request.txt', 'wb+') 16 | f.write(environ['wsgi.input'].read(int(environ['CONTENT_LENGTH']))) 17 | f.flush() 18 | f.seek(0) 19 | environ['wsgi.input'] = f 20 | request.stat_folder = folder 21 | 22 | 23 | def stats(request): 24 | copy_stream(request) 25 | f1 = request.files['file1'] 26 | f2 = request.files['file2'] 27 | text = request.form['text'] 28 | f1.save(request.stat_folder + '/file1.bin') 29 | f2.save(request.stat_folder + '/file2.bin') 30 | file(request.stat_folder + '/text.txt', 'w').write(text.encode('utf-8')) 31 | return Response('Done.') 32 | 33 | 34 | def upload_file(request): 35 | return Response(''' 36 |

Upload File

37 |
38 |
39 |
40 |
41 | 42 |
43 | ''', mimetype='text/html') 44 | 45 | 46 | def application(environ, start_responseonse): 47 | request = Request(environ) 48 | if request.method == 'POST': 49 | response = stats(request) 50 | else: 51 | response = upload_file(request) 52 | return response(environ, start_responseonse) 53 | 54 | 55 | if __name__ == '__main__': 56 | run_simple('localhost', 5000, application, use_debugger=True) 57 | -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/multipart/firefox3-2png1txt/file1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dinp/dinp-demo-python-flask/3714bdbf5125c0ea48635ea70087cb58d73f54af/dinp/werkzeug/testsuite/multipart/firefox3-2png1txt/file1.png -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/multipart/firefox3-2png1txt/file2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dinp/dinp-demo-python-flask/3714bdbf5125c0ea48635ea70087cb58d73f54af/dinp/werkzeug/testsuite/multipart/firefox3-2png1txt/file2.png -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/multipart/firefox3-2png1txt/request.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dinp/dinp-demo-python-flask/3714bdbf5125c0ea48635ea70087cb58d73f54af/dinp/werkzeug/testsuite/multipart/firefox3-2png1txt/request.txt -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/multipart/firefox3-2png1txt/text.txt: -------------------------------------------------------------------------------- 1 | example text -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/multipart/firefox3-2pnglongtext/file1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dinp/dinp-demo-python-flask/3714bdbf5125c0ea48635ea70087cb58d73f54af/dinp/werkzeug/testsuite/multipart/firefox3-2pnglongtext/file1.png -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/multipart/firefox3-2pnglongtext/file2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dinp/dinp-demo-python-flask/3714bdbf5125c0ea48635ea70087cb58d73f54af/dinp/werkzeug/testsuite/multipart/firefox3-2pnglongtext/file2.png -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/multipart/firefox3-2pnglongtext/request.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dinp/dinp-demo-python-flask/3714bdbf5125c0ea48635ea70087cb58d73f54af/dinp/werkzeug/testsuite/multipart/firefox3-2pnglongtext/request.txt -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/multipart/firefox3-2pnglongtext/text.txt: -------------------------------------------------------------------------------- 1 | --long text 2 | --with boundary 3 | --lookalikes-- -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/multipart/ie6-2png1txt/file1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dinp/dinp-demo-python-flask/3714bdbf5125c0ea48635ea70087cb58d73f54af/dinp/werkzeug/testsuite/multipart/ie6-2png1txt/file1.png -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/multipart/ie6-2png1txt/file2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dinp/dinp-demo-python-flask/3714bdbf5125c0ea48635ea70087cb58d73f54af/dinp/werkzeug/testsuite/multipart/ie6-2png1txt/file2.png -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/multipart/ie6-2png1txt/request.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dinp/dinp-demo-python-flask/3714bdbf5125c0ea48635ea70087cb58d73f54af/dinp/werkzeug/testsuite/multipart/ie6-2png1txt/request.txt -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/multipart/ie6-2png1txt/text.txt: -------------------------------------------------------------------------------- 1 | ie6 sucks :-/ -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/multipart/ie7_full_path_request.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dinp/dinp-demo-python-flask/3714bdbf5125c0ea48635ea70087cb58d73f54af/dinp/werkzeug/testsuite/multipart/ie7_full_path_request.txt -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/multipart/opera8-2png1txt/file1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dinp/dinp-demo-python-flask/3714bdbf5125c0ea48635ea70087cb58d73f54af/dinp/werkzeug/testsuite/multipart/opera8-2png1txt/file1.png -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/multipart/opera8-2png1txt/file2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dinp/dinp-demo-python-flask/3714bdbf5125c0ea48635ea70087cb58d73f54af/dinp/werkzeug/testsuite/multipart/opera8-2png1txt/file2.png -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/multipart/opera8-2png1txt/request.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dinp/dinp-demo-python-flask/3714bdbf5125c0ea48635ea70087cb58d73f54af/dinp/werkzeug/testsuite/multipart/opera8-2png1txt/request.txt -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/multipart/opera8-2png1txt/text.txt: -------------------------------------------------------------------------------- 1 | blafasel öäü -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/multipart/webkit3-2png1txt/file1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dinp/dinp-demo-python-flask/3714bdbf5125c0ea48635ea70087cb58d73f54af/dinp/werkzeug/testsuite/multipart/webkit3-2png1txt/file1.png -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/multipart/webkit3-2png1txt/file2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dinp/dinp-demo-python-flask/3714bdbf5125c0ea48635ea70087cb58d73f54af/dinp/werkzeug/testsuite/multipart/webkit3-2png1txt/file2.png -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/multipart/webkit3-2png1txt/request.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dinp/dinp-demo-python-flask/3714bdbf5125c0ea48635ea70087cb58d73f54af/dinp/werkzeug/testsuite/multipart/webkit3-2png1txt/request.txt -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/multipart/webkit3-2png1txt/text.txt: -------------------------------------------------------------------------------- 1 | this is another text with ümläüts -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/res/test.txt: -------------------------------------------------------------------------------- 1 | FOUND 2 | -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/security.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.testsuite.security 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Tests the security helpers. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import os 12 | import unittest 13 | 14 | from werkzeug.testsuite import WerkzeugTestCase 15 | 16 | from werkzeug.security import check_password_hash, generate_password_hash, \ 17 | safe_join 18 | 19 | 20 | class SecurityTestCase(WerkzeugTestCase): 21 | 22 | def test_password_hashing(self): 23 | """Test the password hashing and password hash checking""" 24 | hash1 = generate_password_hash('default') 25 | hash2 = generate_password_hash(u'default', method='sha1') 26 | assert hash1 != hash2 27 | assert check_password_hash(hash1, 'default') 28 | assert check_password_hash(hash2, 'default') 29 | assert hash1.startswith('sha1$') 30 | assert hash2.startswith('sha1$') 31 | 32 | fakehash = generate_password_hash('default', method='plain') 33 | assert fakehash == 'plain$$default' 34 | assert check_password_hash(fakehash, 'default') 35 | 36 | mhash = generate_password_hash(u'default', method='md5') 37 | assert mhash.startswith('md5$') 38 | assert check_password_hash(mhash, 'default') 39 | 40 | legacy = 'md5$$c21f969b5f03d33d43e04f8f136e7682' 41 | assert check_password_hash(legacy, 'default') 42 | 43 | legacy = u'md5$$c21f969b5f03d33d43e04f8f136e7682' 44 | assert check_password_hash(legacy, 'default') 45 | 46 | def test_safe_join(self): 47 | """Test the safe joining helper""" 48 | assert safe_join('foo', 'bar/baz') == os.path.join('foo', 'bar/baz') 49 | assert safe_join('foo', '../bar/baz') is None 50 | if os.name == 'nt': 51 | assert safe_join('foo', 'foo\\bar') is None 52 | 53 | 54 | def suite(): 55 | suite = unittest.TestSuite() 56 | suite.addTest(unittest.makeSuite(SecurityTestCase)) 57 | return suite 58 | -------------------------------------------------------------------------------- /dinp/werkzeug/testsuite/serving.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.testsuite.serving 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Added serving tests. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import sys 12 | import time 13 | import urllib 14 | import unittest 15 | from functools import update_wrapper 16 | from StringIO import StringIO 17 | 18 | from werkzeug.testsuite import WerkzeugTestCase 19 | 20 | from werkzeug import __version__ as version, serving 21 | from werkzeug.testapp import test_app 22 | from threading import Thread 23 | 24 | 25 | real_make_server = serving.make_server 26 | 27 | 28 | def silencestderr(f): 29 | def new_func(*args, **kwargs): 30 | old_stderr = sys.stderr 31 | sys.stderr = StringIO() 32 | try: 33 | return f(*args, **kwargs) 34 | finally: 35 | sys.stderr = old_stderr 36 | return update_wrapper(new_func, f) 37 | 38 | 39 | def run_dev_server(application): 40 | servers = [] 41 | def tracking_make_server(*args, **kwargs): 42 | srv = real_make_server(*args, **kwargs) 43 | servers.append(srv) 44 | return srv 45 | serving.make_server = tracking_make_server 46 | try: 47 | t = Thread(target=serving.run_simple, args=('localhost', 0, application)) 48 | t.setDaemon(True) 49 | t.start() 50 | time.sleep(0.25) 51 | finally: 52 | serving.make_server = real_make_server 53 | if not servers: 54 | return None, None 55 | server ,= servers 56 | ip, port = server.socket.getsockname()[:2] 57 | if ':' in ip: 58 | ip = '[%s]' % ip 59 | return server, '%s:%d' % (ip, port) 60 | 61 | 62 | class ServingTestCase(WerkzeugTestCase): 63 | 64 | @silencestderr 65 | def test_serving(self): 66 | server, addr = run_dev_server(test_app) 67 | rv = urllib.urlopen('http://%s/?foo=bar&baz=blah' % addr).read() 68 | assert 'WSGI Information' in rv 69 | assert 'foo=bar&baz=blah' in rv 70 | assert ('Werkzeug/%s' % version) in rv 71 | 72 | @silencestderr 73 | def test_broken_app(self): 74 | def broken_app(environ, start_response): 75 | 1/0 76 | server, addr = run_dev_server(broken_app) 77 | rv = urllib.urlopen('http://%s/?foo=bar&baz=blah' % addr).read() 78 | assert 'Internal Server Error' in rv 79 | 80 | 81 | def suite(): 82 | suite = unittest.TestSuite() 83 | suite.addTest(unittest.makeSuite(ServingTestCase)) 84 | return suite 85 | -------------------------------------------------------------------------------- /dinp/werkzeug/useragents.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.useragents 4 | ~~~~~~~~~~~~~~~~~~~ 5 | 6 | This module provides a helper to inspect user agent strings. This module 7 | is far from complete but should work for most of the currently available 8 | browsers. 9 | 10 | 11 | :copyright: (c) 2011 by the Werkzeug Team, see AUTHORS for more details. 12 | :license: BSD, see LICENSE for more details. 13 | """ 14 | import re 15 | 16 | 17 | class UserAgentParser(object): 18 | """A simple user agent parser. Used by the `UserAgent`.""" 19 | 20 | platforms = ( 21 | ('iphone|ios', 'iphone'), 22 | (r'darwin|mac|os\s*x', 'macos'), 23 | ('win', 'windows'), 24 | (r'android', 'android'), 25 | (r'x11|lin(\b|ux)?', 'linux'), 26 | ('(sun|i86)os', 'solaris'), 27 | (r'nintendo\s+wii', 'wii'), 28 | ('irix', 'irix'), 29 | ('hp-?ux', 'hpux'), 30 | ('aix', 'aix'), 31 | ('sco|unix_sv', 'sco'), 32 | ('bsd', 'bsd'), 33 | ('amiga', 'amiga') 34 | ) 35 | browsers = ( 36 | ('googlebot', 'google'), 37 | ('msnbot', 'msn'), 38 | ('yahoo', 'yahoo'), 39 | ('ask jeeves', 'ask'), 40 | (r'aol|america\s+online\s+browser', 'aol'), 41 | ('opera', 'opera'), 42 | ('chrome', 'chrome'), 43 | ('firefox|firebird|phoenix|iceweasel', 'firefox'), 44 | ('galeon', 'galeon'), 45 | ('safari', 'safari'), 46 | ('webkit', 'webkit'), 47 | ('camino', 'camino'), 48 | ('konqueror', 'konqueror'), 49 | ('k-meleon', 'kmeleon'), 50 | ('netscape', 'netscape'), 51 | (r'msie|microsoft\s+internet\s+explorer', 'msie'), 52 | ('lynx', 'lynx'), 53 | ('links', 'links'), 54 | ('seamonkey|mozilla', 'seamonkey') 55 | ) 56 | 57 | _browser_version_re = r'(?:%s)[/\sa-z(]*(\d+[.\da-z]+)?(?i)' 58 | _language_re = re.compile( 59 | r'(?:;\s*|\s+)(\b\w{2}\b(?:-\b\w{2}\b)?)\s*;|' 60 | r'(?:\(|\[|;)\s*(\b\w{2}\b(?:-\b\w{2}\b)?)\s*(?:\]|\)|;)' 61 | ) 62 | 63 | def __init__(self): 64 | self.platforms = [(b, re.compile(a, re.I)) for a, b in self.platforms] 65 | self.browsers = [(b, re.compile(self._browser_version_re % a)) 66 | for a, b in self.browsers] 67 | 68 | def __call__(self, user_agent): 69 | for platform, regex in self.platforms: 70 | match = regex.search(user_agent) 71 | if match is not None: 72 | break 73 | else: 74 | platform = None 75 | for browser, regex in self.browsers: 76 | match = regex.search(user_agent) 77 | if match is not None: 78 | version = match.group(1) 79 | break 80 | else: 81 | browser = version = None 82 | match = self._language_re.search(user_agent) 83 | if match is not None: 84 | language = match.group(1) or match.group(2) 85 | else: 86 | language = None 87 | return platform, browser, version, language 88 | 89 | 90 | class UserAgent(object): 91 | """Represents a user agent. Pass it a WSGI environment or a user agent 92 | string and you can inspect some of the details from the user agent 93 | string via the attributes. The following attributes exist: 94 | 95 | .. attribute:: string 96 | 97 | the raw user agent string 98 | 99 | .. attribute:: platform 100 | 101 | the browser platform. The following platforms are currently 102 | recognized: 103 | 104 | - `aix` 105 | - `amiga` 106 | - `android` 107 | - `bsd` 108 | - `hpux` 109 | - `iphone` 110 | - `irix` 111 | - `linux` 112 | - `macos` 113 | - `sco` 114 | - `solaris` 115 | - `wii` 116 | - `windows` 117 | 118 | .. attribute:: browser 119 | 120 | the name of the browser. The following browsers are currently 121 | recognized: 122 | 123 | - `aol` * 124 | - `ask` * 125 | - `camino` 126 | - `chrome` 127 | - `firefox` 128 | - `galeon` 129 | - `google` * 130 | - `kmeleon` 131 | - `konqueror` 132 | - `links` 133 | - `lynx` 134 | - `msie` 135 | - `msn` 136 | - `netscape` 137 | - `opera` 138 | - `safari` 139 | - `seamonkey` 140 | - `webkit` 141 | - `yahoo` * 142 | 143 | (Browsers maked with a star (``*``) are crawlers.) 144 | 145 | .. attribute:: version 146 | 147 | the version of the browser 148 | 149 | .. attribute:: language 150 | 151 | the language of the browser 152 | """ 153 | 154 | _parser = UserAgentParser() 155 | 156 | def __init__(self, environ_or_string): 157 | if isinstance(environ_or_string, dict): 158 | environ_or_string = environ_or_string.get('HTTP_USER_AGENT', '') 159 | self.string = environ_or_string 160 | self.platform, self.browser, self.version, self.language = \ 161 | self._parser(environ_or_string) 162 | 163 | def to_header(self): 164 | return self.string 165 | 166 | def __str__(self): 167 | return self.string 168 | 169 | def __nonzero__(self): 170 | return bool(self.browser) 171 | 172 | def __repr__(self): 173 | return '<%s %r/%s>' % ( 174 | self.__class__.__name__, 175 | self.browser, 176 | self.version 177 | ) 178 | 179 | 180 | # conceptionally this belongs in this module but because we want to lazily 181 | # load the user agent module (which happens in wrappers.py) we have to import 182 | # it afterwards. The class itself has the module set to this module so 183 | # pickle, inspect and similar modules treat the object as if it was really 184 | # implemented here. 185 | from werkzeug.wrappers import UserAgentMixin 186 | -------------------------------------------------------------------------------- /wsgi.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import sys 3 | sys.path.insert(0, "./dinp/") 4 | 5 | import time 6 | from flask import Flask 7 | 8 | app = Flask(__name__) 9 | 10 | @app.route("/") 11 | def index(): 12 | sys.stdout.write('----------------stdout at: %s\n' % time.strftime('%Y-%m-%d %H:%M:%S')) 13 | sys.stderr.write('----------------stderr at: %s\n' % time.strftime('%Y-%m-%d %H:%M:%S')) 14 | return "hello, dinp" 15 | 16 | # export for paas 17 | application = app 18 | 19 | if __name__ == '__main__': 20 | application.run() 21 | --------------------------------------------------------------------------------