# import flask dependencies from flask import Flask from flask import render_template 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(host='0.0.0.0', debug=True)
def start(ctx, presentation, port, config, media, theme, style, debug): """Start revelation presentation command""" # Check if reveal.js is installed if not os.path.exists(REVEALJS_FOLDER): click.echo("Reveal.js not found, running installation...") ctx.invoke(installreveal) # Check for presentation file if os.path.isfile(presentation): path = os.path.dirname(presentation) else: click.echo("Error: Presentation file not found.") ctx.exit(1) # Check for style override file if style and (not os.path.isfile(style) or not style.endswith(".css")): click.echo("Error: Style is not a css file or does not exists.") ctx.exit(1) # Check for media root if not media: media = os.path.join(path, "media") if not os.path.isdir(media): # Running without media folder media = None click.echo("Media folder not detected, running without media") # Check for theme root if not theme: theme = os.path.join(path, "theme") if not os.path.isdir(theme): # Running without theme folder theme = None # Check for configuration file if not config: config = os.path.join(path, "config.py") if not os.path.isfile(config): # Running without configuration file config = None click.echo("Configuration file not detected, running with defaults.") click.echo("Starting revelation server...") # instantiating revelation app app = Revelation(presentation, config, media, theme, style, True) if debug: app = DebuggedApplication(app) PresentationReloader.tracking_path = os.path.abspath(path) click.echo("Running at http://localhost:{}".format(port)) WebSocketServer( ("localhost", port), Resource([ ("^/reloader.*", PresentationReloader), ("^/.*", DebuggedApplication(app)), ]), ).serve_forever()
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. :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 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 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 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 not in ('', '*') and hostname or 'localhost' if ':' in display_hostname: display_hostname = '[%s]' % display_hostname quit_msg = '(Press CTRL+C to quit)' port = sock.getsockname()[1] _log('info', ' * Running on %s://%s:%d/ %s', ssl_context is None and 'http' or '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 os.environ.get('WERKZEUG_RUN_MAIN') != 'true': 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_ip_version(hostname, port) s = socket.socket(address_family, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((hostname, port)) 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() from ._reloader import run_with_reloader run_with_reloader(inner, extra_files, reloader_interval, reloader_type) else: inner()
""" WSGI config for mainsite project. 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", " mainsite.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
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
return current_app.response_class(out_json, mimetype='application/json') ### Add Request Headers & Initialize Flags ### @app.after_request def after_request(response): response.headers.add('Access-Control-Allow-Origin', '*') response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization') response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE') return response if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-p", dest="port_number", default="9982", help="Sets the Port") parser.add_argument("-d", dest="debug", default="False", help="Sets the Debugging Option") # Default port is production value; prod,stage,dev = 9982, sandbox=9983 args = parser.parse_args() port_num = int(args.port_number) debugger = args.debug == 'True' hostname = gethostname() app.run(host='0.0.0.0', port=port_num, debug=debugger, use_evalex=False) application = DebuggedApplication(app, True)
def _my_run_simple( hostname, port, application, use_reloader, use_debugger, use_evalex, extra_files, reloader_interval, reloader_type, threaded, processes, request_handler, static_files, passthrough_errors, ssl_context, ): """copy-paste-modify of werkzeug with a wishlist feature hack-added mainly this exists because the whole http server stack (an inheritance hierarchy four classes deep!) does not have a listener/hook interface. so the only thing this function accomplishes is to copy-paste what we need from `werkzeug.serving.run_simple()` *plus* we hold on to the server so we can hack it #here4. details: - this is a refactoring of `werkzeug.serving.run_simple` - if you want to see what the server would be like without this mostly redundant hackery, comment-in #here3 (NOTE you will be WITHOUT jobser). - we follow the structure there as much as is practical to do (while pruning some unnecesary stuff out - spiked at #history-A.1 (the first one, oops) """ 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): _ssl = (lambda: ssl_context is None and 'http' or 'https')() _hn = hostname _prt = sock.getsockname()[1] _msg = '(Press CTRL+C to quit)' _ws_log('info', ' * Running on %s://%s:%d/ %s', _ssl, _hn, _prt, _msg) def _inner(): fd = None s = os.environ.get('WERKZEUG_SERVER_FD') if s is not None: fd = int(s) srv = ws.make_server(hostname, port, application, threaded, processes, request_handler, passthrough_errors, ssl_context, fd) # :#here4: if use_reloader: _ = ' * WARNING: reloader is on so jobser will not be used!' _ws_log('warn', _) else: # _try_to_capture_that_lyfe(srv) # doesn't add much _hackishly_start_jobser_at_server_start(srv) _hackishly_stop_jobser_at_server_stop(srv) if fd is None: _log_startup(srv.socket) srv.serve_forever() import os if use_reloader: if os.environ.get('WERKZEUG_RUN_MAIN') != 'true': import socket addr_fam = socket.AF_INET s = socket.socket(addr_fam, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) _ai = socket.getaddrinfo(hostname, port, addr_fam, socket.SOCK_STREAM, socket.SOL_TCP) _sock_addr = _ai[0][4] # all this is is (host, port) s.bind(_sock_addr) s.set_inheritable(True) os.environ['WERKZEUG_SERVER_FD'] = str(s.fileno()) s.listen(ws.LISTEN_QUEUE) _log_startup(s) from werkzeug._reloader import run_with_reloader run_with_reloader(_inner, extra_files, reloader_interval, reloader_type) else: _inner()
def __init__( self, name, service, favicon_url=None, template_404=None, template_500=None, *args, **kwargs ): super().__init__(name, *args, **kwargs) self.service = service self.config["SECRET_KEY"] = os.getenv("SECRET_KEY", "base_secret") self.url_map.strict_slashes = False self.url_map.converters["regex"] = RegexConverter if self.debug: self.wsgi_app = DebuggedApplication(self.wsgi_app) self.wsgi_app = ProxyFix(self.wsgi_app) self.before_request(clear_trailing_slash) self.before_request( prepare_redirects( path=os.path.join(self.root_path, "..", "redirects.yaml") ) ) self.before_request( prepare_redirects( path=os.path.join( self.root_path, "..", "permanent-redirects.yaml" ), permanent=True, ) ) self.before_request( prepare_deleted( path=os.path.join(self.root_path, "..", "deleted.yaml") ) ) self.context_processor(base_context) talisker.flask.register(self) talisker.logs.set_global_extra({"service": self.service}) # Default error handlers if template_404: @self.errorhandler(404) def not_found_error(error): return flask.render_template(template_404), 404 if template_500: @self.errorhandler(500) def internal_error(error): return flask.render_template(template_500), 500 # Default routes if favicon_url: @self.route("/favicon.ico") def favicon(): return flask.redirect(favicon_url) robots_path = os.path.join(self.root_path, "..", "robots.txt") humans_path = os.path.join(self.root_path, "..", "humans.txt") if os.path.isfile(robots_path): @self.route("/robots.txt") def robots(): return flask.send_file(robots_path) if os.path.isfile(humans_path): @self.route("/humans.txt") def humans(): return flask.send_file(humans_path)
with open('chaturbate.json') as f: s = f.read() streams = json.loads(s) if request.args.get('cb', False) != False: cb = True else: cb = False sc = session.query(SexProviderSnapshot).filter(SexProviderSnapshot.available==True).order_by(SexProviderSnapshot.price.asc()).all() prices_sc = [float(p.price) for p in sc] stats_sc = {'mean': int(np.mean(prices_sc)), 'median': int(np.median(prices_sc)), 'min': min(prices_sc), 'max': max(prices_sc)} last_trades = Trade.last_trades(100, result=(Trade.date, Trade.amount, Trade.price)) last_trades.reverse() last_trades = tuple((trade[0].replace(tzinfo=datetime.timezone.utc).astimezone(tz=pytz.timezone('America/Caracas')).replace(tzinfo=None), locale.format('%.8f', trade[1], grouping=True), locale.format('%.2f', trade[2], grouping=True), locale.format('%.2f', trade[1]*trade[2], grouping=True)) for trade in last_trades) if streams['good']: stream = streams['good'][0] else: stream = None music_tags = ['<iframe style="border: 0; width: 100%; height: 120px;" src="https://bandcamp.com/EmbeddedPlayer/album=158016030/size=large/bgcol=ffffff/linkcol=0687f5/tracklist=false/artwork=small/transparent=true/" name="{}" seamless><a href="http://galaxie500.bandcamp.com/album/on-fire">On Fire by Galaxie 500</a></iframe>'.format(int(datetime.datetime.utcnow().timestamp())), '<iframe style="border: 0; width: 100%; height: 120px;" src="https://bandcamp.com/EmbeddedPlayer/album=1696464046/size=large/bgcol=ffffff/linkcol=0687f5/tracklist=false/artwork=small/transparent=true/" name="{}" seamless><a href="http://pwelverumandsun.bandcamp.com/album/dont-wake-me-up">Don't Wake Me Up by the Microphones</a></iframe>'.format(int(datetime.datetime.utcnow().timestamp())),] return render_template('index.html', stats_sc=stats_sc, vesusd=vesusd, last_trades=last_trades, sc_urls=[sc[0].source_url, random.choice([x for x in sc if int(x.price) == stats_sc['median']]).source_url, sc[-1].source_url], stream=stream, music_tag=random.choice(music_tags), cb=cb) app.debug = True app = DebuggedApplication(app, True, pin_security=False) if __name__ == '__main__': app.run(debug=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 _log('info', ' * Running on %s://%s:%d/', ssl_context is None and 'http' or 'https', display_hostname, port) 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()
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
def make_app(): app = setup_app(config, check_superuser=True) if debug: app = DebuggedApplication(app, True) return app
""" # 3rd party imports from werkzeug.debug import DebuggedApplication import cherrypy # Pjuu imports from pjuu import create_app if __name__ == '__main__': """ Run Pjuu inside a debug enabled CherryPy. This is our test server. It is much more stable than Flasks. By default we bind this to all IPs so that we can test the the dev site with our phones over the local network """ app = create_app() debug_app = DebuggedApplication(app, True) cherrypy.tree.graft(debug_app, '/') cherrypy.config.update({ 'engine.autoreload.on': True, 'server.socket_port': 5000, 'server.socket_host': '0.0.0.0' }) try: cherrypy.engine.start() cherrypy.engine.block() except KeyboardInterrupt: cherrypy.engine.stop()
def run(): global application app.debug = True application = DebuggedApplication(application, evalex=True) server = WSGIServer(('localhost', PORT), application, handler_class=WebSocketHandler) server.serve_forever()
parser.add_argument('-d', '--debug', action='store_true', help="Runs Stocksearch in Debug mode default flase") parser.add_argument( '-c', '--connection', default="secured/postgres.json", help= "The path to the database connection file default secured/postgres.json" ) parser.add_argument( '-i', '--init', action='store_true', help="Builds the documentation and runs all tests before start") args = parser.parse_args() if args.init: init() app.config['db-connection-file'] = args.connection if args.debug: app.debug = True debug_app = DebuggedApplication(app, evalex=True) run_simple(args.host, args.port, debug_app) else: run_simple(args.host, args.port, app)
from werkzeug.debug import DebuggedApplication import sys app_path = "/home/adorno/.workspace/theproject" # app path sys.path.insert(0, app_path) # virtual environment activate_this = app_path + "/venv/bin/activate_this.py" # for python 2 # execfile(activate_this, dict(__file__=activate_this)) # for python 3 with open(activate_this) as file: exec(file.read(), dict(__file__=activate_this)) from apps.web import web web.app.config["LOG_FILE"] = app_path + "/web.log" application = DebuggedApplication(web.app, True)
data = sequence.pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH) # Give prediction predictions = model.predict(data) prediction = predictions[0] # Report results. result = {} result['predict'] = {g: float(prediction[i]) for g, i in groups.items()} # Get details about the deployed model if possible. metadata_path = 'valohai-metadata.json' if os.path.isfile(metadata_path): with open(metadata_path) as f: try: deployment_metadata = json.load(f) result['deployment'] = deployment_metadata except json.JSONDecodeError: # Could not read the deployment metadata, ignore it pass response = create_response(result, 200) return response(environ, start_response) predict_wsgi = DebuggedApplication(predict_wsgi) if __name__ == '__main__': from werkzeug.serving import run_simple run_simple('localhost', 8000, predict_wsgi)
from flask import Flask import os from flask_debugtoolbar import DebugToolbarExtension from werkzeug.debug import DebuggedApplication app = Flask('application') if os.getenv('FLASK_CONF') == 'DEV': # Development settings app.config.from_object('application.settings.Development') # Flask-DebugToolbar toolbar = DebugToolbarExtension(app) # Google app engine mini profiler # https://github.com/kamens/gae_mini_profiler app.wsgi_app = DebuggedApplication(app.wsgi_app, evalex=True) from gae_mini_profiler import profiler, templatetags @app.context_processor def inject_profiler(): return dict(profiler_includes=templatetags.profiler_includes()) app.wsgi_app = profiler.ProfilerWSGIMiddleware(app.wsgi_app) elif os.getenv('FLASK_CONF') == 'TEST': app.config.from_object('application.settings.Testing') else: app.config.from_object('application.settings.Production')
from flask import Flask, render_template, request from werkzeug.debug import DebuggedApplication from marvel_characters import character_info, character_images app = Flask(__name__) app.wsgi_app = DebuggedApplication(app.wsgi_app, True) @app.route('/') def index(): heroes = character_images.keys() return render_template('index.html', heroes=heroes, character_info=character_info, character_images=character_images) @app.route('/question') def show_question(): heroes = character_images.keys() return render_template('question.html', heroes=heroes, character_info=character_info, character_images=character_images) if __name__ == "__main__": app.run(debug=True)
})) def on_close(self, reason): print("Connection closed!") @flask_app.route('/index.html') def index(): return render_template('index.html') server = WebSocketServer( ('0.0.0.0', 8000), Resource([ ('^/chat', ChatApplication), ('^/.*', DebuggedApplication(flask_app)) ]), debug=False, ) for client in server.clients.values(): client.ws.send(("text2")) server.serve_forever() try: db = pymysql.connect(DBHOST, DBUSER, DBPASS, DBNAME, charset='utf8') print("连接上了") cur = db.cursor() cur.execute('Insert into `danmus` values("%s","%s","%s")', args) print("数据插入成功")
def __init__(self, *args, **kwargs): print "init DebuggedApplication" from werkzeug.debug import DebuggedApplication self.debug_app = DebuggedApplication(self.debug_wsgi_app, evalex=True) self.debug_container = tornado.wsgi.WSGIContainer(self.debug_app) super(DebugApplication, self).__init__(*args, **kwargs)
logging.info("Instance {} does not exist".format(instance_id)) return True state = task["lastStatus"] if state not in ("RUNNING", "PROVISIONING", "PENDING"): logging.info("Instance {} is {}".format(instance_id, state)) return True return False def urlencode(s): """str -> b64 str""" if type(s) == str: s = s.encode() return b64encode(s).decode() def urldecode(s): """b64 str -> str""" return b64decode(s).decode() if __name__ == "__main__": logging.getLogger(__name__).setLevel(logging.INFO) WebSocketServer( ("", port), Resource([("^/.*", MephistoRouter), ("^/.*", DebuggedApplication(app))]), debug=False, ).serve_forever()
""" Preview for Seamus page """ context = make_context() # Read the books JSON into the page. with open('data/songs.json', 'rb') as readfile: songs_data = json.load(readfile) for song in songs_data: song['song_art'] = song['song_art'].replace('-s500', '-s200') songs = sorted(songs_data, key=lambda k: (k['artist'].lower()[4:] if k['artist'].lower().startswith('the ') else k['artist'].lower())) context['songs'] = songs return render_template('seamus-preview.html', **context) app.register_blueprint(static.static) app.register_blueprint(oauth.oauth) # 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__': print 'This command has been removed! Please run "fab app" instead!'
from werkzeug.debug import DebuggedApplication import hello_world app = DebuggedApplication(hello_world.application, evalex=True)
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", "rein.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
import logging import os import sys from werkzeug.debug import DebuggedApplication logging.basicConfig( level=logging.DEBUG, format="%(levelname)s: %(asctime)s {%(filename)s:%(lineno)d}: %(message)s " ) (file_path, fname) = os.path.split(__file__) app_path = os.path.dirname(file_path) os.chdir(app_path) logging.info("My path is " + app_path) sys.path.insert(0, app_path) sys.stdout = sys.stderr from jyotisha.rest_api import run application = DebuggedApplication(run.app, True)
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_thread() monkey.patch_time() def run_server(): self.wsgi_server.serve_forever() run_with_reloader(run_server, extra_files=extra_files) else: self.wsgi_server.serve_forever()
def __call__(self, environ, start_response): app = DebuggedApplication(app=self._wsgiapp) return app(environ, start_response)
def inner_run(self, options): try: from werkzeug import run_simple from werkzeug.debug import DebuggedApplication from werkzeug.serving import WSGIRequestHandler as _WSGIRequestHandler # 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!") pass except ImportError: raise CommandError("Werkzeug is required to use runserver_plus. Please visit http://werkzeug.pocoo.org/ or install via pip. (pip install Werkzeug)") 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 = (sys.platform == 'win32') and 'CTRL-BREAK' or 'CONTROL-C' 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") if hasattr(self, 'check'): self.check(display_num_errors=self.show_startup_messages) else: self.validate(display_num_errors=self.show_startup_messages) try: self.check_migrations() except ImproperlyConfigured: pass handler = get_internal_wsgi_application() 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"]: """ OpenSSL is needed for SSL support. This will make flakes8 throw warning since OpenSSL is not used directly, alas, this is the only way to show meaningful error messages. See: http://lucumr.pocoo.org/2011/9/21/python-import-blackbox/ for more information on python imports. """ try: import OpenSSL # NOQA except ImportError: 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: from werkzeug.serving import make_ssl_devcert 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: import webbrowser 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, )
Handles downloading of the figure in various file formats. """ manager = Manager mimetypes = { 'ps': 'application/postscript', 'eps': 'application/postscript', 'pdf': 'application/pdf', 'svg': 'image/svg+xml', 'png': 'image/png', 'jpeg': 'image/jpeg', 'tif': 'image/tiff', 'emf': 'application/emf' } buff = io.BytesIO() manager.canvas.print_figure(buff, format=fmt) resp = make_response(buff.getvalue(), 200) resp.headers['Content-Type'] = mimetypes.get(fmt, 'binary') return resp if __name__ == '__main__': server = WebSocketServer(('0.0.0.0', 7777), Resource([('^/ws', WebSocket_App), ('^/.*', DebuggedApplication(app))]), debug=False) print "started at 0.0.0.0:7777" server.serve_forever()