Exemple #1
0
 def __init__(self, ctx):
     # Convert paths and ids to utf-8, otherwise werkzeug will break
     self.exports = dict(imap(
         lambda x: (x[0].encode('utf-8'), x[1].encode('utf-8')),
         self.exports.items()))
     IMiddleware.__init__(self, ctx)
     SharedDataMiddleware.__init__(self, self.application, self.exports)
Exemple #2
0
def create_app():
    instance_path = path(__file__).abspath().parent / 'instance'
    app = flask.Flask(__name__,
                      instance_path=instance_path,
                      instance_relative_config=True)
    app.config.update(default_config)
    app.config.from_pyfile("settings.py", silent=True)

    sentry.init_app(app)

    app.register_blueprint(views.lists)
    app.register_blueprint(views.flis)
    _my_extensions = app.jinja_options["extensions"] + ["jinja2.ext.do"]
    template_loader = jinja2.ChoiceLoader([
        frame.FrameTemplateLoader(),
        app.create_global_jinja_loader(),
    ])
    app.jinja_options = dict(app.jinja_options,
                             extensions=_my_extensions,
                             loader=template_loader)
    database.initialize_app(app)
    if app.config['DEBUG']:
        files_path = path(app.root_path)
        files_path = flask.safe_join(files_path, "instance/files")
        app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
            "/static/files": files_path,
        })
    if app.config["HTTP_PROXIED"]:
        from revproxy import ReverseProxied
        app.wsgi_app = ReverseProxied(app.wsgi_app)
    return app
    def upload(self, name=None, path=None, folder='upload',\
            allowed_extensions=None, max_size=None):
        """
        ckeditor upload method
        :name: the app name or blueprint name
        :path: the upload path
        :allowed_extensions: allowed file extensions
        :max_size: the max size of uploaded file
        """
        error = ''
        url = ''
        callback = request.args.get("CKEditorFuncNum")

        if request.method == 'POST' and 'upload' in request.files:
            fileobj = request.files['upload']
            fname, fext = os.path.splitext(fileobj.filename)
            if allowed_extensions and \
                fext not in allowed_extensions:
                error = '%s not in the allowed extensions!' % fext
                return error
            rnd_name = '%s%s' % (self.gen_rnd_filename(), fext)

            if not path:
                filepath = os.path.join(name.static_folder, 'upload', rnd_name)
            else:
                filepath = path
                app.add_url_rule('/ckupload/<filename>',
                                 'uploaded_file',
                                 build_only=True)
                app.wsgi_app = SharedDataMiddleware(app.wsgi_app,
                                                    {'/ckupload/': path})

            dirname = os.path.dirname(filepath)
            if not os.path.exists(dirname):
                try:
                    os.makedirs(dirname)
                except:
                    error = 'path <%s> not exist!' % filepath
            elif not os.access(dirname, os.W_OK):
                error = 'path <%s> not writable' % filepath
            if not error:
                fileobj.save(filepath)
                url = url_for('.static',
                              filename='%s/%s' % ('upload', rnd_name))
                # if not path:
                #     url = url_for('.static', filename='%s/%s' % (folder, rnd_name))
                # else:
                #     url = url_for('.uploaded_file', filename='%s/%s' % (folder, rnd_name))
        else:
            error = 'post error'

        res = """
                <script type="text/javascript">
                    window.parent.CKEDITOR.tools.callFunction('%s', '%s', '%s');
                </script>
             """ % (callback, url, error)

        response = make_response(res)
        response.headers["Content-Type"] = "text/html"
        return response
Exemple #4
0
    def prepare(self):
        local.fp = self
        self.prepared = True

        @self.app.before_request
        def before_request():
            g.start = time.time()

        if self.config.DEBUG:

            @self.app.after_request
            def after_request(response):
                diff = time.time() - g.start
                if (response.response):
                    response.headers["Execution-Time"] = str(diff)
                return response

        self.app.add_url_rule(self.app.config['UPLOAD_DIRECTORY_URL'] +
                              '<filename>',
                              'FyPress.uploaded_file',
                              build_only=True)
        self.app.wsgi_app = SharedDataMiddleware(
            self.app.wsgi_app, {
                self.app.config['UPLOAD_DIRECTORY_URL']:
                self.app.config['UPLOAD_DIRECTORY']
            })

        self.blueprint()
