def serve_files(self, export_files=None, extend_config=True): if not self.config['debug']: raise Exception("You can't serve files out of debug mode.") if export_files is None: export_files = {} if extend_config: export_files.update(self.config.get('export_files', {})) self.middleware = SharedDataMiddleware(self.middleware, export_files)
def set_statics(app): ctx = AppContext() modules = ctx.read("modules") for module_name in ctx.read("sorted_modules"): if modules[module_name]["static"] == True: if modules[module_name]["base"] == True: app = SharedDataMiddleware( app, {"/base": ("olaf.addons.base", 'static')}) else: app = SharedDataMiddleware( app, {"/{}".format(module_name): (module_name, 'static')}) return app
def create_app(config=None): app = Backend(config) app = SharedDataMiddleware(app, { '/static': os.path.join(os.path.dirname(__file__), 'static'), '/modules': os.path.join(os.path.dirname(os.path.dirname(__file__)), 'modules') }) return app
def create_app(with_static = True): app = Application() if(with_static): app.wsgi_app = SharedDataMiddleware(app.wsgi_app, { '/static': os.path.join(os.path.dirname(__file__), 'static') }) return app
def run(): from ekklesia_voting.app import make_wsgi_app args = parser.parse_args() wsgi_app = make_wsgi_app(args.config_file) wrapped_app = SharedDataMiddleware(wsgi_app, { '/static': ("ekklesia_voting", 'static'), '/static/deform': ("deform", 'static'), '/static/webfonts': os.environ.get('WEBFONTS_PATH'), '/static/js': os.environ.get('JS_PATH') }) if args.stackdump: stackdump_setup() # use ipdb as default breakpoint() hook (Python 3.7 feature) try: import ipdb except ImportError: pass else: sys.breakpointhook = ipdb.set_trace with open(os.path.join(tmpdir, "ekklesia_voting.started"), "w") as wf: wf.write(datetime.datetime.now().isoformat()) wf.write("\n") # reload when translation MO files change extra_reload_files = glob.glob('src/ekklesia_voting/translations/**/*.mo', recursive=True) if args.config_file is not None: extra_reload_files.append(args.config_file) werkzeug.serving.run_simple(args.bind, args.http_port, wrapped_app, use_reloader=args.debug, extra_files=extra_reload_files, use_debugger=args.debug)
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) # 上传文件设置 app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {'/i/': get_file_path()}) login_manager.init_app(app) from app.modules.main import main as main_blueprint app.register_blueprint(main_blueprint) from app.modules.auth import auth as auth_blueprint app.register_blueprint(auth_blueprint) # from app.modules.documentation import documentation as documentation_blueprint # app.register_blueprint(documentation_blueprint) # from app.modules.file import file as file_blueprint app.register_blueprint(file_blueprint) from app.modules.task import task as task_blueprint app.register_blueprint(task_blueprint) from app.modules.notice import notice as notice_blueprint app.register_blueprint(notice_blueprint) from app.modules.room import room as room_blueprint app.register_blueprint(room_blueprint) from app.modules.schedule import schedule as schedule_blueprint app.register_blueprint(schedule_blueprint) return app
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 start(self): middleware = NotFound() if self.document_root: # middleware for serving static files middleware = SharedDataMiddleware(middleware, {"/": self.document_root}) if self.delayed_response: self._app = DelayedWSGIApplication(middleware, self.delayed_response) else: self._app = WSGIApplication(middleware) # plug the rules self._app.url_map = Map(self.rules) if self.ssl_encryption: try: ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) ctx.load_cert_chain(self.ssl_cert, self.ssl_key) run_simple(self.host, self.port, self._app, threaded=True, ssl_context=ctx) except TypeError: pass else: run_simple(self.host, self.port, self._app, threaded=False)
def _start_frontend(config, host, port, ssh_port): semaphore = threading.Semaphore(0) def active_callback(): semaphore.release() func, close_app_func = get_app(config) inginious_root_path = os.path.abspath( os.path.join(os.path.dirname(__file__), '..', '..', '..')) func = SharedDataMiddleware(func, [ ('/static/', os.path.join(inginious_root_path, 'frontend', 'static')) ]) server = make_server(host, port, func) class FrontendThread(threading.Thread): def __init__(self): super(FrontendThread, self).__init__() self.daemon = True def run(self): try: server.start() except: server.stop() thread = FrontendThread() thread.start() semaphore.acquire() return thread, server, close_app_func
def create_app(redis_host='localhost', redis_port=6379, with_static=True): 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(with_static=True): app = Werbinich() if with_static: app.wsgi_app = SharedDataMiddleware( app.wsgi_app, {'/static': os.path.join(os.path.dirname(__file__), 'static')}) return app
def create_app(redis_host="localhost", redis_port=6379, with_static=True): 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 createApp(app_config=Config): app = Flask(__name__) app.config.from_object(app_config) db.init_app(app) migrate.init_app(app, db) from app.admin import views admin_app.init_app(app, index_view=views.AdminHomeView( name="Home", template="admin/index.html")) api.init_app(api_blueprint) cors.init_app(api_blueprint) mail.init_app(app) jwt.init_app(app) redis_store.init_app(app) es.init_app(app, db) with app.app_context(): register_blueprint(app) setup_jwt(jwt, redis_store) register_apis(api) register_admin_views(admin_app, app, views) app.add_url_rule("/uploads/<filename>", "uploaded_file", build_only=True) app.wsgi_app = SharedDataMiddleware( app.wsgi_app, {"/uploads": app.config["UPLOAD_FOLDER"]}) return app
def create_app(host='localhost', port=6379, db=2, with_static=True): configure = {'host': host, 'port': port, 'db': db} app = Shorty(configure) if with_static: app.wsgi_app = SharedDataMiddleware( app.wsgi_app, {'/static': os.path.join(os.path.dirname(__file__), 'static')}) return app
def __init__(self, database_uri): self.database_engine = create_engine(database_uri) # apply our middlewares. we apply the middlewars *inside* the # application and not outside of it so that we never lose the # reference to the `SimpleWiki` object. self._dispatch = SharedDataMiddleware(self.dispatch_request, {"/_shared": SHARED_DATA}) # free the context locals at the end of the request self._dispatch = local_manager.make_middleware(self._dispatch)
def create_app(storage_path, host_base, template_dir=None, static_dir=None): app = RecipeViewer( { "storage_path": storage_path, "host_base": host_base, "template_dir": template_dir, } ) if static_dir is None: static_dir = ("stray_recipe_manager", "static") app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {"/static": static_dir}) return app
def __init__(self, db_uri): local.application = self server = Server(db_uri) try: db = server.create("urls") except Exception: db = server["urls"] self.dispatch = SharedDataMiddleware(self.dispatch, {"/static": STATIC_PATH}) URL.db = db
def create_app(): app = Flask('flask_cra_example') # Using the shared data middleware we can let the Flask app serve everything, # but you need to do a `npm run build` for it which creates a production-like # build. For an actual production deployment you would have your web server # serve the data from `.../client/build/` and just forward API requests to # the Flask app! app.wsgi_app = SharedDataMiddleware( app.wsgi_app, {'/': os.path.join(os.path.dirname(__file__), 'build')}) app.register_blueprint(frontend) app.register_blueprint(api) return app
def wsgi_app_render(document, **kwargs): if 'port' in kwargs: port = kwargs['port'] else: port = 8888 url = SCRIPT_DIR app = Application(RenderDocument.render(document)) app = SharedDataMiddleware(app, { '/static': os.path.join(url, 'templates/static') }) print(f'Ario Document Server started http://localhost:{port}') run_simple('127.0.0.1', port, app, use_debugger=True, use_reloader=True)
def create_app(watchdog, verbose=False, with_static=True, with_debugger=True, use_evalex=True): from werkzeug.middleware.shared_data 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 __call__(self, environ, start_response): """ wsgi 入口 :param environ: :param start_response: :return: """ if not self.config.static_map: return self.handle_wsgi_request(environ, start_response) from werkzeug.middleware.shared_data import SharedDataMiddleware return SharedDataMiddleware(self.handle_wsgi_request, self.config.static_map)( environ, start_response)
def __call__(self, environ, start_response): """ wsgi 入口 :param environ: :param start_response: :return: """ if not self.context.static_map: return self.handle_wsgi_request(environ, start_response) return SharedDataMiddleware(self.handle_wsgi_request, self.context.static_map)(environ, start_response)
def static_files(app): settings = ag.app.settings if settings.static_files.enabled: # serve static files from static directory (e.g. after copying # from the source packages; use static-copy command for that) if settings.static_files.location == 'static': exported_dirs = { '/' + routing.static_url('/'): settings.dirs.static } return SharedDataMiddleware(app, exported_dirs) # serve static files from source packages based on hierarchy rules return StaticFileServer(app) return app
def init_app(self, app): """Flask application initialization.""" self.init_config(app) app.register_blueprint( blueprint, url_prefix=app.config.get('WIKI_URL_PREFIX') ) app.add_url_rule( app.config.get('WIKI_URL_PREFIX') + '/files/<filename>', 'uploaded_files', build_only=True) app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {app.config.get( 'WIKI_URL_PREFIX') + '/files': app.config['WIKI_UPLOAD_FOLDER']}) app.extensions['flask-wiki'] = self
def test_shared_data_middleware(tmpdir): def null_application(environ, start_response): start_response("404 NOT FOUND", [("Content-Type", "text/plain")]) yield b"NOT FOUND" test_dir = str(tmpdir) with open(os.path.join(test_dir, to_native(u"äöü", "utf-8")), "w") as test_file: test_file.write(u"FOUND") for t in [list, dict]: app = SharedDataMiddleware( null_application, t( [ ("/", os.path.join(os.path.dirname(__file__), "..", "res")), ("/sources", os.path.join(os.path.dirname(__file__), "..", "res")), ("/pkg", ("werkzeug.debug", "shared")), ("/foo", test_dir), ] ), ) for p in "/test.txt", "/sources/test.txt", "/foo/äöü": app_iter, status, headers = run_wsgi_app(app, create_environ(p)) assert status == "200 OK" if p.endswith(".txt"): content_type = next(v for k, v in headers if k == "Content-Type") assert content_type == "text/plain; charset=utf-8" with closing(app_iter) as app_iter: data = b"".join(app_iter).strip() assert data == b"FOUND" app_iter, status, headers = run_wsgi_app( app, create_environ("/pkg/debugger.js") ) with closing(app_iter) as app_iter: contents = b"".join(app_iter) assert b"$(function() {" in contents for path in ("/missing", "/pkg", "/pkg/", "/pkg/missing.txt"): app_iter, status, headers = run_wsgi_app(app, create_environ(path)) assert status == "404 NOT FOUND" assert b"".join(app_iter).strip() == b"NOT FOUND"
def __init__(self, repos, config): self.repos = repos self.config = config self.log = logging.getLogger("wsgi") # at this point, we should build our routing map rules = [ Rule("/", endpoint="frontpage"), Rule(self.config.apiendpoint, endpoint="api"), Rule(self.config.apiendpoint + ";stats", endpoint="api"), Rule(self.config.searchendpoint, endpoint="search") ] if self.config.legacyapi: rules.append(Rule("/-/publ", endpoint="api")) converters = [] self.reporules = {} for repo in self.repos: # a typical repo might provide two rules: # * Rule("/doc/<repo>/<basefile>", endpoint=repo.alias + ".doc") # * Rule("/dataset/<repo>?param1=x", endpoint=repo.alias + ".ds") # # although werkzeug.routing.RuleTemplate seems like it could do that generically? self.reporules[repo] = repo.requesthandler.rules rules.extend(self.reporules[repo]) converters.extend(repo.requesthandler.rule_converters) # at this point, we could maybe write a apache:mod_rewrite # or nginx compatible config based on our rules? # from pprint import pprint # pprint(sorted(x.rule for x in rules)) # import threading, traceback # print("Pid: %s, thread id: %s" % (os.getpid(), threading.get_ident())) # traceback.print_stack() self.routingmap = Map(rules, converters=dict(converters)) base = self.config.datadir exports = { '/index.html': os.path.join(base, 'index.html'), '/rsrc': os.path.join(base, 'rsrc'), '/robots.txt': os.path.join(base, 'robots.txt'), '/favicon.ico': os.path.join(base, 'favicon.ico') } if self.config.legacyapi: exports.extend({ '/json-ld/context.json': os.path.join(base, 'rsrc/api/context.json'), '/var/terms': os.path.join(base, 'rsrc/api/terms.json'), '/var/common': os.path.join(base, 'rsrc/api/common.json') }) self.wsgi_app = SharedDataMiddleware(self.wsgi_app, exports)
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 app = SharedDataMiddleware( app, {"/public": path.join(path.dirname(__file__), "public")}) # clean up locals app = local_manager.make_middleware(app) return app
def create_app(config, with_static=True): # 创建app对象 app = Web({ "redis_host": config.get("redis_host", "localhost"), "redis_port": config.get("redis_port", 6379) }) # 加载静态资源文件 if with_static: app.wsgi_app = SharedDataMiddleware( app.wsgi_app, {"/static": os.path.join(os.path.dirname(__file__), "static")}) if not os.path.exists(app.session_path): os.mkdir(app.session_path) session.set_storage_path(app.session_path) session.load_local_session() return app
def __init__(self, package_name): self.package_name = package_name self.url_map = Map() self.view_functions = {} self.jinja_options = {'autoescape': select_autoescape(['html', 'xml'])} self.jinja_env = Environment(loader=self.create_jinja_loader(), **self.jinja_options) self.root_path = _get_package_path(package_name) if self.static_path is not None: self.url_map.add( Rule(self.static_path + '/<filename>', build_only=True, endpoint='static')) target = os.path.join(self.root_path, 'static') self.wsgi_app = SharedDataMiddleware(self.wsgi_app, {self.static_path: target})
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 test_get_file_loader(): app = SharedDataMiddleware(None, {}) assert callable(app.get_file_loader("foo"))