def set_debug_mode(app): from werkzeug.debug import DebuggedApplication app = DebuggedApplication(app) # profiling if settings.debug_level() == settings.DEBUG_AND_PROFILE: from werkzeug.middleware.profiler import ProfilerMiddleware app = ProfilerMiddleware(application, sys.stdout) profile_log_path = settings.get('global', 'profile_log_path') if profile_log_path: app = ProfilerMiddleware(app, open(profile_log_path), 'w') return app
def configure_api(flask_app=api_classes.App, flask_api=api_classes.AiidaApi, **kwargs): """ Configures a flask.Flask instance and returns it. :param flask_app: Class inheriting from flask app class :type flask_app: :py:class:`flask.Flask` :param flask_api: flask_restful API class to be used to wrap the app :type flask_api: :py:class:`flask_restful.Api` :param config: directory containing the config.py configuration file :param catch_internal_server: If true, catch and print internal server errors with full python traceback. Useful during app development. :param wsgi_profile: use WSGI profiler middleware for finding bottlenecks in the web application :param posting: Whether or not to include POST-enabled endpoints (currently only `/querybuilder`). :returns: Flask RESTful API :rtype: :py:class:`flask_restful.Api` """ # Unpack parameters config = kwargs.pop('config', CLI_DEFAULTS['CONFIG_DIR']) catch_internal_server = kwargs.pop('catch_internal_server', CLI_DEFAULTS['CATCH_INTERNAL_SERVER']) wsgi_profile = kwargs.pop('wsgi_profile', CLI_DEFAULTS['WSGI_PROFILE']) posting = kwargs.pop('posting', CLI_DEFAULTS['POSTING']) if kwargs: raise ValueError(f'Unknown keyword arguments: {kwargs}') # Import the configuration file spec = importlib.util.spec_from_file_location( os.path.join(config, 'config'), os.path.join(config, 'config.py')) config_module = importlib.util.module_from_spec(spec) spec.loader.exec_module(config_module) # Instantiate an app app = flask_app(__name__, catch_internal_server=catch_internal_server) # Apply default configuration app.config.update(**config_module.APP_CONFIG) # Allow cross-origin resource sharing cors_prefix = r'{}/*'.format(config_module.API_CONFIG['PREFIX']) CORS(app, resources={cors_prefix: {'origins': '*'}}) # Configure the serializer if config_module.SERIALIZER_CONFIG: from aiida.restapi.common.utils import CustomJSONEncoder app.json_encoder = CustomJSONEncoder # Set up WSGI profiler if requested if wsgi_profile: from werkzeug.middleware.profiler import ProfilerMiddleware app.config['PROFILE'] = True app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30]) # Instantiate and return a Flask RESTful API by associating its app return flask_api(app, posting=posting, **config_module.API_CONFIG)
def main(): info("main: ...done.") from .utils.config import Configuration flask_options = Configuration().get_flask() if "profiler" in flask_options and flask_options["profiler"]: info("Profiling!") from werkzeug.middleware.profiler import ProfilerMiddleware app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30], sort_by=("cumulative", "time", "calls")) del flask_options["profiler"] if "COCALC_PROJECT_ID" in os.environ: from .utils.cocalcwrap import CocalcWrap # we must accept external connections flask_options["host"] = "0.0.0.0" app.wsgi_app = CocalcWrap(app.wsgi_app) stars = "\n" + "*" * 80 info(stars + "\n\033[1mCocalc\033[0m environment detected!\n" + "Visit" + "\n \033[1m https://cocalc.com" + app.wsgi_app.app_root + " \033[0m" + "\nto access this LMFDB instance" + stars) set_running() app.run(**flask_options)
def profile(length, profile_dir): """在请求分析器的监视下运行应用.""" from werkzeug.middleware.profiler import ProfilerMiddleware app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=(length, ), profile_dir=profile_dir) app.run()
def enable_profiling(application): from werkzeug.middleware.profiler import ProfilerMiddleware application.config["PROFILE"] = True application.wsgi_app = ProfilerMiddleware( application.wsgi_app, sort_by=("cumulative", "name"), restrictions=[60] )
def main(args=None): global db if not args: parser = argparse.ArgumentParser(add_help=True, description='ROADrecon GUI', formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('-d', '--database', action='store', help='Database file. Can be the local database name for SQLite, or an SQLAlchemy compatible URL such as postgresql+psycopg2://dirkjan@/roadtools', default='roadrecon.db') parser.add_argument('--debug', action='store_true', help='Enable flask debug') parser.add_argument('--profile', action='store_true', help='Enable flask profiler') args = parser.parse_args() if not ':/' in args.database: if args.database[0] != '/': app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(os.getcwd(), args.database) else: app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + args.database else: app.config['SQLALCHEMY_DATABASE_URI'] = args.database db = SQLAlchemy(app) if args.profile: from werkzeug.middleware.profiler import ProfilerMiddleware app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[5]) app.run(debug=args.debug)
def profile(length, profile_dir): """start the application under the code profiler.""" from werkzeug.middleware.profiler import ProfilerMiddleware app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[length], profile_dir=profile_dir) if __name__ == "__main__": app.run(debug=False)
def profile(length, profile_dir): """Start the application under the code profiler.""" from werkzeug.middleware.profiler import ProfilerMiddleware app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[length], profile_dir=profile_dir) run_simple('127.0.0.1', 5000, app) # app.run(debug=False)
def profile(length, profile_dir): """Start the application under the code profiler.""" from werkzeug.middleware.profiler import ProfilerMiddleware app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[length], profile_dir=profile_dir) app.run()
def create_app(config={}): configure_logging(level=logging.DEBUG) app = Flask("aleph") app.config.from_object(settings) app.config.update(config) if "postgres" not in settings.DATABASE_URI: raise RuntimeError("aleph database must be PostgreSQL!") app.config.update({ "SQLALCHEMY_DATABASE_URI": settings.DATABASE_URI, "FLASK_SKIP_DOTENV": True, "FLASK_DEBUG": settings.DEBUG, "BABEL_DOMAIN": "aleph", "PROFILE": settings.PROFILE, }) if settings.PROFILE: app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30]) migrate.init_app(app, db, directory=settings.ALEMBIC_DIR) configure_oauth(app, cache=get_cache()) mail.init_app(app) db.init_app(app) babel.init_app(app) CORS( app, resources=r"/api/*", origins=settings.CORS_ORIGINS, supports_credentials=True, ) feature_policy = { "accelerometer": NONE, "camera": NONE, "geolocation": NONE, "gyroscope": NONE, "magnetometer": NONE, "microphone": NONE, "payment": NONE, "usb": NONE, } talisman.init_app( app, force_https=settings.FORCE_HTTPS, strict_transport_security=settings.FORCE_HTTPS, feature_policy=feature_policy, content_security_policy=settings.CONTENT_POLICY, ) from aleph.views import mount_app_blueprints mount_app_blueprints(app) # This executes all registered init-time plugins so that other # applications can register their behaviour. for plugin in get_extensions("aleph.init"): plugin(app=app) return app
def main( filenames: Tuple[str], port: int, host: str, prefix: str, incognito: bool, debug: bool, profile: bool, profile_dir: str, ) -> None: # pragma: no cover """Start Fava for FILENAMES on http://<host>:<port>. If the `BEANCOUNT_FILE` environment variable is set, Fava will use the files (space-delimited) specified there in addition to FILENAMES. Note you can also specify command-line options via environment variables. For example, `--host=0.0.0.0` is equivalent to setting the environment variable `FAVA_HOST=0.0.0.0`. """ if profile: debug = True env_filename = os.environ.get("BEANCOUNT_FILE") all_filenames = (filenames + tuple(env_filename.split()) if env_filename else filenames) if not all_filenames: raise click.UsageError("No file specified") app.config["BEANCOUNT_FILES"] = all_filenames app.config["INCOGNITO"] = incognito if prefix: app.wsgi_app = DispatcherMiddleware( # type: ignore simple_wsgi, {prefix: app.wsgi_app}) if not debug: server = Server((host, port), app) print(f"Running Fava on http://{host}:{port}") server.safe_start() else: if profile: app.config["PROFILE"] = True app.wsgi_app = ProfilerMiddleware( # type: ignore app.wsgi_app, restrictions=(30, ), profile_dir=profile_dir if profile_dir else None, ) app.jinja_env.auto_reload = True try: app.run(host, port, debug) except OSError as error: if error.errno == errno.EADDRINUSE: raise click.UsageError( "Can not start webserver because the port is already in " "use. Please choose another port with the '-p' option.") raise
def profiler() -> None: from werkzeug.middleware.profiler import ProfilerMiddleware from decksite import main main.APP.config['PROFILE'] = True main.APP.wsgi_app = ProfilerMiddleware(main.APP.wsgi_app, restrictions=[30]) # type: ignore main.init()
def setup_profiling(application): profiling_dir = "profiling" if os.path.exists(profiling_dir): shutil.rmtree(profiling_dir) os.makedirs(profiling_dir) application.wsgi_app = ProfilerMiddleware(application.wsgi_app, profile_dir=profiling_dir) application.debug = True
def profile(length=25, profile_dir=None): """ 使用python manage.py profile启动程序后,终端会显示每条请求的分析数据,其中包含运行最慢的25个函数 :param length: 函数数量 :param profile_dir: 保存目录 """ from werkzeug.middleware.profiler import ProfilerMiddleware app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[length], profile_dir=profile_dir) app.run()
def run(): app = Flask(__name__.split('.')[0]) app.register_blueprint(api.blueprint) app.config['PROFILE'] = True app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[10]) app.model = models.AlexNet() app.run(host='0.0.0.0', debug=True, port=5067, threaded=False, use_reloader=True)
def serve(ip_address='0.0.0.0', port=8000, profile=False, no_reload=False, no_threading=False, site=None, sites_path='.'): global application, _site, _sites_path _site = site _sites_path = sites_path from werkzeug.serving import run_simple if profile: application = ProfilerMiddleware(application, sort_by=('cumtime', 'calls')) if not os.environ.get('NO_STATICS'): application = SharedDataMiddleware(application, { str('/assets'): str(os.path.join(sites_path, 'assets')) }) application = StaticDataMiddleware(application, { str('/files'): str(os.path.abspath(sites_path)) }) application.debug = True application.config = { 'SERVER_NAME': 'localhost:8000' } in_test_env = os.environ.get('CI') if in_test_env: log = logging.getLogger('werkzeug') log.setLevel(logging.ERROR) # pcon - Make this a variable, so you can change between 0.0.0.0, or 127.0.0.1, or whatever you want. run_simple(ip_address, int(port), application, use_reloader=False if in_test_env else not no_reload, use_debugger=not in_test_env, use_evalex=not in_test_env, threaded=not no_threading)
def configure(cls, app: Flask): profile_dir = cls.create_profile_dir() if profile_dir is None: # We are not configured return from werkzeug.middleware.profiler import ProfilerMiddleware filename = cls.FILENAME_TEMPLATE + ".prof" app.config["PROFILE"] = True app.wsgi_app = ProfilerMiddleware(app.wsgi_app, profile_dir=str(profile_dir), filename_format=filename)
def install_middlewares(app, settings): "Install a set of middlewares defined in the ini file on the given app." # Setup new-relic. if settings.get("newrelic_config"): ini_file = settings["newrelic_config"] env = settings["newrelic_env"] newrelic.agent.initialize(ini_file, env) app = newrelic.agent.WSGIApplicationWrapper(app) # Adds the Werkzeug profiler. if asbool(settings.get("profiler_enabled")): profile_dir = settings["profiler_dir"] app = ProfilerMiddleware(app, profile_dir=profile_dir, restrictions=("*kinto.core*")) return app
def profile(length=25, profile_dir=None): """ This module provides a simple WSGI profiler middleware for finding bottlenecks in web application. It uses the profile or cProfile module to do the profiling and writes the stats to the stream provided see: http://werkzeug.pocoo.org/docs/0.9/contrib/profiler/ """ from werkzeug.middleware.profiler import ProfilerMiddleware app.config["PROFILE"] = True app.wsgi_app = ProfilerMiddleware( app.wsgi_app, restrictions=[length], profile_dir=profile_dir ) app.run()
def run() -> None: if len(sys.argv) < 2: print('No entry point specified.') sys.exit(1) if sys.argv[1] == 'discordbot': from discordbot import bot bot.init() elif sys.argv[1] == 'decksite': from decksite import main main.init() elif sys.argv[1] == 'decksite-profiler': from werkzeug.middleware.profiler import ProfilerMiddleware from decksite import main main.APP.config['PROFILE'] = True main.APP.wsgi_app = ProfilerMiddleware(main.APP.wsgi_app, restrictions=[30 ]) # type: ignore main.init() elif 'price_grabber' in sys.argv: from price_grabber import price_grabber price_grabber.run() elif 'srv_price' in sys.argv: from price_grabber import srv_prices srv_prices.init() elif sys.argv[1] in ['scraper', 'scrapers', 'maintenance']: task(sys.argv) elif sys.argv[1] == 'tests': print('Call `dev.py tests` instead.') sys.exit(1) elif sys.argv[1] == 'rotation': from rotation_script import rotation_script rotation_script.run() elif sys.argv[1] == 'logsite': import logsite logsite.APP.run(host='0.0.0.0', port=5001, debug=True) elif sys.argv[1] == 'github_tools': import github_tools github_tools.APP.run(host='0.0.0.0', port=5002, debug=True) else: try: m = importlib.import_module( '{module}.main'.format(module=sys.argv[1])) m.run() # type: ignore except ImportError: print("I don't recognize `{0}`".format(sys.argv[1])) sys.exit(1) sys.exit(0)
def _set_linter_and_profiler(self): if self._app.config["WSGI_WERKZEUG_PROFILER_ENABLED"]: file = self._app.config["WSGI_WERKZEUG_PROFILER_FILE"] self._app.wsgi_app = ProfilerMiddleware( self._app.wsgi_app, # pylint: disable=consider-using-with stream=open(file, "w", encoding="utf-8") if file else sys.stdout, restrictions=self._app. config["WSGI_WERKZEUG_PROFILER_RESTRICTION"], ) self._app.logger.debug("Registered: '%s'", ProfilerMiddleware.__name__) if self._app.config["WSGI_WERKZEUG_LINT_ENABLED"]: self._app.wsgi_app = LintMiddleware(self._app.wsgi_app) self._app.logger.debug("Registered: '%s'", LintMiddleware.__name__)
def main(): if hubzero: app.run_server(port=8000, host='0.0.0.0') elif in_jupyterlab: viewer.show(app) else: if flask_debug: print(join(dirname(dirname(realpath(__file__))), 'debug')) app.server.config['PROFILE'] = True app.server.wsgi_app = ProfilerMiddleware( app.server.wsgi_app, restrictions=[30], profile_dir=join(dirname(dirname(realpath(__file__))), 'debug')) app.run_server(debug=False) else: app.run_server(debug=True)
def configured_app(import_name, debug=False, config_module=None, profile=False, proxy_fix=False, **flask_kwargs): """instantiate a Flask app for details see https://flask.palletsprojects.com/en/1.1.x/api/#flask.Flask * import_name: the name of your app package * debug: put flask app into debug mode * config_module: python module path to load config from * profile: bool. activate flask.contrib.profiler.ProfilerMiddleware * proxy_fix: bool. activate werkzeug.contrib.fixers.ProxyFix Environment variables supported: FLASKAPP_CONFIG envvar module, values will override those in config_module """ app = Flask(import_name, **flask_kwargs) app.secret_key = os.urandom(24) # stop noisy warnings app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.debug = debug if app.debug: app.config['SQLALCHEMY_ECHO'] = True if config_module: app.config.from_object(config_module) if os.getenv("FLASKAPP_CONFIG", False): # do not fail silently if configured file cannot be loaded app.config.from_envvar("FLASKAPP_CONFIG", silent=False) # enable profiling? if profile: pstat_dir = tempfile.mkdtemp() log.debug("PROFILER writing pstat files to {}".format(pstat_dir)) app.wsgi_app = ProfilerMiddleware(app.wsgi_app, profile_dir=pstat_dir) @app.route('/') def index(): return jsonify({"{}-server".format(import_name): "ok"}) return app
def create_app(test_config=None): """ basic Flask app setup. Creates the instance folder if not existing """ app = Flask(__name__, instance_relative_config=True, static_folder="../static", static_url_path="") app.config.from_mapping( SECRET_KEY='dev', PROFILE=False, DATABASE=os.path.join(app.instance_path, 'labyrinth.sqlite'), LIBRARY_PATH=os.path.join(app.instance_path, 'lib'), ) if test_config is None: app.config.from_pyfile('config.py', silent=True) else: app.config.from_mapping(test_config) if app.config["PROFILE"]: app.wsgi_app = ProfilerMiddleware(app.wsgi_app, profile_dir=os.path.join(app.instance_path), stream=None) try: os.makedirs(app.instance_path) except OSError: pass from . import api app.register_blueprint(api.API) from . import game_management app.register_blueprint(game_management.GAME_MANAGEMENT) from labyrinth.database import DatabaseGateway app.before_first_request(lambda: DatabaseGateway.init_database()) app.teardown_request(lambda exc: DatabaseGateway.close_database()) mimetypes.add_type('application/wasm', '.wasm') @app.route('/') def index(): """ Serves the 'static' part, i.e. the Vue application """ return app.send_static_file("index.html") return app
def main(): info("main: ...done.") from lmfdb.utils.config import Configuration flask_options = Configuration().get_flask() if "profiler" in flask_options and flask_options["profiler"]: info("Profiling!") from werkzeug.middleware.profiler import ProfilerMiddleware app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30], sort_by=("cumulative", "time", "calls")) del flask_options["profiler"] #/from werkzeug.middleware.profiler import ProfilerMiddleware #/app.wsgi_app = ProfilerMiddleware( #/ app.wsgi_app, restrictions=[30], sort_by=("cumulative", "time", "calls") #/ ) set_running() app.run(**flask_options)
def local_run(): config = dict( debug=True, host='127.0.0.1', port=5000, ) import os d = "ignoreme/profile" if not os.path.exists(d): os.mkdir(d) from werkzeug.middleware.profiler import ProfilerMiddleware null = open(os.devnull, "w") app.wsgi_app = ProfilerMiddleware( app.wsgi_app, stream=null, profile_dir=d, filename_format="{time}.{method}.{path}.{elapsed:06f}ms.prof", ) print(app.url_map) app.run(**config)
def serve(port=8000, profile=False, no_reload=False, no_threading=False, site=None, sites_path="."): global application, _site, _sites_path _site = site _sites_path = sites_path from werkzeug.serving import run_simple patch_werkzeug_reloader() if profile: application = ProfilerMiddleware(application, sort_by=("cumtime", "calls")) if not os.environ.get("NO_STATICS"): application = SharedDataMiddleware( application, {str("/assets"): str(os.path.join(sites_path, "assets"))}) application = StaticDataMiddleware( application, {str("/files"): str(os.path.abspath(sites_path))}) application.debug = True application.config = {"SERVER_NAME": "localhost:8000"} log = logging.getLogger("werkzeug") log.propagate = False in_test_env = os.environ.get("CI") if in_test_env: log.setLevel(logging.ERROR) run_simple( "0.0.0.0", int(port), application, use_reloader=False if in_test_env else not no_reload, use_debugger=not in_test_env, use_evalex=not in_test_env, threaded=not no_threading, )
def create_app(): global run_once app = Flask(__name__) # app.sockets = Sockets(app) #app.config['DEBUG'] = True app.config['SECRET_KEY'] = 'super-secret' db.init_app(app) auth.init_app(app) api.init_app(app, db.db) @app.after_request def clear_server_header(response): response.headers['Server'] = '' # del response.headers['Set-Cookie'] # response.set_cookie('session', '', expires=0, httponly=True) return response if os.environ.get('FLASK_PROFILE', '') == '1': from werkzeug.middleware.profiler import ProfilerMiddleware app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[10]) return app
def serve(port=8000, profile=False, no_reload=False, no_threading=False, site=None, sites_path='.'): global application, _site, _sites_path _site = site _sites_path = sites_path from werkzeug.serving import run_simple patch_werkzeug_reloader() if profile or os.environ.get('USE_PROFILER'): application = ProfilerMiddleware(application, sort_by=('cumtime', 'calls')) if not os.environ.get('NO_STATICS'): application = SharedDataMiddleware( application, {str('/assets'): str(os.path.join(sites_path, 'assets'))}) application = StaticDataMiddleware( application, {str('/files'): str(os.path.abspath(sites_path))}) application.debug = True application.config = {'SERVER_NAME': 'localhost:8000'} log = logging.getLogger('werkzeug') log.propagate = False in_test_env = os.environ.get('CI') if in_test_env: log.setLevel(logging.ERROR) run_simple('0.0.0.0', int(port), application, use_reloader=False if in_test_env else not no_reload, use_debugger=not in_test_env, use_evalex=not in_test_env, threaded=not no_threading)
$ python run.py python run.py {"message": null, "environment": "dev", "event": "Opinions API started"... {"message": " * Running on http://localhost:8000/ (Press CTRL+C to quit)"... """ from werkzeug.middleware.profiler import ProfilerMiddleware from werkzeug.serving import run_simple from opinions import core app = core.create_app("opinions") if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument("--profile", action='store_true') parser.add_argument("--count-restriction") args = parser.parse_args() count = 30 if args.count_restriction is not None: try: count = int(args.count_restriction) except TypeError: pass if args.profile: app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[count]) # Run Flask app run_simple('localhost', 8000, app, use_reloader=True)