Exemple #5
0
def make_wsgi(profile='Default'):

    config.appinit(settingsmod, profile)

    app = WSGIApp()

    app = ElixirApp(app)

    app = SessionMiddleware(app, **dict(settings.beaker))

    app = RegistryManager(app)

    # serve static files from main app and supporting apps (need to reverse order b/c
    # middleware stack is run in bottom up order).  This works b/c if a
    # static file isn't found, the ShardDataMiddleware just forwards the request
    # to the next app.
    for appname in config.appslist(reverse=True):
        app_py_mod = __import__(appname)
        fs_static_path = path.join(path.dirname(app_py_mod.__file__), 'static')
        static_map = {routing.add_prefix('/'): fs_static_path}
        app = SharedDataMiddleware(app, static_map)

    # show nice stack traces and debug output if enabled
    if settings.debugger.enabled:
        app = DebuggedApplication(app, evalex=settings.debugger.interactive)

    return app
Exemple #6
0
 def __init__(self, debug):
     local.application = self
     iptables.reset(config["interface_lan"], config["interface_wan"])
     for addr in user.getmacs():
         iptables.addmac(addr)
     self.debug = debug
     self.dispatch = SharedDataMiddleware(self.safedispatch, {"/static": path["static"]})
Exemple #7
0
 def setup_static(sender):
     '''Setup static file serving in dev environment'''
     from werkzeug import SharedDataMiddleware
     import os
     app.wsgi_app = SharedDataMiddleware(
         app.wsgi_app,
         {'/': os.path.join(os.path.dirname(__file__), 'static')})
Exemple #8
0
    def prepare(self):
        self.prepared = True

        # Cache
        if self.config.CACHE_TYPE == 'redis':
            self.cache = RedisCache(host=self.config.CACHE_SERV)
        elif self.config.CACHE_TYPE == 'memcached':
            self.cache = MemcachedCache(servers=[self.config.CACHE_SERV])
        else:
            self.cache = FileSystemCache(self.config.CACHE_SERV)

        # Options
        from .admin import Option
        self.options = Option.auto_load()

        # Timer
        @self.app.before_request
        def before_request():
            g.start = time.time()

        # Medias
        self.app.add_url_rule(self.app.config['UPLOAD_DIRECTORY_URL'] +
                              '<filename>',
                              'FyPress.uploaded_file',
                              build_only=True)
        self.app.wsgi_app = SharedDataMiddleware(
            self.app.wsgi_app, {
                self.app.config['UPLOAD_DIRECTORY_URL']:
                self.app.config['UPLOAD_DIRECTORY']
            })
Exemple #9
0
def make_app(session_store=None):
    application = Application(session_store=session_store)
    application = SharedDataMiddleware(application, staticLocations)
    application = local_manager.make_middleware(application)

    if config.getboolean('debugging', 'debug') is True:
        application = DebuggedApplication(application, evalex=True)
    return application
Exemple #10
0
def make_app(dburi, secret_key, debug=False, shell=False):
    """Apply the used middlewares and create the application."""
    static_path = os.path.join(os.path.dirname(__file__), 'static')
    app = LodgeIt(dburi, secret_key)
    if debug:
        app.engine.echo = True
    if not shell:
        # we don't need access to the shared data middleware in shell mode
        app = SharedDataMiddleware(app, {'/static': static_path})
    return app
Exemple #11
0
 def __init__(self):
     local.application = self
     storage_class = import_string(settings.SESSION_STORE)
     if not os.path.isdir(settings.SESSION_PATH):
         os.makedirs(settings.SESSION_PATH)
     self.dispatch = SessionMiddleware(
         self.dispatch, storage_class(path=settings.SESSION_PATH))
     self.dispatch = SharedDataMiddleware(self.dispatch, {
         '/media': settings.MEDIA_ROOT,
     })
Exemple #12
0
    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)
