def __init__(self, address, configuration=None, assembly=None): super(Runtime, self).__init__(configuration, assembly) self.deploy() self.startup() self.dispatcher = MountDispatcher() for unit in self.assembly.collate(Mount): self.dispatcher.mount(unit) wsgi = self.configuration.get('wsgi') if wsgi and 'static-map' in wsgi: map = wsgi['static-map'].split('=') self.dispatcher = SharedDataMiddleware(self.dispatcher, { map[0]: os.path.abspath(map[1]) }, cache=False) self.server = WsgiServer(address, self.dispatcher) self.server.serve()
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): 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(): # Override here 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() from werkzeug._reloader import run_with_reloader run_with_reloader(inner, extra_files, reloader_interval, reloader_type) else: inner()
def create_app(with_static=True): app = MyApp() if with_static: app.wsgi_app = SharedDataMiddleware( app.wsgi_app, {'/static': os.path.join(os.path.dirname(__file__), 'static')}) fs_session_store = FilesystemSessionStore() app.wsgi_app = WerkzeugCAS.fromConfig( app.wsgi_app, fs_session_store, ignored_callback=ignored_callback, filename='test.cfg') return app
def create_application(from_file): if from_file: work_dir = os.path.dirname(os.path.abspath(from_file)) else: work_dir = os.getcwd() os.chdir(work_dir) static_files = {'/static': os.path.join(work_dir, 'static')} jam.context = Local() local_manager = LocalManager([jam.context]) application = App(work_dir) application = SharedDataMiddleware(application, static_files) application = local_manager.make_middleware(application) return application
def create_ads_app(with_static=True): """ Creates ads app. :param with_static: (bool) :return: (AdsAppWithViews obj) """ app = AdsAppWithViews() if with_static: app.wsgi_app = SharedDataMiddleware( app.wsgi_app, { '/static': os.path.join(os.path.dirname(__file__), 'werkzeug_ads_app/static') }) return app
def WSGIHandler(self): """Returns GRR's WSGI handler.""" sdm = SharedDataMiddleware(self, { "/": config.CONFIG["AdminUI.document_root"], }) # Use DispatcherMiddleware to make sure that SharedDataMiddleware is not # used at all if the URL path doesn't start with "/static". This is a # workaround for cases when unicode URLs are used on systems with # non-unicode filesystems (as detected by Werkzeug). In this case # SharedDataMiddleware may fail early while trying to convert the # URL into the file path and not dispatch the call further to our own # WSGI handler. return DispatcherMiddleware(self, { "/static": sdm, })
def create_app(redis_host=('localhost'), redis_port=6379, with_static=True): """ Creates an instance of our app, passes configuration and can add middleware. :param redis_host: :param redis_port: :param with_static: :return: """ app = Shortly({'redis_host': redis_host, 'redis_port': redis_port}) if with_static: app.wsgi_app = SharedDataMiddleware( app.wsgi_app, {'/static': os.path.join(os.path.dirname(__file__), 'static')}) return app
def create_app(): app = flask.Flask(__name__, instance_relative_config=True) app.register_blueprint(webpages) app.config.update(DEFAULT_CONFIG) app.config.from_pyfile('settings.py', silent=True) dbsession.initialize_app(app) if 'STATIC_URL_MAP' in app.config: from werkzeug.wsgi import SharedDataMiddleware app.wsgi_app = SharedDataMiddleware(app.wsgi_app, app.config['STATIC_URL_MAP']) app.config['OSM_API_URL'] = app.config['OSM_API_URL'].rstrip('/') osm.initialize_app(app) return app
def __init__(self, hostname, port, name, landing_page): self.landing_page = landing_page try: module = importlib.import_module(name) static_path = os.path.dirname(module.__file__) + '/static' except ImportError: static_path = os.path.join(os.getcwd(), 'static') self.dynamic_path = '/tmp/%s' % name if not os.path.exists(self.dynamic_path): os.mkdir(self.dynamic_path) application = SharedDataMiddleware(self.application, {'/': static_path}) self.srv = make_server(hostname, port, application)
def create_app(watchdog, verbose=False, with_static=True, with_debugger=True, use_evalex=True): from werkzeug.wsgi import SharedDataMiddleware from werkzeug.debug import DebuggedApplication app = CDPedia(watchdog, verbose=verbose) if with_static: paths = [("/" + path, os.path.join(config.DIR_ASSETS, path)) for path in config.ALL_ASSETS] paths += [('/cmp', app.tmpdir)] app.wsgi_app = SharedDataMiddleware(app.wsgi_app, dict(paths)) if with_debugger: app.wsgi_app = DebuggedApplication(app.wsgi_app, use_evalex) return app
def create_app(): """创建Flask app""" app = Flask(__name__) config = load_config() app.config.from_object(config) # Proxy fix app.wsgi_app = ProxyFix(app.wsgi_app) # CSRF protect CsrfProtect(app) if app.debug: DebugToolbarExtension(app) # serve static files during development app.wsgi_app = SharedDataMiddleware(app.wsgi_app, { '/uploads': os.path.join(app.config.get('PROJECT_PATH'), 'uploads') }) else: app.logger.addHandler(logging.StreamHandler()) app.logger.setLevel(logging.ERROR) if app.config.get('SENTRY_DSN'): from .utils.sentry import sentry sentry.init_app(app, dsn=app.config.get('SENTRY_DSN')) # 注册组件 register_db(app) register_routes(app) register_jinja(app) register_error_handle(app) register_uploadsets(app) # before every request @app.before_request def before_request(): ban_ips = app.config.get('BAN_IPS') if request.remote_addr in ban_ips: abort(404) g.user = get_current_user() return app
def create_app(config=None): """ >>> app = create_app() 2018... """ app = Flask(__name__) if config is None: mode = os.environ.get("GENIUS_MODE") config_file = 'config.py' if mode == 'deploy': config_file = 'deploy_config.py' app.config.from_pyfile(config_file) jinja_config = {k[3:].lower(): v for k, v in app.config.items() if k.lower().startswith('j2_')} jinja_config.update(app.jinja_options) app.jinja_options = ImmutableDict(**jinja_config) configure_app(app) db.init_db(app) bp.init_app(app) # register plugins finally ext.init_app(app) @app.route('/jerry_lend_books') def _(): jerry = User.query.first() simon = User.query.filter_by(User.id != jerry.id) book = Book.query.first() jerry.post_book(book) b_copy = BookOfUser.query.first() branch = Branch.query.first() rec = jerry.lend_book(branch=branch, book_copy=b_copy) if not rec: return make_response("Not Permitted..") return make_response(repr(rec).strip()) app.wsgi_app = SharedDataMiddleware( app.wsgi_app, { '/i': UPLOAD_DIR, '/static': STATIC_FILE_DIR } ) add_cli_interfaces(app) return app
def getWsgiAppStatic(): #Returns a Wsgi app, serving static content from the project 'app/' folder stringPathToThisModule = os.path.dirname(__file__) stringPathToStaticContent = os.path.join(stringPathToThisModule, 'app') stringPathToManagementStaticContent = os.path.join(stringPathToThisModule, 'management_app') #Map static content to one or more URI's within this Wsgi application. stringStaticInternalUriPrefix = '/' #Don't prepend any internal prefix dictInternalPrefixToPathMapping = { stringStaticInternalUriPrefix: stringPathToStaticContent, '/management': stringPathToManagementStaticContent } # instantiate a stand-alone Static content Wsgi app return SharedDataMiddleware( exceptionNullWsgiApp #make stand-alone , dictInternalPrefixToPathMapping)
def make_app(config=None): """ Factory function that creates a new `CoolmagicApplication` object. Optional WSGI middlewares should be applied here. """ config = config or {} app = CoolMagicApplication(config) # static stuff from werkzeug.wsgi import SharedDataMiddleware app = SharedDataMiddleware( app, {'/public': path.join(path.dirname(__file__), 'public')}) # clean up locals app = local_manager.make_middleware(app) return app
def __init__(self, listen_port, handlers, parameters, shard=0, listen_address=""): super(WebService, self).__init__(shard) static_files = parameters.pop('static_files', []) rpc_enabled = parameters.pop('rpc_enabled', False) rpc_auth = parameters.pop('rpc_auth', None) auth_middleware = parameters.pop('auth_middleware', None) is_proxy_used = parameters.pop('is_proxy_used', False) self.wsgi_app = tornado.wsgi.WSGIApplication(handlers, **parameters) self.wsgi_app.service = self for entry in static_files: self.wsgi_app = SharedDataMiddleware(self.wsgi_app, {"/static": entry}) if rpc_enabled: self.wsgi_app = DispatcherMiddleware( self.wsgi_app, {"/rpc": RPCMiddleware(self, rpc_auth)}) # Remove any authentication header that a user may try to fake. self.wsgi_app = HeaderRewriterFix( self.wsgi_app, remove_headers=[WebService.AUTHENTICATED_USER_HEADER]) if auth_middleware is not None: self.wsgi_app = auth_middleware(self.wsgi_app) # If is_proxy_used is set to True we'll use the content of the # X-Forwarded-For HTTP header (if provided) to determine the # client IP address, ignoring the one the request came from. # This allows to use the IP lock behind a proxy. Activate it # only if all requests come from a trusted source (if clients # were allowed to directlty communicate with the server they # could fake their IP and compromise the security of IP lock). if is_proxy_used: self.wsgi_app = ProxyFix(self.wsgi_app) self.web_server = WSGIServer((listen_address, listen_port), self.wsgi_app)
def create_app(): """Create Flask app.""" app = Flask(__name__) config = load_config() app.config.from_object(config) if not hasattr(app, 'production'): app.production = not app.debug and not app.testing # Proxy fix app.wsgi_app = ProxyFix(app.wsgi_app) # CSRF protect CsrfProtect(app) # Log errors to stderr in production mode if app.production: app.logger.addHandler(logging.StreamHandler()) app.logger.setLevel(logging.ERROR) # Enable Sentry if app.config.get('SENTRY_DSN'): from .utils.sentry import sentry sentry.init_app(app, dsn=app.config.get('SENTRY_DSN')) else: DebugToolbarExtension(app) # Serve static files during development app.wsgi_app = SharedDataMiddleware(app.wsgi_app, { '/uploads': os.path.join(app.config.get('PROJECT_PATH'), 'uploads') }) # Register components register_db(app) register_routes(app) register_jinja(app) register_assets(app) register_error_handle(app) register_uploadsets(app) register_hooks(app) return app
def run_app(app, ip='127.0.0.1', port=4242, use_debugger=True, use_reloader=True, threaded=True): app = SharedDataMiddleware(app, {'/': 'static'}) while True: try: run_simple(ip, port, app, use_debugger=use_debugger, use_reloader=use_reloader, threaded=threaded) break except (OSError, socket.error): port += 1
def devserver(extra_conf=None): """ Start a development server """ from werkzeug.wsgi import SharedDataMiddleware # Load the "example" conf root = app.root_path.split(os.path.dirname(__file__))[0] conf = os.path.join(root, 'backend', 'var', 'conf', 'fontana.conf') app.config.from_pyfile(conf) if extra_conf: app.config.from_pyfile(os.path.join(root, extra_conf)) # Serve the frontend files app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {'/': app.config['STATIC_DIR']}) # Setup a index.html redirect for convenience sake. app.route('/')(lambda: flask.redirect('index.html')) # Run the development server app.run(port=5001)
def paste_app_factory(global_config, **app_config): configs = app_config['config'].split() mediagoblin_config = None for config in configs: if os.path.exists(config) and os.access(config, os.R_OK): mediagoblin_config = config break if not mediagoblin_config: raise IOError("Usable mediagoblin config not found.") del app_config['config'] mgoblin_app = MediaGoblinApp(mediagoblin_config) mgoblin_app.call_backend = SharedDataMiddleware(mgoblin_app.call_backend, exports=app_config) mgoblin_app = hook_transform('wrap_wsgi', mgoblin_app) return mgoblin_app
def run_app(app, **kwargs): ip = kwargs.get("ip") port = kwargs.get("port") use_debugger = kwargs.get("use_debugger") use_reloader = kwargs.get("use_reloader") threaded = kwargs.get("threaded") html_dir = kwargs.get("html_dir") log.info("html_dir: {}".format(html_dir)) app = SharedDataMiddleware(app, html_dirs) while True: try: run_simple(ip, port, app, use_debugger=use_debugger, use_reloader=use_reloader, threaded=threaded) break except (OSError, socket.error): port += 1
def start(self): """ Start the server. """ plugins = voltron.plugin.pm.web_plugins self.app = DispatcherMiddleware( VoltronFlaskApp('voltron', template_folder='web/templates', static_folder='web/static', server=self), { "/view": SharedDataMiddleware( None, { '/{}'.format(n): os.path.join(p._dir, 'static') for (n, p) in six.iteritems(plugins) }), "/ui": ui_app }) def run_listener(name, cls, arg): log.debug("Starting listener for {} socket on {}".format( name, str(arg))) s = cls(*arg) t = threading.Thread(target=s.serve_forever) t.start() self.threads.append(t) self.listeners.append(s) if voltron.config.server.listen.tcp: run_listener('tcp', ThreadedVoltronWSGIServer, list(voltron.config.server.listen.tcp) + [self.app]) if voltron.config.server.listen.domain: path = os.path.expanduser(str(voltron.config.server.listen.domain)) try: os.unlink(path) except: pass run_listener('domain', ThreadedUnixWSGIServer, [path, self.app]) self.is_running = True
def create(): config = Config() app = QlessPyapi(config) if config['ui']: app.wsgi_app = DispatcherMiddleware( app.wsgi_app, { '/api': app.wsgi_app, '/app': SharedDataMiddleware(redirect('/app/index.html'), { '/': path.join(path.dirname(__file__), 'qless-ui', 'app') }), '/': redirect('/app/index.html') }) return app, config
def _create_app(self): app = Flask(__name__) app.debug = self.conf.FLASK_DEBUG if not self.conf.STATIC_RESOURCE: raise Exception('STATIC_RESOURCE setting not configured.') if not self.conf.TEMPLATE_RESOURCE: raise Exception('TEMPLATE_RESOURCE setting not configured.') app.wsgi_app = SharedDataMiddleware(app.wsgi_app, { '/': self.conf.STATIC_RESOURCE }) if type(self.conf.TEMPLATE_RESOURCE) == tuple: # package, not filepath app.jinja_loader = PackageLoader(*self.conf.TEMPLATE_RESOURCE) else: app.jinja_loader = FileSystemLoader(self.conf.TEMPLATE_RESOURCE) if self.conf.ALLOW_DEFERREDS: self._enable_deferreds(app) return app
def __init__(self, package_name): print("Flask __init__ start!") self.debug = False # 调试模式开关 # 注意: # - 这个参数,不是随便乱给的 # - 要跟实际的 项目工程目录名对应,否则无法找到对应的工程 self.package_name = package_name # 注意: # - 调用前面定义的 全局私有方法 # - 依赖前面的传入参数, 通过该参数, 获取 项目工程源码根目录. self.root_path = _get_package_path(self.package_name) # 获取项目根目录 self.view_functions = {} # 视图函数集 self.error_handlers = {} # 出错处理 self.before_request_funcs = [] # 预处理 self.after_request_funcs = [] # 结束清理 self.template_context_processors = [_default_template_ctx_processor] # todo: 待深入 self.url_map = Map() # 关键依赖: werkzeug.routing.Map if self.static_path is not None: # 处理静态资源 # # todo: 待深入 关键依赖: werkzeug.routing.Rule self.url_map.add( Rule(self.static_path + '/<filename>', build_only=True, endpoint='static')) if pkg_resources is not None: target = (self.package_name, 'static') else: target = os.path.join(self.root_path, 'static') # # todo: 待深入, 关键依赖: werkzeug.SharedDataMiddleware self.wsgi_app = SharedDataMiddleware(self.wsgi_app, {self.static_path: target}) # todo: 待深入, jinja2 模板配置 self.jinja_env = Environment(loader=self.create_jinja_loader(), **self.jinja_options) self.jinja_env.globals.update( url_for=url_for, get_flashed_messages=get_flashed_messages) print("Flask __init__ end!")
def init_bp_modules(): """add blueprint modules. """ global app from ifanhao.comics.views import bp_comics app.register_blueprint(bp_comics, url_prefix='/comics') from ifanhao.views.avs import bp_avs app.register_blueprint(bp_avs, url_prefix='/a') from ifanhao.views.actors import bp_actors app.register_blueprint(bp_actors, url_prefix='/b') from ifanhao.sitemaps import bp_sitemap app.register_blueprint(bp_sitemap) # server media folder app.wsgi_app = SharedDataMiddleware( app.wsgi_app, {app.config.get('MEDIA_URL_PATH'): app.config.get('MEDIA_FOLDER')}) @app.route('/api/version', methods=['GET']) @smart_render() def version_handler(): from ifanhao import version return version() @app.route('/') @app.route('/index') @smart_render() def index(): pass @app.route('/robots.txt') @smart_render() def robots(): return send_file('./templates/robots.txt') @app.route('/favicon.ico') def favicon(): return redirect(url_for('static', filename='favicon.ico'))
def __init__(self, work_dir, load_task): mimetypes.add_type('text/cache-manifest', '.appcache') self.started = datetime.datetime.now() self.work_dir = work_dir self.state = common.PROJECT_NONE self._load_lock = Lock() self.admin = None self.task = None self.privileges = None self._busy = 0 self.pid = os.getpid() self.jam_dir = os.path.realpath(os.path.dirname(jam.__file__)) self.jam_version = jam.version() self.__is_locked = 0 self.application_files = { '/': self.work_dir, '/jam/': self.jam_dir } self.fileserver = SharedDataMiddleware(None, self.application_files, cache_timeout=1) self.url_map = Map([ Rule('/', endpoint='root_file'), Rule('/<file_name>', endpoint='root_file'), Rule('/js/<file_name>', endpoint='file'), Rule('/css/<file_name>', endpoint='file'), Rule('/jam/js/<file_name>', endpoint='file'), Rule('/jam/js/ace/<file_name>', endpoint='file'), Rule('/jam/css/<file_name>', endpoint='file'), Rule('/jam/css/themes/<file_name>', endpoint='file'), Rule('/jam/img/<file_name>', endpoint='file'), Rule('/api', endpoint='api'), Rule('/upload', endpoint='upload') ]) self.admin = self.create_admin() with self.admin.lock('$creating_task'): self.admin.read_settings() self.max_content_length = self.admin.max_content_length self.build_id_prefix = '$buildID' self.save_build_id(); if load_task: self.get_task() self.check_migration()
def build_application(): config = { "core": { "build_secrets": os.environ["BUILD_SECRETS"], "freenode_verification": os.environ["FREENODE_VERIFICATION"], }, "s3": { "aws_access_key_id": os.environ["AWS_ACCESS_KEY_ID"], "aws_secret_access_key": os.environ["AWS_SECRET_ACCESS_KEY"], "bucket": "topaz-builds", }, "database": { "uri": os.environ["DATABASE_URL"], }, } app = Application(config, S3Storage) app = SharedDataMiddleware(app, { "/static/": os.path.join(os.path.dirname(__file__), os.pardir, "static"), }) return Sentry(app, Client(os.environ["SENTRY_DSN"]))
def create_application(from_file=None, load_task=False): if from_file: if os.path.isfile(from_file): work_dir = os.path.dirname(from_file) else: work_dir = from_file else: work_dir = os.getcwd() work_dir = os.path.realpath(work_dir) os.chdir(work_dir) static_files = { '/static': os.path.join(work_dir, 'static') } jam.context = Local() local_manager = LocalManager([jam.context]) application = App(work_dir, load_task) application = SharedDataMiddleware(application, static_files) application = local_manager.make_middleware(application) return application
def create_app(with_static=True): """ Initializes Controller (controller) and Forms (app) objects, pass controller to app to keep track of number of submissions per minute """ # Initiate a logger logger = logging.getLogger('formsender') handler = logging.handlers.SysLogHandler(address=conf.LOG_ADDR) formatter = logging.Formatter('%(levelname)s %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(logging.INFO) # Initiate rate/duplicate controller and application controller = Controller() app = Forms(controller, logger) if with_static: app.wsgi_app = SharedDataMiddleware( app.wsgi_app, {'/static': os.path.join(os.path.dirname(__file__), 'static')}) return app
def serve(port=8000, profile=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=('tottime', 'calls')) if not os.environ.get('NO_STATICS'): application = SharedDataMiddleware(application, { '/assets': os.path.join(sites_path, 'assets'), }) application = StaticDataMiddleware(application, { '/files': os.path.abspath(sites_path) }) run_simple('0.0.0.0', int(port), application, use_reloader=True, use_debugger=True, use_evalex=True, threaded=True)
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 if profile: application = ProfilerMiddleware(application, sort_by=('cumtime', 'calls')) if not os.environ.get('NO_STATICS'): application = SharedDataMiddleware( application, { '/assets': os.path.join(sites_path, 'assets'), }) application = StaticDataMiddleware( application, {'/files': 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) 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 test_shareddatamiddleware_get_file_loader(): """Shared middleware file loader lookup""" app = SharedDataMiddleware(None, {}) assert callable(app.get_file_loader('foo'))