def __call__(self, environ, start_response): # check if websocket call if "wsgi.websocket" in environ and not environ["wsgi.websocket"] is None: # a websocket call, no debugger ;) return self.app(environ, start_response) # else go on with debugger return DebuggedApplication.__call__(self, environ, start_response)
It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "todo.settings.production") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Wrap werkzeug debugger if DEBUG is on from django.conf import settings if settings.DEBUG: try: import django.views.debug import six from werkzeug.debug import DebuggedApplication def null_technical_500_response(request, exc_type, exc_value, tb): six.reraise(exc_type, exc_value, tb) django.views.debug.technical_500_response = null_technical_500_response application = DebuggedApplication(application, evalex=True) except ImportError: pass else: from dj_static import Cling application = Cling(application)
This is the wsgi file that uwsgi/apache loads Not a lot happening in here. Basically we just set up the envinronment """ import os import sys import logging # Set up an environment var for the location of our config os.environ['HOMESTACK_CONFIG'] = "/opt/.config/homestack" # Set up basic logging logging.basicConfig(stream=sys.stderr, level=logging.ERROR) # Ensure we've got import access (local shit) sys.path.insert(0, os.path.dirname(os.path.realpath(__file__))) sys.path.append("/opt/homestack") # Actually import our application now from app import create_app application = create_app() #allow werkzeug to work with uWSGI if (application.debug): from werkzeug.debug import DebuggedApplication application.wsgi_app = DebuggedApplication(application.wsgi_app, True) if __name__ == "__main__": application.run(host='0.0.0.0', debug=True)
context = make_context() context['config'] = flatten_app_config() parsed_factcheck_doc = getattr(g, 'parsed_factcheck', None) if parsed_factcheck_doc is None: logger.debug("did not find parsed_factcheck") with open(app_config.TRANSCRIPT_HTML_PATH) as f: html = f.read() context.update(parse_document(html)) else: logger.debug("found parsed_factcheck in g") context.update(parsed_factcheck_doc) return context def parse_document(html): doc = CopyDoc(html) parsed_document = parse_doc.parse(doc) return parsed_document # Enable Werkzeug debug pages if app_config.DEBUG: wsgi_app = DebuggedApplication(app, evalex=False) else: wsgi_app = app # Catch attempts to run the app directly if __name__ == '__main__': logging.error('This command has been removed! Run "fab app" instead!')
It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mail.settings.production") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Wrap werkzeug debugger if DEBUG is on from django.conf import settings if settings.DEBUG: try: import django.views.debug import six from werkzeug.debug import DebuggedApplication def null_technical_500_response(request, exc_type, exc_value, tb): six.reraise(exc_type, exc_value, tb) django.views.debug.technical_500_response = null_technical_500_response application = DebuggedApplication( application, evalex=True, # Turning off pin security as DEBUG is True pin_security=False) except ImportError: pass
def make_flask_stack(conf): """ This has to pass the flask app through all the same middleware that Pylons used """ root = os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) debug = asbool(conf.get('debug', conf.get('DEBUG', False))) testing = asbool(conf.get('testing', conf.get('TESTING', False))) app = flask_app = CKANFlask(__name__, static_url_path='') # Register storage for accessing group images, site logo, etc. storage_folder = [] storage = uploader.get_storage_path() if storage: storage_folder = [os.path.join(storage, 'storage')] # Static files folders (core and extensions) public_folder = config.get_value(u'ckan.base_public_folder') app.static_folder = config.get_value( 'extra_public_paths' ).split(',') + [os.path.join(root, public_folder)] + storage_folder app.jinja_options = jinja_extensions.get_jinja_env_options() app.jinja_env.policies['ext.i18n.trimmed'] = True app.debug = debug app.testing = testing app.template_folder = os.path.join(root, 'templates') app.app_ctx_globals_class = CKAN_AppCtxGlobals app.url_rule_class = CKAN_Rule # Update Flask config with the CKAN values. We use the common config # object as values might have been modified on `load_environment` if config: app.config.update(config) else: app.config.update(conf) # Do all the Flask-specific stuff before adding other middlewares # Secret key needed for flask-debug-toolbar and sessions if not app.config.get('SECRET_KEY'): app.config['SECRET_KEY'] = config.get_value('beaker.session.secret') if not app.config.get('SECRET_KEY'): raise RuntimeError(u'You must provide a value for the secret key' ' with the SECRET_KEY config option') root_path = config.get_value('ckan.root_path') if debug: from flask_debugtoolbar import DebugToolbarExtension app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False debug_ext = DebugToolbarExtension() # register path that includes `ckan.site_root` before # initializing debug app. In such a way, our route receives # higher precedence. # TODO: After removal of Pylons code, switch to # `APPLICATION_ROOT` config value for flask application. Right # now it's a bad option because we are handling both pylons # and flask urls inside helpers and splitting this logic will # bring us tons of headache. if root_path: app.add_url_rule( root_path.replace('{{LANG}}', '').rstrip('/') + '/_debug_toolbar/static/<path:filename>', '_debug_toolbar.static', debug_ext.send_static_file ) debug_ext.init_app(app) from werkzeug.debug import DebuggedApplication app.wsgi_app = DebuggedApplication(app.wsgi_app, True) # Use Beaker as the Flask session interface class BeakerSessionInterface(SessionInterface): def open_session(self, app, request): if 'beaker.session' in request.environ: return request.environ['beaker.session'] def save_session(self, app, session, response): session.save() namespace = 'beaker.session.' session_opts = {k.replace('beaker.', ''): v for k, v in config.items() if k.startswith(namespace)} if (not session_opts.get('session.data_dir') and session_opts.get('session.type', 'file') == 'file'): cache_dir = conf.get('cache_dir') or conf.get('cache.dir') session_opts['session.data_dir'] = '{data_dir}/sessions'.format( data_dir=cache_dir) app.wsgi_app = RootPathMiddleware(app.wsgi_app, session_opts) app.wsgi_app = SessionMiddleware(app.wsgi_app, session_opts) app.session_interface = BeakerSessionInterface() # Add Jinja2 extensions and filters app.jinja_env.filters['empty_and_escape'] = \ jinja_extensions.empty_and_escape # Common handlers for all requests app.before_request(ckan_before_request) app.after_request(ckan_after_request) # Template context processors app.context_processor(helper_functions) app.context_processor(c_object) @app.context_processor def ungettext_alias(): u''' Provide `ungettext` as an alias of `ngettext` for backwards compatibility ''' return dict(ungettext=ungettext) # Babel _ckan_i18n_dir = i18n.get_ckan_i18n_dir() pairs = [ (_ckan_i18n_dir, u'ckan') ] + [ (p.i18n_directory(), p.i18n_domain()) for p in reversed(list(PluginImplementations(ITranslation))) ] i18n_dirs, i18n_domains = zip(*pairs) app.config[u'BABEL_TRANSLATION_DIRECTORIES'] = ';'.join(i18n_dirs) app.config[u'BABEL_DOMAIN'] = 'ckan' app.config[u'BABEL_MULTIPLE_DOMAINS'] = ';'.join(i18n_domains) app.config[u'BABEL_DEFAULT_TIMEZONE'] = str(helpers.get_display_timezone()) babel = CKANBabel(app) babel.localeselector(get_locale) # WebAssets _setup_webassets(app) # Auto-register all blueprints defined in the `views` folder _register_core_blueprints(app) _register_error_handler(app) # Set up each IBlueprint extension as a Flask Blueprint for plugin in PluginImplementations(IBlueprint): plugin_blueprints = plugin.get_blueprint() if not isinstance(plugin_blueprints, list): plugin_blueprints = [plugin_blueprints] for blueprint in plugin_blueprints: app.register_extension_blueprint(blueprint) lib_plugins.register_package_blueprints(app) lib_plugins.register_group_blueprints(app) # Start other middleware for plugin in PluginImplementations(IMiddleware): app = plugin.make_middleware(app, config) for plugin in PluginImplementations(IMiddleware): try: app = plugin.make_error_log_middleware(app, config) except AttributeError: log.critical('Middleware class {0} is missing the method' 'make_error_log_middleware.' .format(plugin.__class__.__name__)) # Initialize repoze.who who_parser = WhoConfig(conf['here']) who_parser.parse(open(conf['who.config_file'])) app = PluggableAuthenticationMiddleware( RepozeAdapterMiddleware(app), who_parser.identifiers, who_parser.authenticators, who_parser.challengers, who_parser.mdproviders, who_parser.request_classifier, who_parser.challenge_decider, logging.getLogger('repoze.who'), logging.WARN, # ignored who_parser.remote_user_key ) # Update the main CKAN config object with the Flask specific keys # that were set here or autogenerated flask_config_keys = set(flask_app.config.keys()) - set(config.keys()) for key in flask_config_keys: config[key] = flask_app.config[key] # Prevent the host from request to be added to the new header location. app = HostHeaderMiddleware(app) app = I18nMiddleware(app) if config.get_value('ckan.tracking_enabled'): app = TrackingMiddleware(app, config) # Add a reference to the actual Flask app so it's easier to access app._wsgi_app = flask_app return app
def run_simple(hostname, port, application, use_reloader=False, use_debugger=False, use_evalex=True, extra_files=None, reloader_interval=1, reloader_type='auto', threaded=False, processes=1, request_handler=None, static_files=None, passthrough_errors=False, ssl_context=None): """Start a WSGI application. Optional features include a reloader, multithreading and fork support. This function has a command-line interface too:: python -m werkzeug.serving --help .. versionadded:: 0.5 `static_files` was added to simplify serving of static files as well as `passthrough_errors`. .. versionadded:: 0.6 support for SSL was added. .. versionadded:: 0.8 Added support for automatically loading a SSL context from certificate file and private key. .. versionadded:: 0.9 Added command-line interface. .. versionadded:: 0.10 Improved the reloader and added support for changing the backend through the `reloader_type` parameter. See :ref:`reloader` for more information. .. versionchanged:: 0.15 Bind to a Unix socket by passing a path that starts with ``unix://`` as the ``hostname``. :param hostname: The host to bind to, for example ``'localhost'``. If the value is a path that starts with ``unix://`` it will bind to a Unix socket instead of a TCP socket.. :param port: The port for the server. eg: ``8080`` :param application: the WSGI application to execute :param use_reloader: should the server automatically restart the python process if modules were changed? :param use_debugger: should the werkzeug debugging system be used? :param use_evalex: should the exception evaluation feature be enabled? :param extra_files: a list of files the reloader should watch additionally to the modules. For example configuration files. :param reloader_interval: the interval for the reloader in seconds. :param reloader_type: the type of reloader to use. The default is auto detection. Valid values are ``'stat'`` and ``'watchdog'``. See :ref:`reloader` for more information. :param threaded: should the process handle each request in a separate thread? :param processes: if greater than 1 then handle each request in a new process up to this maximum number of concurrent processes. :param request_handler: optional parameter that can be used to replace the default one. You can use this to replace it with a different :class:`~BaseHTTPServer.BaseHTTPRequestHandler` subclass. :param static_files: a list or dict of paths for static files. This works exactly like :class:`SharedDataMiddleware`, it's actually just wrapping the application in that middleware before serving. :param passthrough_errors: set this to `True` to disable the error catching. This means that the server will die on errors but it can be useful to hook debuggers in (pdb etc.) :param ssl_context: an SSL context for the connection. Either an :class:`ssl.SSLContext`, a tuple in the form ``(cert_file, pkey_file)``, the string ``'adhoc'`` if the server should automatically create one, or ``None`` to disable SSL (which is the default). """ if not isinstance(port, int): raise TypeError('port must be an integer') if use_debugger: from werkzeug.debug import DebuggedApplication application = DebuggedApplication(application, use_evalex) if static_files: from werkzeug.wsgi import SharedDataMiddleware application = SharedDataMiddleware(application, static_files) def log_startup(sock): display_hostname = hostname if hostname not in ('', '*') else 'localhost' quit_msg = '(Press CTRL+C to quit)' if sock.family == af_unix: _log('info', ' * Running on %s %s', display_hostname, quit_msg) else: if ':' in display_hostname: display_hostname = '[%s]' % display_hostname port = sock.getsockname()[1] _log('info', ' * Running on %s://%s:%d/ %s', 'http' if ssl_context is None else 'https', display_hostname, port, quit_msg) def inner(): try: fd = int(os.environ['WERKZEUG_SERVER_FD']) except (LookupError, ValueError): fd = None srv = make_server(hostname, port, application, threaded, processes, request_handler, passthrough_errors, ssl_context, fd=fd) if fd is None: log_startup(srv.socket) srv.serve_forever() if use_reloader: # If we're not running already in the subprocess that is the # reloader we want to open up a socket early to make sure the # port is actually available. if not is_running_from_reloader(): if port == 0 and not can_open_by_fd: raise ValueError('Cannot bind to a random port with enabled ' 'reloader if the Python interpreter does ' 'not support socket opening by fd.') # Create and destroy a socket so that any exceptions are # raised before we spawn a separate Python interpreter and # lose this ability. address_family = select_address_family(hostname, port) server_address = get_sockaddr(hostname, port, address_family) s = socket.socket(address_family, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(server_address) if hasattr(s, 'set_inheritable'): s.set_inheritable(True) # If we can open the socket by file descriptor, then we can just # reuse this one and our socket will survive the restarts. if can_open_by_fd: os.environ['WERKZEUG_SERVER_FD'] = str(s.fileno()) s.listen(LISTEN_QUEUE) log_startup(s) else: s.close() if address_family == af_unix: _log('info', "Unlinking %s" % server_address) os.unlink(server_address) # Do not use relative imports, otherwise "python -m werkzeug.serving" # breaks. from werkzeug._reloader import run_with_reloader run_with_reloader(inner, extra_files, reloader_interval, reloader_type) else: inner()
def make_debug(global_conf={}, **conf): from werkzeug.debug import DebuggedApplication app = make_app(global_conf, config=DEBUG_CFG, debug=True) return DebuggedApplication(app, evalex=True)
def inner_run(self, options): if not HAS_WERKZEUG: raise CommandError( "Werkzeug is required to use runserver_plus. Please visit http://werkzeug.pocoo.org/ or install via pip. (pip install Werkzeug)" ) # Set colored output if settings.DEBUG: try: set_werkzeug_log_color() except Exception: # We are dealing with some internals, anything could go wrong if self.show_startup_messages: print( "Wrapping internal werkzeug logger for color highlighting has failed!" ) class WSGIRequestHandler(_WSGIRequestHandler): def make_environ(self): environ = super().make_environ() if not options['keep_meta_shutdown_func']: del environ['werkzeug.server.shutdown'] return environ threaded = options['threaded'] use_reloader = options['use_reloader'] open_browser = options['open_browser'] quit_command = 'CONTROL-C' if sys.platform != 'win32' else 'CTRL-BREAK' reloader_interval = options['reloader_interval'] reloader_type = options['reloader_type'] self.extra_files = set(options['extra_files']) self.nopin = options['nopin'] if self.show_startup_messages: print("Performing system checks...\n") try: check_errors( self.check)(display_num_errors=self.show_startup_messages) check_errors(self.check_migrations)() handler = check_errors(self.get_handler)(**options) except Exception as exc: self.stderr.write("Error occurred during checks: %r" % exc, ending="\n\n") handler = self.get_error_handler(exc, **options) if USE_STATICFILES: use_static_handler = options['use_static_handler'] insecure_serving = options['insecure_serving'] if use_static_handler and (settings.DEBUG or insecure_serving): handler = StaticFilesHandler(handler) if options["cert_path"] or options["key_file_path"]: if not HAS_OPENSSL: raise CommandError( "Python OpenSSL Library is " "required to use runserver_plus with ssl support. " "Install via pip (pip install pyOpenSSL).") certfile, keyfile = self.determine_ssl_files_paths(options) dir_path, root = os.path.split(certfile) root, _ = os.path.splitext(root) try: if os.path.exists(certfile) and os.path.exists(keyfile): ssl_context = (certfile, keyfile) else: # Create cert, key files ourselves. ssl_context = make_ssl_devcert(os.path.join( dir_path, root), host='localhost') except ImportError: if self.show_startup_messages: print( "Werkzeug version is less than 0.9, trying adhoc certificate." ) ssl_context = "adhoc" else: ssl_context = None bind_url = "%s://%s:%s/" % ("https" if ssl_context else "http", self.addr if not self._raw_ipv6 else '[%s]' % self.addr, self.port) if self.show_startup_messages: print("\nDjango version %s, using settings %r" % (django.get_version(), settings.SETTINGS_MODULE)) print("Development server is running at %s" % (bind_url, )) print("Using the Werkzeug debugger (http://werkzeug.pocoo.org/)") print("Quit the server with %s." % quit_command) if open_browser: webbrowser.open(bind_url) if use_reloader and settings.USE_I18N: self.extra_files |= set( filter(lambda filename: str(filename).endswith('.mo'), gen_filenames())) if getattr(settings, 'RUNSERVER_PLUS_EXTRA_FILES', []): self.extra_files |= set(settings['RUNSERVER_PLUS_EXTRA_FILES']) # Werkzeug needs to be clued in its the main instance if running # without reloader or else it won't show key. # https://git.io/vVIgo if not use_reloader: os.environ['WERKZEUG_RUN_MAIN'] = 'true' # Don't run a second instance of the debugger / reloader # See also: https://github.com/django-extensions/django-extensions/issues/832 if os.environ.get('WERKZEUG_RUN_MAIN') != 'true': if self.nopin: os.environ['WERKZEUG_DEBUG_PIN'] = 'off' handler = DebuggedApplication(handler, True) runserver_plus_started.send(sender=self) run_simple( self.addr, int(self.port), handler, use_reloader=use_reloader, use_debugger=True, extra_files=self.extra_files, reloader_interval=reloader_interval, reloader_type=reloader_type, threaded=threaded, request_handler=WSGIRequestHandler, ssl_context=ssl_context, )
'msg_type': 'update_clients', 'clients': [ getattr(client, 'nickname', 'anonymous') for client in self.ws.handler.server.clients.values() ] })) def broadcast(self, message): for client in self.ws.handler.server.clients.values(): client.ws.send( json.dumps({ 'msg_type': 'message', 'nickname': message['nickname'], 'message': message['message'] })) def on_close(self, reason): print "Connection closed! " @flask_app.route('/') def index(): return render_template('index.html') WebSocketServer(('0.0.0.0', 8000), Resource([('^/chat', ChatApplication), ('^/.*', DebuggedApplication(flask_app))]), debug=False).serve_forever()
from flask import Flask from werkzeug.debug import DebuggedApplication app = Flask(__name__) # TODO: Python 2/3 compatible? if python 2.x app.debug=True if python 3 use werkzeug.debug, if error no debugger # app.debug=True # python 2.x # python 3 error TypeError: can't use a string pattern on a bytes-like object # http://stackoverflow.com/questions/10364854/flask-debug-true-does-not-work-when-going-through-uwsgi app.wsgi_app = DebuggedApplication(app.wsgi_app, True) # python 3.x story = ''' One day {character} was feeling {adjective} and then decided to {verb} ''' parts = ['character', 'adjective', 'verb'] def parts_form(parts): markup = '' for part in parts: markup = markup + '<p><label>{part}<input name="{part}"></label></p>'.format(part=part) return markup @app.route('/') def hello(): return '<h1>Hello World!</h1>' @app.route('/<yourname>/') def show_visitor_name(yourname): return '<h1>Hello {}</h1>'.format(yourname) @app.route('/post/<int:post_id>')
'point': 64, 'line': 8, 'polygon': 8 } } }, 'yaml': { 'type': 'parse', 'parse': { 'path': './yaml', }, 'callable': { 'dotted-name': 'vectordatasource.meta.python.make_function_mapping', 'args': ['vectordatasource.gen'], }, }, } tile_server = create_tileserver_from_config(config) tile_server.propagate_errors = True application = DebuggedApplication(tile_server, True) http_server = make_server('localhost', 0, application, threaded=False) with open(sys.argv[3] + ".tmp", 'w') as fh: print>>fh, "%d" % http_server.server_port # move into place atomically os.rename(sys.argv[3] + ".tmp", sys.argv[3]) http_server.serve_forever()
from gevent.wsgi import WSGIServer from werkzeug.debug import DebuggedApplication from run import app http_server = WSGIServer(('', 5000), DebuggedApplication(app)) http_server.serve_forever()
def make_application(debug=None, apps_dir='apps', project_dir=None, include_apps=None, debug_console=True, settings_file='settings.ini', local_settings_file='local_settings.ini', start=True, default_settings=None, dispatcher_cls=None, dispatcher_kwargs=None): """ Make an application object """ from uliweb.utils.common import import_attr dispatcher_cls = dispatcher_cls or SimpleFrame.Dispatcher dispatcher_kwargs = dispatcher_kwargs or {} if project_dir: apps_dir = os.path.normpath(os.path.join(project_dir, 'apps')) if apps_dir not in sys.path: sys.path.insert(0, apps_dir) install_config(apps_dir) application = app = dispatcher_cls(apps_dir=apps_dir, include_apps=include_apps, settings_file=settings_file, local_settings_file=local_settings_file, start=start, default_settings=default_settings, **dispatcher_kwargs) #settings global application object SimpleFrame.__global__.application = app #process wsgi middlewares middlewares = [] parameters = {} for name, v in uliweb.settings.get('WSGI_MIDDLEWARES', {}).iteritems(): order, kwargs = 500, {} if not v: continue if isinstance(v, (list, tuple)): if len(v) > 3: logging.error('WSGI_MIDDLEWARE %s difinition is not right' % name) raise uliweb.UliwebError( 'WSGI_MIDDLEWARE %s difinition is not right' % name) cls = v[0] if len(v) == 2: if isinstance(v[1], int): order = v[1] else: kwargs = v[1] else: order, kwargs = v[1], v[2] else: cls = v middlewares.append((order, name)) parameters[name] = cls, kwargs middlewares.sort(cmp=lambda x, y: cmp(x[0], y[0])) for name in reversed([x[1] for x in middlewares]): clspath, kwargs = parameters[name] cls = import_attr(clspath) app = cls(app, **kwargs) debug_flag = uliweb.settings.GLOBAL.DEBUG if debug or (debug is None and debug_flag): log.setLevel(logging.DEBUG) log.info(' * Loading DebuggedApplication...') from werkzeug.debug import DebuggedApplication app = DebuggedApplication( app, uliweb.settings.GLOBAL.get('DEBUG_CONSOLE', False)) return app
class RegexConverter(BaseConverter): def __init__(self, url_map, *items): super(RegexConverter, self).__init__(url_map) self.regex = items[0] app = flask.Flask(__name__, template_folder="../templates", static_folder="../static") app.before_request(prepare_redirects()) app.url_map.strict_slashes = False app.url_map.converters["regex"] = RegexConverter app.wsgi_app = ProxyFix(app.wsgi_app) if app.debug: app.wsgi_app = DebuggedApplication(app.wsgi_app) talisker.flask.register(app) talisker.logs.set_global_extra({"service": "jp.ubuntu.com"}) set_handlers(app) app.register_blueprint(jp_website) blog = BlogExtension() blog.init_app(app, "Ubuntu blog", [3184], "lang:jp", "/blog") if __name__ == "__main__": app.run(host="0.0.0.0")
import socket import sys import site from meeple import app from werkzeug.debug import DebuggedApplication application = app application.config['DEBUG'] = True application = DebuggedApplication(application, evalex=True, show_hidden_frames=False) application.debug = True
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application) # apply Werkzeug WSGI middleware # if os.environ.setdefault('DJANGO_DEBUG', 'False') is True: from werkzeug.debug import DebuggedApplication application = DebuggedApplication(application, evalex=True, pin_security=True, pin_logging=True) application.debug = True # bjoern.run(application, 'unix:/data/sockets/bjoern-mhackspace.sock') #https://stackoverflow.com/questions/46301706/bjoern-wsgi-server-unix-socket-permissions # class ReloadApplicationMiddleware(object): # def __call__(self, *args, **kwargs): # print('Reloading...') # self.app = self.import_func() # return self.app(*args, **kwargs) # application = ReloadApplicationMiddleware(application) socket_path = '/data/sockets/maidstone-hackspace.sock'
# -*- coding: utf-8 -*- import sys, os sys.path.append('/home/k/kvognc/positions.mrnr.ru/project' ) # указываем директорию с проектом sys.path.append( '/home/k/kvognc/.local/Python-3.7.0/virtualenv/positions.mrnr.ru/lib/python3.7/site-packages' ) # указываем директорию с библиотеками, куда поставили Flask from project import app as application # когда Flask стартует, он ищет application. Если не указать 'as application', сайт не заработает from werkzeug.debug import DebuggedApplication # Опционально: подключение модуля отладки application.wsgi_app = DebuggedApplication( application.wsgi_app, True) # Опционально: включение модуля отадки application.debug = True # Опционально: True/False устанавливается по необходимости в отладке
def run_simple(hostname, port, application, use_reloader=False, use_debugger=False, use_evalex=True, extra_files=None, reloader_interval=1, threaded=False, processes=1, request_handler=None, static_files=None, passthrough_errors=False, ssl_context=None): """Start an application using wsgiref and with an optional reloader. This wraps `wsgiref` to fix the wrong default reporting of the multithreaded WSGI variable and adds optional multithreading and fork support. This function has a command-line interface too:: python -m werkzeug.serving --help .. versionadded:: 0.5 `static_files` was added to simplify serving of static files as well as `passthrough_errors`. .. versionadded:: 0.6 support for SSL was added. .. versionadded:: 0.8 Added support for automatically loading a SSL context from certificate file and private key. .. versionadded:: 0.9 Added command-line interface. :param hostname: The host for the application. eg: ``'localhost'`` :param port: The port for the server. eg: ``8080`` :param application: the WSGI application to execute :param use_reloader: should the server automatically restart the python process if modules were changed? :param use_debugger: should the werkzeug debugging system be used? :param use_evalex: should the exception evaluation feature be enabled? :param extra_files: a list of files the reloader should watch additionally to the modules. For example configuration files. :param reloader_interval: the interval for the reloader in seconds. :param threaded: should the process handle each request in a separate thread? :param processes: if greater than 1 then handle each request in a new process up to this maximum number of concurrent processes. :param request_handler: optional parameter that can be used to replace the default one. You can use this to replace it with a different :class:`~BaseHTTPServer.BaseHTTPRequestHandler` subclass. :param static_files: a dict of paths for static files. This works exactly like :class:`SharedDataMiddleware`, it's actually just wrapping the application in that middleware before serving. :param passthrough_errors: set this to `True` to disable the error catching. This means that the server will die on errors but it can be useful to hook debuggers in (pdb etc.) :param ssl_context: an SSL context for the connection. Either an OpenSSL context, a tuple in the form ``(cert_file, pkey_file)``, the string ``'adhoc'`` if the server should automatically create one, or `None` to disable SSL (which is the default). """ if use_debugger: from werkzeug.debug import DebuggedApplication application = DebuggedApplication(application, use_evalex) if static_files: from werkzeug.wsgi import SharedDataMiddleware application = SharedDataMiddleware(application, static_files) def inner(): make_server(hostname, port, application, threaded, processes, request_handler, passthrough_errors, ssl_context).serve_forever() if os.environ.get('WERKZEUG_RUN_MAIN') != 'true': display_hostname = hostname != '*' and hostname or 'localhost' if ':' in display_hostname: display_hostname = '[%s]' % display_hostname quit_msg = '(Press CTRL+C to quit)' _log('info', ' * Running on %s://%s:%d/ %s', ssl_context is None and 'http' or 'https', display_hostname, port, quit_msg) if use_reloader: # Create and destroy a socket so that any exceptions are raised before # we spawn a separate Python interpreter and lose this ability. address_family = select_ip_version(hostname, port) test_socket = socket.socket(address_family, socket.SOCK_STREAM) test_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) test_socket.bind((hostname, port)) test_socket.close() run_with_reloader(inner, extra_files, reloader_interval) else: inner()
return None file_key = list(request.files.keys())[0] file = request.files.get(file_key) img = Image.open(file.stream) img.load() return img def predict_wsgi(environ, start_response): img = read_image_from_wsgi_request(environ) if not img: return Response('no file uploaded', 400)(environ, start_response) # The predictor must be lazily instantiated; # the TensorFlow graph can apparently not be shared # between processes. global predictor if not predictor: predictor = Predictor() prediction = predictor.predict_digit(img) response = Response(json.dumps(prediction), mimetype='application/json') return response(environ, start_response) predict_wsgi = DebuggedApplication(predict_wsgi) if __name__ == '__main__': from werkzeug.serving import run_simple run_simple('localhost', 3000, predict_wsgi)
def __init__(self, app, socketio): self.app = app if app.debug: app.wsgi_app = DebuggedApplication(app.wsgi_app, evalex=True) self.wsgi_app = app.wsgi_app self.socketio = socketio
# import flask dependencies from flask import Flask, request, make_response, jsonify, render_template import requests import json from datetime import datetime from werkzeug.debug import DebuggedApplication # from gen_HTML import generate_HTML_report app = Flask(__name__) appDebug = DebuggedApplication(app, evalex=True) # default route @app.route('/') def index(): return render_template("gamepagecard.html") # Host report @app.route('/fasit', methods=['GET']) def report(): return render_template('fasitpage.html') # run the app if __name__ == '__main__': app.run(debug=True)
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from werkzeug.debug import DebuggedApplication import app.config as config from app import create_app app = create_app() if config.DEBUG: def nointernalerror(): raise sys.exc_info() app.internalerror = nointernalerror app = DebuggedApplication(app.wsgifunc(), evalex=True) else: app = app.wsgifunc()
def run_simple_wsgi( hostname: str, port: int, application: "WSGIApplication", use_reloader: bool = False, use_debugger: bool = False, use_evalex: bool = True, extra_files: t.Optional[t.Iterable[str]] = None, exclude_patterns: t.Optional[t.Iterable[str]] = None, reloader_interval: int = 1, reloader_type: str = "stat", threaded: bool = False, processes: int = 1, request_handler: t.Optional[t.Type[WSGIRequestHandler]] = None, static_files: t.Optional[t.Dict[str, t.Union[str, t.Tuple[str, str]]]] = None, passthrough_errors: bool = False, ssl_context: t.Optional[_TSSLContextArg] = None, ) -> None: """Start a WSGI application. Optional features include a reloader, multithreading and fork support. :param hostname: The host to bind to, for example ``'localhost'``. If the value is a path that starts with ``unix://`` it will bind to a Unix socket instead of a TCP socket.. :param port: The port for the server. eg: ``8080`` :param application: the WSGI application to execute :param use_reloader: should the server automatically restart the python process if modules were changed? :param use_debugger: should the werkzeug debugging system be used? :param use_evalex: should the exception evaluation feature be enabled? :param extra_files: a list of files the reloader should watch additionally to the modules. For example configuration files. :param exclude_patterns: List of :mod:`fnmatch` patterns to ignore when running the reloader. For example, ignore cache files that shouldn't reload when updated. :param reloader_interval: the interval for the reloader in seconds. :param reloader_type: the type of reloader to use. The default is auto detection. Valid values are ``'stat'`` and ``'watchdog'``. See :ref:`reloader` for more information. :param threaded: should the process handle each request in a separate thread? :param processes: if greater than 1 then handle each request in a new process up to this maximum number of concurrent processes. :param request_handler: optional parameter that can be used to replace the default one. You can use this to replace it with a different :class:`~BaseHTTPServer.BaseHTTPRequestHandler` subclass. :param static_files: a list or dict of paths for static files. This works exactly like :class:`SharedDataMiddleware`, it's actually just wrapping the application in that middleware before serving. :param passthrough_errors: set this to `True` to disable the error catching. This means that the server will die on errors but it can be useful to hook debuggers in (pdb etc.) :param ssl_context: an SSL context for the connection. Either an :class:`ssl.SSLContext`, a tuple in the form ``(cert_file, pkey_file)``, the string ``'adhoc'`` if the server should automatically create one, or ``None`` to disable SSL (which is the default). """ if not isinstance(port, int): raise TypeError("port must be an integer") if use_debugger: from werkzeug.debug import DebuggedApplication application = DebuggedApplication(application, use_evalex) if static_files: from werkzeug.middleware.shared_data import SharedDataMiddleware application = SharedDataMiddleware(application, static_files) def log_startup(sock: socket.socket) -> None: _navycut_base_logger() if sock.family == af_unix: Console.log.Info(f"Running on {hostname} (Press CTRL+C to quit)") else: if hostname == "0.0.0.0": _running_on_all_addr_logger() display_hostname = get_interface_ip(socket.AF_INET) elif hostname == "::": _running_on_all_addr_logger() display_hostname = get_interface_ip(socket.AF_INET6) else: display_hostname = hostname if ":" in display_hostname: display_hostname = f"[{display_hostname}]" _run_base_server_logger("http" if ssl_context is None else "https", display_hostname, sock.getsockname()[1] ) def inner() -> None: try: fd: t.Optional[int] = int(os.environ["WERKZEUG_SERVER_FD"]) except (LookupError, ValueError): fd = None srv = make_server( hostname, port, application, threaded, processes, request_handler, passthrough_errors, ssl_context, fd=fd, ) if fd is None: log_startup(srv.socket) srv.serve_forever() if use_reloader: # If we're not running already in the subprocess that is the # reloader we want to open up a socket early to make sure the # port is actually available. if not is_running_from_reloader(): if port == 0 and not can_open_by_fd: raise ValueError( "Cannot bind to a random port with enabled " "reloader if the Python interpreter does " "not support socket opening by fd." ) # Create and destroy a socket so that any exceptions are # raised before we spawn a separate Python interpreter and # lose this ability. address_family = select_address_family(hostname, port) server_address = get_sockaddr(hostname, port, address_family) s = socket.socket(address_family, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(server_address) s.set_inheritable(True) # If we can open the socket by file descriptor, then we can just # reuse this one and our socket will survive the restarts. if can_open_by_fd: os.environ["WERKZEUG_SERVER_FD"] = str(s.fileno()) s.listen(LISTEN_QUEUE) log_startup(s) else: s.close() if address_family == af_unix: server_address = t.cast(str, server_address) Console.log.Info(f"Unlinking {server_address}") os.unlink(server_address) from ._reloader import run_with_reloader as _rwr _rwr( inner, extra_files=extra_files, exclude_patterns=exclude_patterns, interval=reloader_interval, reloader_type=reloader_type, ) else: inner()
return render_template('/testing/test_form.html') @app.route('/testing/test_form_response', methods=['POST']) def test_form_response(): first_name = request.form['first_name'] last_name = request.form['last_name'] return 'Hello %s %s !<br/><br/><a href="/testing/test_form">Back</a>' % (first_name, last_name) @app.route('/testing/testPlotly') def test_plotly(): return render_template('/testing/testPlotly.html') @app.route('/testing/testPlotly_response') def test_plotly_response(): n_points = int(request.args.get('n_points')) df = testPlotly.get_data(n_points) html_chart = testPlotly.get_plotly_html(df, '# points = ' + str(n_points)) return jsonify({'html': html_chart}) app.debug = True # debug mode is on from werkzeug.debug import DebuggedApplication app.wsgi_app = DebuggedApplication(app.wsgi_app, evalex=True) if __name__ == '__main__': app.run(debug=True)
def run(): global application app.debug = True application = DebuggedApplication(application, evalex=True) server = WSGIServer(('0.0.0.0', PORT), application) server.serve_forever()
def run(self, app, host=None, port=None, **kwargs): """Run the SocketIO web server. :param app: The Flask application instance. :param host: The hostname or IP address for the server to listen on. Defaults to 127.0.0.1. :param port: The port number for the server to listen on. Defaults to 5000. :param debug: ``True`` to start the server in debug mode, ``False`` to start in normal mode. :param use_reloader: ``True`` to enable the Flask reloader, ``False`` to disable it. :param extra_files: A list of additional files that the Flask reloader should watch. Defaults to ``None`` :param log_output: If ``True``, the server logs all incomming connections. If ``False`` logging is disabled. Defaults to ``True`` in debug mode, ``False`` in normal mode. Unused when the threading async mode is used. :param kwargs: Additional web server options. The web server options are specific to the server used in each of the supported async modes. Note that options provided here will not be seen when using an external web server such as gunicorn, since this method is not called in that case. """ if host is None: host = '127.0.0.1' if port is None: server_name = app.config['SERVER_NAME'] if server_name and ':' in server_name: port = int(server_name.rsplit(':', 1)[1]) else: port = 5000 debug = kwargs.pop('debug', app.debug) log_output = kwargs.pop('log_output', debug) use_reloader = kwargs.pop('use_reloader', debug) extra_files = kwargs.pop('extra_files', None) app.debug = debug if app.debug and self.server.eio.async_mode != 'threading': # put the debug middleware between the SocketIO middleware # and the Flask application instance # # mw1 mw2 mw3 Flask app # o ---- o ---- o ---- o # / # o Flask-SocketIO # \ middleware # o # Flask-SocketIO WebSocket handler # # BECOMES # # dbg-mw mw1 mw2 mw3 Flask app # o ---- o ---- o ---- o ---- o # / # o Flask-SocketIO # \ middleware # o # Flask-SocketIO WebSocket handler # self.sockio_mw.wsgi_app = DebuggedApplication( self.sockio_mw.wsgi_app, evalex=True) if self.server.eio.async_mode == 'threading': from werkzeug._internal import _log _log( 'warning', 'WebSocket transport not available. Install ' 'eventlet or gevent and gevent-websocket for ' 'improved performance.') app.run(host=host, port=port, threaded=True, use_reloader=use_reloader, **kwargs) elif self.server.eio.async_mode == 'eventlet': def run_server(): import eventlet import eventlet.wsgi import eventlet.green addresses = eventlet.green.socket.getaddrinfo(host, port) if not addresses: raise RuntimeError( 'Could not resolve host to a valid address') eventlet_socket = eventlet.listen(addresses[0][4], addresses[0][0]) # If provided an SSL argument, use an SSL socket ssl_args = [ 'keyfile', 'certfile', 'server_side', 'cert_reqs', 'ssl_version', 'ca_certs', 'do_handshake_on_connect', 'suppress_ragged_eofs', 'ciphers' ] ssl_params = {k: kwargs[k] for k in kwargs if k in ssl_args} if len(ssl_params) > 0: for k in ssl_params: kwargs.pop(k) ssl_params['server_side'] = True # Listening requires true eventlet_socket = eventlet.wrap_ssl( eventlet_socket, **ssl_params) eventlet.wsgi.server(eventlet_socket, app, log_output=log_output, **kwargs) if use_reloader: run_with_reloader(run_server, extra_files=extra_files) else: run_server() elif self.server.eio.async_mode == 'gevent': from gevent import pywsgi try: from geventwebsocket.handler import WebSocketHandler websocket = True except ImportError: websocket = False log = 'default' if not log_output: log = None if websocket: self.wsgi_server = pywsgi.WSGIServer( (host, port), app, handler_class=WebSocketHandler, log=log, **kwargs) else: self.wsgi_server = pywsgi.WSGIServer((host, port), app, log=log, **kwargs) if use_reloader: # monkey patching is required by the reloader from gevent import monkey monkey.patch_all() def run_server(): self.wsgi_server.serve_forever() run_with_reloader(run_server, extra_files=extra_files) else: self.wsgi_server.serve_forever()
from .utils import jsonify from .database import to_db, db, DBVoteMessage, DBMessage, DBInitMessage, DBPrevoteMessage, DBProposeMessage, DBAcknowledge, \ MSG_TYPE_CLASS_MAP from node.enums import INIT # noqa # pylint: disable=unused-import from node.messages import Message # noqa # pylint: disable=unused-import __author__ = 'luckydonald' logger = logging.getLogger(__name__) VERSION = "0.0.1" __version__ = VERSION assert INIT == INIT # to prevent the unused import warning. Is used in SQL statement. from werkzeug.debug import DebuggedApplication app = Flask(__name__) debug = DebuggedApplication(app, console_path="/console/") API_V1 = "" API_V2 = "/api/v2" @app.route(API_V1 + "/dump", methods=['POST', 'GET', 'PUT']) @app.route(API_V1 + "/dump/", methods=['POST', 'GET', 'PUT']) @orm.db_session def dump_to_db(): try: logger.info("Incoming: {}".format(request.get_json(force=True))) msg = to_db(request.get_json(force=True)) if msg: db.commit() logger.info("Added {}: {id}".format(msg, id=msg.id))
os.umask(int(settings.get('global', 'umask'), 8)) if not settings.get_bool('global', 'maintenance'): application = KonTextWsgiApp() else: application = MaintenanceWsgiApp() robots_path = os.path.join(os.path.dirname(__file__), 'files/robots.txt') if os.path.isfile(robots_path): from werkzeug.wsgi import SharedDataMiddleware application = SharedDataMiddleware(application, {'/robots.txt': robots_path}) if settings.is_debug_mode(): from werkzeug.debug import DebuggedApplication application = DebuggedApplication(application) # profiling if settings.debug_level() == settings.DEBUG_AND_PROFILE: from werkzeug.contrib.profiler import ProfilerMiddleware, MergeStream stream = MergeStream( sys.stdout, open(settings.get('global', 'profile_log_path'), 'w')) application = ProfilerMiddleware(application, stream) if __name__ == '__main__': from werkzeug.serving import run_simple from werkzeug.wsgi import SharedDataMiddleware import argparse DEFAULT_PORT = 5000 DEFAULT_ADDR = '127.0.0.1'
#!/usr/bin/env python """ """ from werkzeug.contrib.fixers import ProxyFix # needed for http server proxies from werkzeug.debug import DebuggedApplication from flask_reddit import app # as application app.wsgi_app = ProxyFix(app.wsgi_app) # needed for http server proxies application = DebuggedApplication(app, True)
import os import sys from werkzeug.contrib.fixers import ProxyFix # allow errors and print statements be redirected to error.log sys.stdout = sys.stderr # get project dir project_path = os.getcwd() ## activate virtualenv #activate_this = os.path.join(project_path, 'venv/bin/activate_this.py') #execfile(activate_this, dict(__file__=activate_this)) # retrieve app from init import app as application # enable debugging mode if necessary if application.debug: # start interactive debugger from werkzeug.debug import DebuggedApplication application = DebuggedApplication(application, evalex=True) else: # add this fix when working behind a proxy application.wsgi_app = ProxyFix(application.wsgi_app)
def make_flask_stack(conf, **app_conf): """ This has to pass the flask app through all the same middleware that Pylons used """ root = os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) debug = asbool(conf.get('debug', conf.get('DEBUG', False))) testing = asbool(app_conf.get('testing', app_conf.get('TESTING', False))) app = flask_app = CKANFlask(__name__) app.debug = debug app.testing = testing app.template_folder = os.path.join(root, 'templates') app.app_ctx_globals_class = CKAN_AppCtxGlobals app.url_rule_class = CKAN_Rule app.jinja_options = jinja_extensions.get_jinja_env_options() # Update Flask config with the CKAN values. We use the common config # object as values might have been modified on `load_environment` if config: app.config.update(config) else: app.config.update(conf) app.config.update(app_conf) # Do all the Flask-specific stuff before adding other middlewares # Secret key needed for flask-debug-toolbar and sessions if not app.config.get('SECRET_KEY'): app.config['SECRET_KEY'] = config.get('beaker.session.secret') if not app.config.get('SECRET_KEY'): raise RuntimeError(u'You must provide a value for the secret key' ' with the SECRET_KEY config option') if debug: from flask_debugtoolbar import DebugToolbarExtension app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False DebugToolbarExtension(app) from werkzeug.debug import DebuggedApplication app = DebuggedApplication(app, True) app = app.app log = logging.getLogger('werkzeug') log.setLevel(logging.DEBUG) # Use Beaker as the Flask session interface class BeakerSessionInterface(SessionInterface): def open_session(self, app, request): if 'beaker.session' in request.environ: return request.environ['beaker.session'] def save_session(self, app, session, response): session.save() namespace = 'beaker.session.' session_opts = dict([(k.replace('beaker.', ''), v) for k, v in config.iteritems() if k.startswith(namespace)]) if (not session_opts.get('session.data_dir') and session_opts.get('session.type', 'file') == 'file'): cache_dir = app_conf.get('cache_dir') or app_conf.get('cache.dir') session_opts['session.data_dir'] = '{data_dir}/sessions'.format( data_dir=cache_dir) app.wsgi_app = SessionMiddleware(app.wsgi_app, session_opts) app.session_interface = BeakerSessionInterface() # Add Jinja2 extensions and filters app.jinja_env.filters['empty_and_escape'] = \ jinja_extensions.empty_and_escape # Common handlers for all requests app.before_request(ckan_before_request) app.after_request(ckan_after_request) # Template context processors app.context_processor(helper_functions) app.context_processor(c_object) @app.context_processor def ungettext_alias(): u''' Provide `ungettext` as an alias of `ngettext` for backwards compatibility ''' return dict(ungettext=ungettext) # Babel pairs = [(os.path.join(root, u'i18n'), 'ckan') ] + [(p.i18n_directory(), p.i18n_domain()) for p in PluginImplementations(ITranslation)] i18n_dirs, i18n_domains = zip(*pairs) app.config[u'BABEL_TRANSLATION_DIRECTORIES'] = ';'.join(i18n_dirs) app.config[u'BABEL_DOMAIN'] = 'ckan' app.config[u'BABEL_MULTIPLE_DOMAINS'] = ';'.join(i18n_domains) babel = CKANBabel(app) babel.localeselector(get_locale) @app.route('/hello', methods=['GET']) def hello_world(): return 'Hello World, this is served by Flask' @app.route('/hello', methods=['POST']) def hello_world_post(): return 'Hello World, this was posted to Flask' # WebAssets _setup_webassets(app) # Auto-register all blueprints defined in the `views` folder _register_core_blueprints(app) _register_error_handler(app) # Set up each IBlueprint extension as a Flask Blueprint for plugin in PluginImplementations(IBlueprint): if hasattr(plugin, 'get_blueprint'): plugin_blueprints = plugin.get_blueprint() if not isinstance(plugin_blueprints, list): plugin_blueprints = [plugin_blueprints] for blueprint in plugin_blueprints: app.register_extension_blueprint(blueprint) lib_plugins.register_package_blueprints(app) lib_plugins.register_group_blueprints(app) # Set flask routes in named_routes for rule in app.url_map.iter_rules(): if '.' not in rule.endpoint: continue controller, action = rule.endpoint.split('.') needed = list(rule.arguments - set(rule.defaults or {})) route = { rule.endpoint: { 'action': action, 'controller': controller, 'highlight_actions': action, 'needed': needed } } config['routes.named_routes'].update(route) # Start other middleware for plugin in PluginImplementations(IMiddleware): app = plugin.make_middleware(app, config) # Fanstatic fanstatic_enable_rollup = asbool( app_conf.get('fanstatic_enable_rollup', False)) if debug: fanstatic_config = { 'versioning': True, 'recompute_hashes': True, 'minified': False, 'bottom': True, 'bundle': False, 'rollup': fanstatic_enable_rollup, } else: fanstatic_config = { 'versioning': True, 'recompute_hashes': False, 'minified': True, 'bottom': True, 'bundle': True, 'rollup': fanstatic_enable_rollup, } root_path = config.get('ckan.root_path', None) if root_path: root_path = re.sub('/{{LANG}}', '', root_path) fanstatic_config['base_url'] = root_path app = Fanstatic(app, **fanstatic_config) for plugin in PluginImplementations(IMiddleware): try: app = plugin.make_error_log_middleware(app, config) except AttributeError: log.critical('Middleware class {0} is missing the method' 'make_error_log_middleware.'.format( plugin.__class__.__name__)) # Initialize repoze.who who_parser = WhoConfig(conf['here']) who_parser.parse(open(app_conf['who.config_file'])) app = PluggableAuthenticationMiddleware( app, who_parser.identifiers, who_parser.authenticators, who_parser.challengers, who_parser.mdproviders, who_parser.request_classifier, who_parser.challenge_decider, logging.getLogger('repoze.who'), logging.WARN, # ignored who_parser.remote_user_key) # Update the main CKAN config object with the Flask specific keys # that were set here or autogenerated flask_config_keys = set(flask_app.config.keys()) - set(config.keys()) for key in flask_config_keys: config[key] = flask_app.config[key] # Add a reference to the actual Flask app so it's easier to access app._wsgi_app = flask_app return app
from flask.app import Flask from flask.ext.admin.base import MenuLink import settings from my_app.admin_views import AdminIndex from werkzeug.debug import DebuggedApplication from flask_admin import Admin from google.appengine.api import users flask_app = Flask(__name__) flask_app.config.from_object(settings) admin = Admin( flask_app, name='Solicitudes', index_view=AdminIndex(url='/admin', name='Platzi'), ) admin.add_link(MenuLink(name='Logout', url=users.create_logout_url('/'))) if flask_app.config['DEBUG']: flask_app.debug = True app = DebuggedApplication(flask_app, evalex=True) app = flask_app from my_app import admin_views from my_app import views
def make_flask_stack(conf, **app_conf): """ This has to pass the flask app through all the same middleware that Pylons used """ root = os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) debug = asbool(conf.get('debug', conf.get('DEBUG', False))) testing = asbool(app_conf.get('testing', app_conf.get('TESTING', False))) app = flask_app = CKANFlask(__name__) app.debug = debug app.testing = testing app.template_folder = os.path.join(root, 'templates') app.app_ctx_globals_class = CKAN_AppCtxGlobals app.url_rule_class = CKAN_Rule app.jinja_options = jinja_extensions.get_jinja_env_options() # Update Flask config with the CKAN values. We use the common config # object as values might have been modified on `load_environment` if config: app.config.update(config) else: app.config.update(conf) app.config.update(app_conf) # Do all the Flask-specific stuff before adding other middlewares # Secret key needed for flask-debug-toolbar and sessions if not app.config.get('SECRET_KEY'): app.config['SECRET_KEY'] = config.get('beaker.session.secret') if not app.config.get('SECRET_KEY'): raise RuntimeError(u'You must provide a value for the secret key' ' with the SECRET_KEY config option') if debug: from flask_debugtoolbar import DebugToolbarExtension app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False DebugToolbarExtension(app) from werkzeug.debug import DebuggedApplication app = DebuggedApplication(app, True) app = app.app log = logging.getLogger('werkzeug') log.setLevel(logging.DEBUG) # Use Beaker as the Flask session interface class BeakerSessionInterface(SessionInterface): def open_session(self, app, request): if 'beaker.session' in request.environ: return request.environ['beaker.session'] def save_session(self, app, session, response): session.save() namespace = 'beaker.session.' session_opts = dict([(k.replace('beaker.', ''), v) for k, v in config.iteritems() if k.startswith(namespace)]) if (not session_opts.get('session.data_dir') and session_opts.get('session.type', 'file') == 'file'): cache_dir = app_conf.get('cache_dir') or app_conf.get('cache.dir') session_opts['session.data_dir'] = '{data_dir}/sessions'.format( data_dir=cache_dir) app.wsgi_app = SessionMiddleware(app.wsgi_app, session_opts) app.session_interface = BeakerSessionInterface() # Add Jinja2 extensions and filters app.jinja_env.filters['empty_and_escape'] = \ jinja_extensions.empty_and_escape # Common handlers for all requests app.before_request(ckan_before_request) app.after_request(ckan_after_request) # Template context processors app.context_processor(helper_functions) app.context_processor(c_object) @app.context_processor def ungettext_alias(): u''' Provide `ungettext` as an alias of `ngettext` for backwards compatibility ''' return dict(ungettext=ungettext) # Babel pairs = [(os.path.join(root, u'i18n'), 'ckan')] + [ (p.i18n_directory(), p.i18n_domain()) for p in PluginImplementations(ITranslation) ] i18n_dirs, i18n_domains = zip(*pairs) app.config[u'BABEL_TRANSLATION_DIRECTORIES'] = ';'.join(i18n_dirs) app.config[u'BABEL_DOMAIN'] = 'ckan' app.config[u'BABEL_MULTIPLE_DOMAINS'] = ';'.join(i18n_domains) babel = CKANBabel(app) babel.localeselector(get_locale) @app.route('/hello', methods=['GET']) def hello_world(): return 'Hello World, this is served by Flask' @app.route('/hello', methods=['POST']) def hello_world_post(): return 'Hello World, this was posted to Flask' # WebAssets _setup_webassets(app) # Auto-register all blueprints defined in the `views` folder _register_core_blueprints(app) _register_error_handler(app) # Set up each IBlueprint extension as a Flask Blueprint for plugin in PluginImplementations(IBlueprint): if hasattr(plugin, 'get_blueprint'): plugin_blueprints = plugin.get_blueprint() if not isinstance(plugin_blueprints, list): plugin_blueprints = [plugin_blueprints] for blueprint in plugin_blueprints: app.register_extension_blueprint(blueprint) lib_plugins.register_package_blueprints(app) lib_plugins.register_group_blueprints(app) # Set flask routes in named_routes for rule in app.url_map.iter_rules(): if '.' not in rule.endpoint: continue controller, action = rule.endpoint.split('.') needed = list(rule.arguments - set(rule.defaults or {})) route = { rule.endpoint: { 'action': action, 'controller': controller, 'highlight_actions': action, 'needed': needed } } config['routes.named_routes'].update(route) # Start other middleware for plugin in PluginImplementations(IMiddleware): app = plugin.make_middleware(app, config) # Fanstatic fanstatic_enable_rollup = asbool(app_conf.get('fanstatic_enable_rollup', False)) if debug: fanstatic_config = { 'versioning': True, 'recompute_hashes': True, 'minified': False, 'bottom': True, 'bundle': False, 'rollup': fanstatic_enable_rollup, } else: fanstatic_config = { 'versioning': True, 'recompute_hashes': False, 'minified': True, 'bottom': True, 'bundle': True, 'rollup': fanstatic_enable_rollup, } root_path = config.get('ckan.root_path', None) if root_path: root_path = re.sub('/{{LANG}}', '', root_path) fanstatic_config['base_url'] = root_path app = Fanstatic(app, **fanstatic_config) for plugin in PluginImplementations(IMiddleware): try: app = plugin.make_error_log_middleware(app, config) except AttributeError: log.critical('Middleware class {0} is missing the method' 'make_error_log_middleware.' .format(plugin.__class__.__name__)) # Initialize repoze.who who_parser = WhoConfig(conf['here']) who_parser.parse(open(app_conf['who.config_file'])) app = PluggableAuthenticationMiddleware( app, who_parser.identifiers, who_parser.authenticators, who_parser.challengers, who_parser.mdproviders, who_parser.request_classifier, who_parser.challenge_decider, logging.getLogger('repoze.who'), logging.WARN, # ignored who_parser.remote_user_key ) # Update the main CKAN config object with the Flask specific keys # that were set here or autogenerated flask_config_keys = set(flask_app.config.keys()) - set(config.keys()) for key in flask_config_keys: config[key] = flask_app.config[key] # Add a reference to the actual Flask app so it's easier to access app._wsgi_app = flask_app return app