Esempio n. 1
0
def create_app(with_static=True):
    app = TrackDeploySvc()
    if with_static:
        app.wsgi_app = SharedDataMiddleware(
            app.wsgi_app, {
                '/track_deploy/static':
                os.path.join(os.path.dirname(__file__), 'track_deploy/static')
            })
        #app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
        #    '/track_deploy/static':  '/track_deploy/static'
        #})
    return app
Esempio n. 2
0
    def __init__(self, listen_port, handlers, parameters, shard=0,
                 listen_address=""):
        super().__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', None)
        num_proxies_used = parameters.pop('num_proxies_used', None)

        self.wsgi_app = tornado_wsgi.WSGIApplication(handlers, **parameters)
        self.wsgi_app.service = self

        for entry in static_files:
            # TODO If we will introduce a flag to trigger autoreload in
            # Jinja2 templates, use it to disable the cache arg here.
            self.wsgi_app = SharedDataMiddleware(
                self.wsgi_app, {"/static": entry},
                cache=True, cache_timeout=SECONDS_IN_A_YEAR,
                fallback_mimetype="application/octet-stream")

        self.file_cacher = FileCacher(self)
        self.wsgi_app = FileServerMiddleware(self.file_cacher, self.wsgi_app)

        if rpc_enabled:
            self.wsgi_app = DispatcherMiddleware(
                self.wsgi_app, {"/rpc": RPCMiddleware(self, rpc_auth)})

        # The authentication middleware needs to be applied before the
        # ProxyFix as otherwise the remote address it gets is the one
        # of the proxy.
        if auth_middleware is not None:
            self.wsgi_app = auth_middleware(self.wsgi_app)
            self.auth_handler = self.wsgi_app

        # If we are behind one or more proxies, 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 num_proxies_used is None:
            if is_proxy_used:
                num_proxies_used = 1
            else:
                num_proxies_used = 0

        if num_proxies_used > 0:
            self.wsgi_app = ProxyFix(self.wsgi_app, num_proxies_used)

        self.web_server = WSGIServer((listen_address, listen_port), self)
    def __init__(self, name):
        self.name = name
        self.url_map = Map([])

        self.routes = {}
        self.wsgi_app = SharedDataMiddleware(self.wsgi_app, {
            '/static': os.path.join(os.getcwd(), 'static')
        })

        flaginfo_route = "/flaginfo"
        self.routes[flaginfo_route] = flagoninfo
        self.url_map.add(Rule(flaginfo_route, endpoint=flaginfo_route))
Esempio n. 4
0
    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', None)
        num_proxies_used = parameters.pop('num_proxies_used', None)

        self.wsgi_app = tornado.wsgi.WSGIApplication(
            handlers, template_whitespace="single", **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)})

        # The authentication middleware needs to be applied before the
        # ProxyFix as otherwise the remote address it gets is the one
        # of the proxy.
        if auth_middleware is not None:
            self.wsgi_app = auth_middleware(self.wsgi_app)
            self.auth_handler = self.wsgi_app

        # If we are behind one or more proxies, 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 num_proxies_used is None:
            if is_proxy_used:
                num_proxies_used = 1
            else:
                num_proxies_used = 0

        if num_proxies_used > 0:
            self.wsgi_app = ProxyFix(self.wsgi_app, num_proxies_used)

        self.web_server = WSGIServer((listen_address, listen_port),
                                     self.wsgi_app)
Esempio n. 5
0
	def add_static(self, sps, not_compile=[], url_path="/", merge=True, build=True):
		static_path = []
		for sp in sps:
			try:
				sp = Importer.module_path(sp)
			except:
				pass
			try:
				static_path.append(sp)
				static_builder = StaticBuilder(sp, not_compile)
				if build:
					static_builder.build()
				if build:
					self.wsgi_app = SharedDataMiddleware(self.wsgi_app, {url_path : sp + "/build"}, cache=False)
				else:
					self.wsgi_app = SharedDataMiddleware(self.wsgi_app, {url_path : sp}, cache=False)
			except:
				pass
		if merge:
			self.options["views"]["static_path"] = self.options["views"]["static_path"] + static_path
		else:
			self.options["views"]["static_path"] = static_path
Esempio n. 6
0
def localStart():
    globalInit()
    from werkzeug.serving import run_simple
    static_dir = os.path.join(os.path.dirname(__file__), "..", "static")
    exports = {
        '/': static_dir,
        }
    app_entry = SharedDataMiddleware(application, exports)
    t = Thread(target=checkNode, args=(raConfDir, tmpConfDir, serNode))
    t.deamon = True
    t.start()
    run_simple('0.0.0.0', runPort, app_entry, use_debugger=True, use_reloader=True)
    t._Thread__stop()
Esempio n. 7
0
    def __init__(self, settings):
        app = App(settings)
        api = Api(settings)

        self.wsgi = SharedDataMiddleware(
            self.wsgi, {'/statics': settings.get("statics_dir")},
            cache=settings.get("debug"),
            cache_timeout=(0 if settings.get("debug") else 60 * 60 * 12))

        self.wsgi = DispatcherMiddleware(self.wsgi, {
            '/rest': api,
            '/app': app
        })