Exemple #13
0
def create_app(name=__name__, config={}):
    app = Flask(name)
    app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DB_URI')
    # app.config['SQLALCHEMY_POOL_SIZE'] = 10
    app.secret_key = config.get('secret_key', '(secret key is not set)')

    app.config.update(config)

    from app.analysis.model import db
    db.init_app(app)

    from app.api import api_module
    from app.main import main_module
    from app.corpus import corpus_module
    app.register_blueprint(api_module, url_prefix='')
    app.register_blueprint(main_module, url_prefix='')
    app.register_blueprint(corpus_module, url_prefix='/corpus')

    from app.utils import register_filters
    register_filters(app)

    babel.init_app(app)

    if app.config['DEBUG']:
        from werkzeug import SharedDataMiddleware
        app.wsgi_app = SharedDataMiddleware(
            app.wsgi_app,
            {'/': os.path.join(os.path.dirname(__file__), 'static')})

    @app.before_first_request
    def init_rollbar():
        """init rollbar module"""
        rollbar.init(
            # access token
            os.environ.get('ROLLBAR_TOKEN', ''),
            # environment name
            os.environ.get('ROLLBAR_ENV', 'development'),
            # server root directory, makes tracebacks prettier
            root=os.path.dirname(os.path.realpath(__file__)),
            # flask already sets up logging
            allow_logging_basic_config=False,
            # Use HTTP as GAE does not allow the use of the SSL package
            endpoint='http://api.rollbar.com/api/1/')

        # send exceptions from `app` to rollbar, using flask's signal system.
        got_request_exception.connect(rollbar.contrib.flask.report_exception,
                                      app)

    if babel.locale_selector_func is None:
        babel.localeselector(get_locale)

    return app
Exemple #14
0
def create_app(config_name='development'):
    app = Flask(__name__)
    app.config.from_object(config[config_name])

    app.elasticsearch = Elasticsearch([app.config['ELASTICSEARCH_URL']]) \
        if app.config['ELASTICSEARCH_URL'] else None

    config[config_name].init_app(app)

    db.init_app(app)
    mail.init_app(app)
    login_manager.init_app(app)
    pagedown.init_app(app)
    moment.init_app(app)
    lesscss(app)

    app.add_url_rule('/uploads/<filename>', 'uploads', build_only=True)
    app.wsgi_app = SharedDataMiddleware(
        app.wsgi_app, {'/uploads': app.config['UPLOAD_FOLDER']})
    app.memory = base.Client(('localhost', 11211))

    from .errors import errors
    app.register_blueprint(errors)

    from .main import main
    app.register_blueprint(main)

    from .auth import auth
    app.register_blueprint(auth)

    from .admin import admin
    app.register_blueprint(admin)

    from .moderator import moderator
    app.register_blueprint(moderator)

    from .user import user
    app.register_blueprint(user)

    from .post import post
    app.register_blueprint(post)

    from .comment import comment
    app.register_blueprint(comment)

    from .notice import notice
    app.register_blueprint(notice)

    from .api_1_0 import api as api_blueprint
    app.register_blueprint(api_blueprint, url_prefix='/api/v1.0')

    return app
Exemple #15
0
    def _setup_static_handler(self):
        from werkzeug import SharedDataMiddleware

        self.app.wsgi_app = SharedDataMiddleware(
            self.app.wsgi_app, {
                '/': os.path.normpath(self.www_path),
            },
            cache=False)

        @self.app.route('/', methods=['GET'])
        def index_get():
            with open(os.path.join(self.www_path, 'index.html'), 'r') as fd:
                return fd.read()
    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
Exemple #17
0
    def __init__(self, hostname, port, database, debug=False):
        self.hostname = hostname
        self.port = port
        self.debug = debug

        app.debug = debug
        app.secret_key = 'dummy_secret_key' if debug else os.urandom(24)
        app.wsgi_app = SharedDataMiddleware(
            app.wsgi_app,
            {'/': os.path.join(os.path.dirname(__file__), 'static')})

        op.open_db(database)

        logger.info('crawler setup: hostname {0}, port {1}, db {2}, debug {3}',
                    hostname, port, database, debug)
Exemple #18
0
def create_app(config_name='development'):
    app = Flask(__name__)
    app.config.from_object(config[config_name])

    config[config_name].init_app(app)

    db.init_app(app)
    mail.init_app(app)
    login_manager.init_app(app)

    app.add_url_rule('/uploads/<filename>', 'uploads', build_only=True)
    app.wsgi_app = SharedDataMiddleware(
        app.wsgi_app, {'/uploads': app.config['UPLOAD_FOLDER']})

    from .ex import ex
    app.register_blueprint(ex)

    return app
def _configure_uploads(app):
    app.config['FILES_PATH'] = files_path = Path(app.instance_path) / 'files'
    app.config['PATH_BACKGROUNDS_KEY'] = path_backgrounds_key = 'backgrounds'
    app.config['PATH_CROP_KEY'] = path_crop_key = 'crops'
    app.config['PATH_CUSTOM_KEY'] = path_custom_key = 'custom_uploads'
    app.config['PATH_LOGOS_KEY'] = path_logos_key = 'logos'
    app.config['PATH_THUMB_KEY'] = path_thumb_key = 'thumbnails'
    app.config['PATH_PRINTOUTS_KEY'] = path_printouts_key = 'printouts'

    if 'UPLOADED_BACKGROUNDS_DEST' not in app.config:
        app.config['UPLOADED_BACKGROUNDS_DEST'] = (files_path /
                                                   path_backgrounds_key)
    if 'UPLOADED_CROP_DEST' not in app.config:
        app.config['UPLOADED_CROP_DEST'] = files_path / path_crop_key
    if 'UPLOADED_CUSTOM_DEST' not in app.config:
        app.config['UPLOADED_CUSTOM_DEST'] = files_path / path_custom_key
    if 'UPLOADED_LOGOS_DEST' not in app.config:
        app.config['UPLOADED_LOGOS_DEST'] = files_path / path_logos_key
    if 'UPLOADED_PRINTOUTS_DEST' not in app.config:
        app.config['UPLOADED_PRINTOUTS_DEST'] = files_path / path_printouts_key

    # ensure logos and printouts folders exist
    app.config['UPLOADED_LOGOS_DEST'].makedirs_p()
    app.config['UPLOADED_PRINTOUTS_DEST'].makedirs_p()

    if 'MEDIA_FOLDER' not in app.config:
        app.config['MEDIA_FOLDER'] = files_path
    if 'MEDIA_THUMBNAIL_FOLDER' not in app.config:
        app.config['MEDIA_THUMBNAIL_FOLDER'] = \
            app.config['UPLOADED_THUMBNAIL_DEST'] = files_path / path_thumb_key
    app.config['MEDIA_THUMBNAIL_URL'] = '/static/files/thumbnails/'

    app.add_url_rule('/static/files/<filename>', 'files', build_only=True)
    app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
        '/static/files': files_path,
    })

    # limit upload size to 1MB
    patch_request_class(app, app.config.get(
        'MAX_UPLOAD_SIZE', 1 * 1024 * 1024))
    configure_uploads(app, (backgrounds, custom_upload, logos_upload))
    Thumbnail(app)
Exemple #20
0
    def run_server():
        from gevent import monkey
        monkey.patch_all(subprocess=True)
        from gevent.wsgi import WSGIServer
        import socket
        from geventwebsocket.handler import WebSocketHandler

        os.environ['CONFIG'] = CONFIG
        from lightop import app

        if not DEBUG:  # run on NAS
            from werkzeug import SharedDataMiddleware
            app.wsgi_app = SharedDataMiddleware(
                app.wsgi_app,
                {'/': os.path.join(os.path.dirname(__file__), 'static')})
        # websocket conflict: WebSocketHandler
        if DEBUG or STAGING:
            # from werkzeug.debug import DebuggedApplication
            app.debug = True
            # app = DebuggedApplication(app, evalex=True)

        print('Fork monitor programs')
        pgid = os.getpgid(0)
        procs = []
        procs.extend([
            subprocess.Popen(program, close_fds=True, shell=True)
            for program in PROGRAMS
        ])
        signal.signal(signal.SIGTERM, lambda *args: killpg(pgid))
        signal.signal(signal.SIGHUP, lambda *args: killpg(pgid))
        signal.signal(signal.SIGINT, lambda *args: killpg(pgid))

        print('Running on port ' + str(PORT))
        try:
            http_server = WSGIServer(('', PORT),
                                     app,
                                     handler_class=WebSocketHandler)
            http_server.serve_forever()
        except socket.error as e:
            print(e)