Esempio n. 8
0
    def start(self):
        middleware = NotFound()
        if self.document_root:
            # middleware for serving static files
            middleware = SharedDataMiddleware(middleware,
                                              {"/": self.document_root})

        self._app = WSGIApplication(middleware)

        # plug the rules
        self._app.url_map = Map(self.rules)

        run_simple(self.host, self.port, self._app, threaded=True)
Esempio n. 9
0
def create_app(views):
    env = WebEnv(views)

    app = env.wsgi

    if env('debug'):
        from werkzeug.wsgi import SharedDataMiddleware

        app = SharedDataMiddleware(app, {
            '/attachments': env('path_attachments'),
            '/theme': env('path_theme'),
        })
    return app
Esempio n. 10
0
    def __init__(self, db_uri):
        local.application = self

        server = Server(db_uri)
        try:
            db = server.create('urls')
        except:
            db = server['urls']
        self.dispatch = SharedDataMiddleware(self.dispatch, {
            '/static':    STATIC_PATH
        })

        URL.db = db
Esempio n. 11
0
def create_app(static_serving=True):

    app = Shortly(dict(host="localhost", port=6379))

    if static_serving:
        app.wsgi_app = SharedDataMiddleware(app=app.wsgi_app,
                                            exports={
                                                "/static":
                                                os.path.join(
                                                    os.path.dirname(__file__),
                                                    "static")
                                            })

    return app
Esempio n. 12
0
 def __init__(self, root=DEFAULT_ROOT, baseclass=Distro):
     logger.info("Searching %s", root)
     self.distros = {}
     for distro in self.walk(root, baseclass):
         path = os.path.splitext(os.path.relpath(distro.tree.root, root))[0]
         logger.info("Found %s %s at %s", distro.name, distro.version, path)
         self.distros[path] = distro
     rules = chain((Submount(('/%s' % path), distro.rules)
                    for path, distro in self.distros.items()), (
                        Rule('/menu.ipxe', endpoint=self.ep_menu_ipxe),
                        Rule('/<path:path>', endpoint=self.ep_static),
                    ))
     self.urlmap = Map(rules)
     self.static = SharedDataMiddleware(NotFound(), {'/': root})
def create_app(with_static=True):
    """
    创建app对象,加入了中间件
    :param with_static:是否开启访问静态资源模式
    :return: app对象
    """
    app = App()
    if with_static:
        # 模板中可使用static中的资源
        # <link rel=stylesheet href=/static/style.css type=text/css>
        app.wsgi_app = SharedDataMiddleware(
            app.wsgi_app, {"/static": os.path.join(os.path.dirname(os.path.dirname(__file__)), "static")}
        )
    return app
Esempio n. 14
0
def create_app(with_static=True):
    app = App()

    if with_static:
        app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
            '/statics':  os.path.join(os.path.dirname(__file__), 'statics')
        })

    if not os.path.isdir('results'):
        os.mkdir('results')

    SingerMorning(app)

    return app
Esempio n. 15
0
    def __init__(self, presentation, media=None, config=None):
        '''
        Initializes the server and creates the environment for the presentation
        '''
        self.config = Config(config)
        self.presentation = presentation

        shared_data = {
            '/static': os.path.join(os.path.dirname(__file__), 'static')
        }

        shared_data.update(self.parse_media_root(media))

        self.wsgi_app = SharedDataMiddleware(self.wsgi_app, shared_data)
Esempio n. 16
0
def create_app(redis_host='localhost', redis_port=6379, with_static=True):

    app = MIR_enabled_music_search_engine({
        '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
Esempio n. 17
0
    def run(self, host='127.0.0.1', port=5000, debug=None):
        """Run the application at the given host and port.

        :param str host: The hostname to run the application on.
        :param int port: The port to run the application on.
        """

        if debug is not None:
            self.debug = debug
        SocketIOServer(
            ('0.0.0.0', 5000),
            SharedDataMiddleware(self, {}),
            resource="socket.io",
            policy_server=False).serve_forever()
Esempio n. 18
0
def create_static_app(root):
    """
    Serves a directory, with hack to make index.html work.
    """
    def with_index_html(environ, start_response):
        environ['PATH_INFO'] = environ.get('PATH_INFO', '') + '/index.html'
        app = SharedDataMiddleware(NotFound(), {
            '/': root,
        })
        return app(environ, start_response)

    return SharedDataMiddleware(with_index_html, {
        '/': root,
    })
Esempio n. 19
0
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()
Esempio n. 20
0
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
Esempio n. 21
0
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
Esempio n. 22
0
 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,
     })
Esempio n. 23
0
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
Esempio n. 24
0
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
Esempio n. 25
0
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
Esempio n. 26
0
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
Esempio n. 27
0
    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)
Esempio n. 28
0
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
Esempio n. 29
0
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
Esempio n. 30
0
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