Exemple #21
0
def setup_env():

    from werkzeug import SharedDataMiddleware
    import os
    application.wsgi_app = SharedDataMiddleware(
        application.wsgi_app,
        {'/': os.path.join(os.path.dirname(__file__), 'static')})

    application.config["DEBUG_TB_INTERCEPT_REDIRECTS"] = False
    application.config["DEBUG_TB_PROFILER_ENABLED"] = False
    application.config['DEBUG_TB_PANELS'] = (
        'flask_debugtoolbar.panels.headers.HeaderDebugPanel',
        'flask_debugtoolbar.panels.logger.LoggingPanel',
        'flask_debugtoolbar.panels.timer.TimerDebugPanel',
        'flask_debugtoolbar.panels.profiler.ProfilerDebugPanel',
        'flask_debugtoolbar.panels.request_vars.RequestVarsDebugPanel',
        # 'flask_debugtoolbar.panels.template.TemplateDebugPanel',
        # 'flask_debugtoolbar.panels.versions.VersionDebugPanel',
        'flask_mongoengine.panels.MongoDebugPanel')

    from flask_debugtoolbar import DebugToolbarExtension
    toolbar = DebugToolbarExtension(application)
Exemple #22
0
def make_static_serving_app(application, shared):
    """
    wrap application in a static file serving app

    @param application: WSGI wiki application that should be wrapped
    @param shared:  directory where static files are located (then we create the
                    usual mapping dict we need automatically), or a ready-to-use
                    mapping dict for SharedDataMiddleware.
                    If True, use builtin static files from STATIC_FILES_PATH.
    @returns: wrapped WSGI application
    """
    if not isinstance(shared, dict):
        if shared is True:
            shared = STATIC_FILES_PATH
        if isdir(shared):
            shared = {config.url_prefix_static: shared,
                      # XXX only works / makes sense for root-mounted wikis:
                      '/favicon.ico': join(shared, 'favicon.ico'),
                      '/robots.txt': join(shared, 'robots.txt')}
        else:
            raise ValueError("Invalid path given for shared parameter")
    return SharedDataMiddleware(application, shared)
Exemple #23
0
    def __call__(self, name, **kwargs):
        self.app = Flask(name, **kwargs)
        self.app.config.from_object(self.config)

        self.bind_extensions(db, mail, celery, csrf, cache, htmlmin, toolbar)

        register_connection(DB_TEMP_NAME, DB_TEMP_NAME)

        self.app.session_interface = MongoEngineSessionInterface(db)
        self.app.permanent_session_lifetime = timedelta(weeks=1)

        self.app.user_datastore = MongoEngineUserDatastore(db, User, Role)
        self.app.security = Security(self.app,
                                     self.app.user_datastore,
                                     login_form=ExtLoginForm)

        @self.app.security.send_mail_task
        def delay_security_email(msg):
            send_security_mail.delay(msg)

        # @self.app.errorhandler(Exception)
        # def validation_error(err):
        #     flash(err.message, 'error')
        #     return redirect(request.path)

        self.register_blueprints(BLUEPRINTS)
        self.register_template_filters(time_distance, is_list, smart_round,
                                       pretty_date, phonofize)
        self.register_context_processors(categories, cart, visited_offers,
                                         pages)

        self.app.jinja_env.globals['get_plural'] = get_plural

        self.app.add_url_rule('/media/<filename>', 'media', build_only=True)
        self.app.wsgi_app = SharedDataMiddleware(
            self.app.wsgi_app, {'/media': self.app.config['MEDIA_DIR']})

        return self.app
def create_app(config_name='default'):
    '''
    factory function creates and initialize app instance
    '''
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    # init of plugins
    db.init_app(app)
    mako.init_app(app)

    # blueprints
    from app.main import main as main_blueprint

    app.register_blueprint(main_blueprint)

    # TODO: ?
    # http://flask.palletsprojects.com/en/1.1.x/patterns/fileuploads/
    # Read source file by SharedDataMiddleware
    app.wsgi_app = SharedDataMiddleware(app.wsgi_app,
                                        {'/i/': app.config['UPLOAD_FOLDER']})

    return app
Exemple #25
0
            modal.endSession()
            mydict = {}
            foodDetected = foodDetected.replace("'", "")
            foodDetected = foodDetected.replace(" ", "")
            splitted = foodDetected.split(",")

            for v in splitted:
                aux = v.split(":")
                mydict[aux[0]] = aux[2]

            imgUrl = url_for('send_file', filename=filename)
            return render_template(
                'detection.html',
                imgUrl=imgUrl,
                foodDetected=mydict,
                totalPrice=calculate_item.calculatePrice(mydict))
    return render_template('upload.html', filename=filename)


@app.route('/uploads/<filename>')
def send_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)


from werkzeug import SharedDataMiddleware
app.add_url_rule('/uploads/<filename>', 'uploaded_file', build_only=True)
app.wsgi_app = SharedDataMiddleware(app.wsgi_app,
                                    {'/upload': app.config['UPLOAD_FOLDER']})

if __name__ == '__main__':
    socketio.run(app)
Exemple #26
0
def create_instance():
    """
    Construct a new Flask instance and return it.
    """
    import os

    app = Flask(__name__)
    app.config.from_object('notifico.config')

    if app.config.get('NOTIFICO_ROUTE_STATIC'):
        # We should handle routing for static assets ourself (handy for
        # small and quick deployments).
        import os.path
        from werkzeug import SharedDataMiddleware

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

    if not app.debug:
        # If sentry (http://getsentry.com) is configured for
        # error collection we should use it.
        if app.config.get('SENTRY_DSN'):
            sentry.dsn = app.config.get('SENTRY_DSN')
            sentry.init_app(app)

    # Setup our redis connection (which is already thread safe)
    app.redis = Redis(host=app.config['REDIS_HOST'],
                      port=app.config['REDIS_PORT'],
                      db=app.config['REDIS_DB'])
    # Attach Flask-Cache to our application instance. We override
    # the backend configuration settings because we only want one
    # Redis instance.
    cache.init_app(app,
                   config={
                       'CACHE_TYPE': 'redis',
                       'CACHE_REDIS_HOST': app.redis,
                       'CACHE_OPTIONS': {
                           'key_prefix': 'cache_'
                       }
                   })
    # Attach Flask-Mail to our application instance.
    mail.init_app(app)
    # Attach Flask-SQLAlchemy to our application instance.
    db.init_app(app)

    # Update celery's configuration with our application config.
    celery.config_from_object(app.config)

    # Import and register all of our blueprints.
    from notifico.views.account import account
    from notifico.views.public import public
    from notifico.views.projects import projects
    from notifico.views.pimport import pimport
    from notifico.views.admin import admin

    app.register_blueprint(account, url_prefix='/u')
    app.register_blueprint(projects)
    app.register_blueprint(public)
    app.register_blueprint(pimport, url_prefix='/i')
    app.register_blueprint(admin, url_prefix='/_')

    # Register our custom error handlers.
    from notifico.views import errors

    app.register_error_handler(500, errors.error_500)

    # cia.vc XML-RPC kludge.
    from notifico.services.hooks.cia import handler
    handler.connect(app, '/RPC2')

    # Setup some custom Jinja2 filters.
    app.jinja_env.filters['pretty_date'] = pretty.pretty_date
    app.jinja_env.filters['plural'] = pretty.plural
    app.jinja_env.filters['fix_link'] = pretty.fix_link

    return app
Exemple #27
0
    logging.basicConfig(filename=options.logfile, level=log_level)

    app.config['SQLALCHEMY_DATABASE_URI'] = options.db
    app.config['DEBUG'] = True
    app.config['SECRET_KEY'] = 'NOT A SECRET'
    app.config.update(cef_config(options.cef_log))

    with app.test_request_context():
        db.init_app(app)
        db.create_all()

    def auth(environ, username, password):
        return options.username == username and options.password == password

    if app.config['DEBUG']:
        # Setting up the cron/ directory with some testing data
        # In production, this is managed by Apache and the json file is going to be override
        # by the cron (see bug 1155935)
        from werkzeug import SharedDataMiddleware
        app.wsgi_app = SharedDataMiddleware(
            app.wsgi_app,
            {'/cron/': path.join(path.dirname(__file__), 'cron/')})

    # We serve (at least) a stastic json file
    from werkzeug import SharedDataMiddleware
    app.wsgi_app = SharedDataMiddleware(
        app.wsgi_app, {'/json/': path.join(path.dirname(__file__), 'json/')})

    app.wsgi_app = AuthBasicHandler(app.wsgi_app, "Release kick-off", auth)
    app.run(port=options.port, host=options.host)
Exemple #28
0
        if callback:
            data = str(func(*args, **kwargs)['data'])
            content = str(callback) + '(' + data + ')'
            mimetype = 'application/javascript'
            return current_app.response_class(content, mimetype=mimetype)
        else:
            return func(*args, **kwargs)['data']
    return decorated_function

def get_4sq_place(location):
    places = client.venues.search(params={'near':location})
    venues = []
    for venue in places['venues']:
        venue['_id'] = venue['id'] #maybe create a copy?
        venues.append(venue)
        #TODO(mbhagat): check if the id already exists and update it
    places_collection = db['foursquare_places']
    places_collection.insert(venues)
    return places;

if __name__ == "__main__":
    # Bind to PORT if defined, otherwise default to 5000.
    port = int(os.environ.get('PORT', 5000))
    from werkzeug import SharedDataMiddleware
    app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
      '/': os.path.join(os.path.dirname(__file__), 'client/app')
    })
    app.debug = True
    app.run(host='0.0.0.0', port=port)
    
Exemple #29
0
def webapp():
    static_path = os.path.join(os.path.dirname(__file__), 'static')
    return SharedDataMiddleware(WebApp(), {'/javascript': static_path})
Exemple #30
0
    def __init__(self, package_name):
        #: the debug flag.  Set this to `True` to enable debugging of
        #: the application.  In debug mode the debugger will kick in
        #: when an unhandled exception ocurrs and the integrated server
        #: will automatically reload the application if changes in the
        #: code are detected.
        self.debug = False

        #: the name of the package or module.  Do not change this once
        #: it was set by the constructor.
        self.package_name = package_name

        #: where is the app root located?
        # 项目根路径
        self.root_path = _get_package_path(self.package_name)

        #: a dictionary of all view functions registered.  The keys will
        #: be function names which are also used to generate URLs and
        #: the values are the function objects themselves.
        #: to register a view function, use the :meth:`route` decorator.
        # 视图函数存储字典
        self.view_functions = {}

        #: a dictionary of all registered error handlers.  The key is
        #: be the error code as integer, the value the function that
        #: should handle that error.
        #: To register a error handler, use the :meth:`errorhandler`
        #: decorator.
        # 错误处理函数存储字典
        self.error_handlers = {}

        #: a list of functions that should be called at the beginning
        #: of the request before request dispatching kicks in.  This
        #: can for example be used to open database connections or
        #: getting hold of the currently logged in user.
        #: To register a function here, use the :meth:`before_request`
        #: decorator.
        # 预处理函数存储字典, 预处理: 请求处理前执行
        self.before_request_funcs = []

        #: a list of functions that are called at the end of the
        #: request.  Tha function is passed the current response
        #: object and modify it in place or replace it.
        #: To register a function here use the :meth:`after_request`
        #: decorator.
        # 请求处理后执行函数存储字典
        self.after_request_funcs = []

        #: a list of functions that are called without arguments
        #: to populate the template context.  Each returns a dictionary
        #: that the template context is updated with.
        #: To register a function here, use the :meth:`context_processor`
        #: decorator.
        self.template_context_processors = [_default_template_ctx_processor]

        self.url_map = Map()

        if self.static_path is not None:
            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')
            self.wsgi_app = SharedDataMiddleware(self.wsgi_app, {
                self.static_path: target
            })

        #: the Jinja2 environment.  It is created from the
        #: :attr:`jinja_options` and the loader that is returned
        #: by the :meth:`create_jinja_loader` function.
        self.jinja_env = Environment(loader=self.create_jinja_loader(),
                                     **self.jinja_options)
        # 添加这两个函数到 jinja 中, 然后再模板文件中也可以调用这些函数了
        self.jinja_env.globals.update(
            url_for=url_for,
            get_flashed_messages=get_flashed_messages
        )
Exemple #31
0
 def __call__(self, *args, **kwargs):
     return SharedDataMiddleware.__call__(self, *args, **kwargs)
Exemple #32
0
 def __init__(self, app, **kwargs):
     exports = {'/' + routing.static_url('/'): ''}
     SharedDataMiddleware.__init__(self, app, exports, **kwargs)