def create_app():
    app = Flask(__name__)

    # Append CORS headers to each request.
    app.after_request(cors_headers)

    # Register views.
    app.register_blueprint(main)
    app.register_blueprint(static)
    app.register_blueprint(status)

    # Use a dummy data generator while Yahoo BOSS access is being sorted out.
    app.register_blueprint(dummy)

    # Log using the mozlog format to stdout.
    handler = StreamHandler(stream=stdout)
    handler.setFormatter(MozLogFormatter(logger_name='universalSearch'))
    handler.setLevel(INFO)
    app.logger_name = 'request.summary'
    app.logger.addHandler(handler)
    app.logger.setLevel(INFO)

    # Use logging middleware.
    if not conf.TESTING:
        app.before_request(request_timer)
        app.after_request(request_summary)

    app.config.update(
        CELERY_BROKER_URL=conf.CELERY_BROKER_URL,
        DEBUG=conf.DEBUG
    )
    return app
Beispiel #2
0
def create_app(config_obj):
    app = Flask(__name__)
    app.config.from_object(config_obj)
    app.after_request(req_end)
    db.init_app(app)
    app.register_blueprint(blueprint, url_prefix='/api/v1')
    return app
Beispiel #3
0
def init_hooks(app: Flask):
    @app.before_first_request
    def set_current_celery_app():
        """Listener for `before_first_request`.

        Set our celery app as current, so that task use the correct
        config. Without that tasks may use their default set app.
        """
        celery = app.extensions.get("celery")
        if celery:
            celery.set_current()

    @app.before_first_request
    def register_signals():
        signals.register_js_api.send(app)

    # def install_id_generator(sender, **kwargs):
    #     g.id_generator = count(start=1)
    #
    # appcontext_pushed.connect(install_id_generator)

    if os.environ.get("FLASK_VALIDATE_HTML"):
        # Workaround circular import
        from abilian.testing.validation import validate_response

        app.after_request(validate_response)
Beispiel #4
0
def create_app():
    app = Flask(__name__)
    api = Api(app)
    app.config.from_object('config.default')
    app.config.from_envvar('APP_SETTINGS', silent=False)
    app.add_url_rule('/api/login', 'login', _get_token)
    from models.base import db
    db.init_app(app)
    from controllers.index import Index
    from controllers.user import UsersList, UserSingle
    from controllers.tasks import TaskSingle, Tasks, AssignTask
    from controllers.comments import Comments
    from controllers.reports import UserComments, TaskStats
    app.before_request(db_connect.before_request)
    app.after_request(db_connect.after_request)
    app.add_url_rule('/api/tasks/<int:task_id>/comments',
                     view_func=Comments.as_view(COMMENTS))
    api.add_resource(Index, '/api/index')
    api.add_resource(UsersList, '/api/users')
    api.add_resource(UserSingle, '/api/users/<int:user_id>')
    api.add_resource(Tasks, '/api/tasks')
    api.add_resource(TaskSingle, '/api/tasks/<int:task_id>')
    api.add_resource(AssignTask, '/api/assign_task')
    api.add_resource(UserComments, '/api/reports/user_comments')
    api.add_resource(TaskStats, '/api/reports/task_stats')
    return app
Beispiel #5
0
def create_app(debug=False):
    app = Flask(__name__)
    app.debug = debug
    app.secret_key = 'this is a secret'
    app.json_encoder = Jsonifier

    app.file_root = os.path.abspath(os.path.dirname(__file__))

    app.before_request(before_request)
    app.after_request(after_request)
    app.context_processor(context_processor)

    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'

    db.init_app(app)
    with app.app_context():
        init_all()
    app.register_blueprint(admin_app, url_prefix='/admin')
    app.register_blueprint(campaign_app, url_prefix='/')
    app.register_blueprint(character_app, url_prefix='/character')
    app.register_blueprint(dm_app, url_prefix='/dm')
    app.register_blueprint(chat_app, url_prefix='/chat')
    app.register_blueprint(items_app, url_prefix='/item-type')
    app.register_blueprint(knowledge_app, url_prefix='/knowledge')

    return app
Beispiel #6
0
def setup_app(warnings=None):
    if warnings is None:
        warnings = []

    app = Flask(__name__)
    cfy_config = config.instance()

    app.logger_name = 'manager-rest'
    # setting up the app logger with a rotating file handler, in addition to
    #  the built-in flask logger which can be helpful in debug mode.
    create_logger(logger_name=app.logger.name,
                  log_level=cfy_config.rest_service_log_level,
                  log_file=cfy_config.rest_service_log_path,
                  log_file_size_MB=cfy_config.rest_service_log_file_size_MB,
                  log_files_backup_count=cfy_config.
                  rest_service_log_files_backup_count)

    # log all warnings passed to function
    for w in warnings:
        app.logger.warning(w)

    # secure the app according to manager configuration
    if cfy_config.security_enabled:
        app.logger.info('initializing rest-service security')
        init_secured_app(app)

    app.before_request(log_request)
    app.after_request(log_response)

    # saving flask's original error handlers
    flask_handle_exception = app.handle_exception
    flask_handle_user_exception = app.handle_user_exception

    api = Api(app)

    # saving flask-restful's error handlers
    flask_restful_handle_exception = app.handle_exception
    flask_restful_handle_user_exception = app.handle_user_exception

    # setting it so that <500 codes use flask-restful's error handlers,
    # while 500+ codes use original flask's error handlers (for which we
    # register an error handler on somewhere else in this module)
    def handle_exception(flask_method, flask_restful_method, e):
        code = getattr(e, 'code', 500)
        if code >= 500:
            return flask_method(e)
        else:
            return flask_restful_method(e)

    app.handle_exception = functools.partial(
        handle_exception,
        flask_handle_exception,
        flask_restful_handle_exception)
    app.handle_user_exception = functools.partial(
        handle_exception,
        flask_handle_user_exception,
        flask_restful_handle_user_exception)

    endpoint_mapper.setup_resources(api)
    return app
def create_app(configpath):
    app = Flask('Neuronal activity analyzer',
                template_folder='templates',
                static_folder='webgui/static')
    app.config.from_pyfile(configpath)
    app.secret_key = app.config['SECRET_KEY']

    # Create folders if they don't exist
    folders = [app.config['VIDEO_FOLDER'],
               app.config['UPLOAD_FOLDER'],
               app.config['DATA_FOLDER']]
    for folder in folders:
        if not os.path.isdir(folder):
            os.mkdir(folder)

    app.register_blueprint(main_blueprint)
    app.register_blueprint(file_select_blueprint)
    app.register_blueprint(segmentation_blueprint)
    app.register_blueprint(roi_editor_blueprint)
    app.register_blueprint(statistics_blueprint)
    app.register_blueprint(batch_blueprint)

    app.after_request(disable_cache)

    app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False

    compress.init_app(app)

    return app
Beispiel #8
0
def create_app(config):
    app = Flask(__name__)
    app.config.update(config)
    app.after_request(add_cors_header)

    db.app = app
    db.init_app(app)

    # Test API for Tracks
    api = Api(app)

    import wpws.waveplot
    import wpws.track
    import wpws.recording
    import wpws.release
    import wpws.medium
    import wpws.artist_credit
    wpws.waveplot.create_api(api)
    wpws.track.create_api(api)
    wpws.recording.create_api(api)
    wpws.release.create_api(api)
    wpws.medium.create_api(api)
    wpws.artist_credit.create_api(api)

    return app
Beispiel #9
0
def register_after_request_handlers(application: Flask) -> None:
    """
        Register handlers that will be executed after each request.

        :param application: The application instance for which the handlers will be registered.
    """
    application.after_request(_header_x_clacks_overhead)
Beispiel #10
0
def main():
    app = Flask(__name__)

    @app.route("/page/<id>")
    def display_message(id):
        stat_server.users_stat()
        return "Page ID is {} !".format(id)

    app.after_request(log_status_code) # the parameter function will run
    app.run(debug=True)                # after each request
Beispiel #11
0
def create_app(config):
    """
    This method is a factory for our Flask app which configures all the
    necessary behavior and register all the blueprints.

    All our views should belong to a blueprint and the blueprints mounted on
    the main App.

    To run our application you need only to instantiate a app using this
    function, given a config object, and call its run method.

    example:

        datalog_app = create_app(my_config_obj)
        datalog_app.run()

    """
    app = Flask('datalog')
    app.config.from_object(config)

    db = config.get_db()

    def call_end_request(response):
        """
        flush pending mongodb requests
        and return the connection to the poll
        """
        db.connection.end_request()
        return response

    def add_db_to_request():
        """
        makes possible to access the db directly from any view
        (possible, but **not encouraged**, avoid doing this)
        """
        g.db = db

    def permanet_sessions():
        """
        makes the session persistent for
        PERMANENT_SESSION_LIFETIME
        """
        session.permanent = True

    app.before_request(add_db_to_request)
    app.before_request(permanet_sessions)
    app.after_request(call_end_request)

    # register blueprints
    app.register_blueprint(app_views)

    connect_models(config)

    return app
Beispiel #12
0
def setup_app():
    app = Flask(__name__)

    # setting up the app logger with a rotating file handler, in addition to
    #  the built-in flask logger which can be helpful in debug mode.

    additional_log_handlers = [
        RotatingFileHandler(
            config.instance().rest_service_log_path,
            maxBytes=1024*1024*100,
            backupCount=20)
    ]

    app.logger_name = 'manager-rest'
    setup_logger(logger_name=app.logger.name,
                 logger_level=logging.DEBUG,
                 handlers=additional_log_handlers,
                 remove_existing_handlers=False)

    app.before_request(log_request)
    app.after_request(log_response)

    # saving flask's original error handlers
    flask_handle_exception = app.handle_exception
    flask_handle_user_exception = app.handle_user_exception

    api = Api(app)

    # saving flask-restful's error handlers
    flask_restful_handle_exception = app.handle_exception
    flask_restful_handle_user_exception = app.handle_user_exception

    # setting it so that <500 codes use flask-restful's error handlers,
    # while 500+ codes use original flask's error handlers (for which we
    # register an error handler on somewhere else in this module)
    def handle_exception(flask_method, flask_restful_method, e):
        code = getattr(e, 'code', 500)
        if code >= 500:
            return flask_method(e)
        else:
            return flask_restful_method(e)

    app.handle_exception = functools.partial(
        handle_exception,
        flask_handle_exception,
        flask_restful_handle_exception)
    app.handle_user_exception = functools.partial(
        handle_exception,
        flask_handle_user_exception,
        flask_restful_handle_user_exception)

    resources.setup_resources(api)
    return app
Beispiel #13
0
def create_app(config):
    """
    Application Factories - http://flask.pocoo.org/docs/patterns/appfactories/
    :param config: Path to config.py file.
    """

    app = Flask(__name__)
    app.config.from_pyfile(config)
    db.init_app(app)
    api = Api(app)

    from application.json_encoder import AlchemyEncoder
    app.json_encoder = AlchemyEncoder

    # Register middlewares here
    from application.middlewares import require_login, apply_cors_headers
    app.before_request(require_login)
    app.after_request(apply_cors_headers)

    # Register blueprints here
    from application.views import bp as bp_auth
    app.register_blueprint(bp_auth)

    from application.views import UserList, UserResource, GroupList, SubjectList, SubjectSignupList, \
        SubjectSignupResource, TermSignupAction, SettingList
    
    api.add_resource(UserList, '/api/users')
    api.add_resource(UserResource, '/api/users/<int:id>')
    api.add_resource(GroupList, '/api/groups')
    api.add_resource(SubjectList, '/api/subjects')
    api.add_resource(SubjectSignupList, '/api/subjects_signup')
    api.add_resource(SubjectSignupResource, '/api/subjects_signup/<int:subject_id>')
    api.add_resource(TermSignupAction, '/api/terms/signup')
    api.add_resource(SettingList, '/api/settings')

    # Admin panel
    from application.models import User, Group, Subject, Term, TermSignup, Setting
    from application.admin import UserAdminView, SubjectAdminView, TermAdminView, TermSignupAdminView, SettingAdminView

    admin = Admin(app)
    admin.add_view(UserAdminView(User, db.session))
    admin.add_view(ModelView(Group, db.session))
    admin.add_view(SubjectAdminView(Subject, db.session))
    admin.add_view(TermAdminView(Term, db.session))
    admin.add_view(TermSignupAdminView(TermSignup, db.session))
    admin.add_view(SettingAdminView(Setting, db.session))

    return app
Beispiel #14
0
def create_app(config_filename='config.yaml'):
    app = Flask(__name__)
    app.response_class = TextResponse
    app.url_map.converters['sid'] = SIDConverter
    app.url_map.converters['sha1'] = SHA1Converter
    app.url_map.converters['label'] = LabelConverter

    load_yaml(app, config_filename)
    init_db(app)
    init_cache(app)

    app.after_request(cors)

    app.register_blueprint(paste)

    return app
Beispiel #15
0
def create_app(config):
    app = Flask(__name__)
    app.config.update(config)
    app.after_request(add_cors_header)

    db.app = app
    db.init_app(app)

    mail.init_app(app)

    from .index import index_views
    app.register_blueprint(index_views, url_prefix='/internal')

    from .registration import registration_views
    app.register_blueprint(registration_views, url_prefix='/internal')

    return app
def run_app():
	app = Flask(__name__)
	app.config.from_object(__name__)
	app.after_request(add_cors_header)

	"""
	Returns the list of (time, location) for all the meals
	To test using curl, try this command:
	curl -H "Content-Type: application/json" -X POST -d '{"start": "Providence, RI", "end": "San Francisco, CA", "date":"2011-12-01T12:00:00.00Z"}' http://127.0.0.1:5000/journey
	"""
	@app.route('/journey', methods=["GET", "POST"])
	def journey():
		start = request.json["start"]
		end = request.json["end"]
		d = datetime.strptime(request.json["date"], '%Y-%m-%dT%H:%M:%S.%fZ') if request.json["date"] != None else datetime.datetime.today()
		meals = maps.getMeals(start, end, d)
		return json.dumps(meals, default=lambda x: x.isoformat() if hasattr(x, 'isoformat') else x)

	"""
	Returns a dict, containing:
	{
		"path": A polyline, defined as [{latitude: int, longitude: int} ... ],
		"locations":[(timestamp, coordinate) ...]
	}
	To test using curl, try this command:
	curl -H "Content-Type: application/json" -X POST -d '{"start": "Providence, RI", "end": "San Francisco, CA", "date":"2011-12-01T12:00:00.00Z"}' http://127.0.0.1:5000/journeyWithPath
	"""
	@app.route('/journeyWithPath', methods=["GET", "POST"])
	def journeyWithPath():
		start = request.json["start"]
		end = request.json["end"]
		d = datetime.strptime(request.json["date"], '%Y-%m-%dT%H:%M:%S.%fZ') if request.json["date"] != None else datetime.datetime.today()
		meals = maps.getMealsAndPath(start, end, d)
		return json.dumps(meals, default=lambda x: x.isoformat() if hasattr(x, 'isoformat') else x)

	"""
	To test using curl, try this command:
	curl -H "Content-Type: application/json" -X POST -d '{"lat": 41.8236, "lng": -71.4222}' http://127.0.0.1:5000/restaurants
	"""
	@app.route('/restaurants', methods=["GET", "POST"])
	def restaurants():
		coords = request.json
		rests = get_restaurants_from_coordinate(coords)
		return json.dumps(rests, default=lambda x: x.isoformat() if hasattr(x, 'isoformat') else x)

	app.run()
Beispiel #17
0
def create_app(config):
    app = Flask(__name__)

    app.config.update(config)
    app.after_request(add_cors_header)

    global db
    db.app = app
    db.init_app(app)

    global manager
    manager.init_app(app, flask_sqlalchemy_db=db)

    manager.create_api(ws.schema.Annotation, methods=['GET'])
    manager.create_api(ws.schema.Application, methods=['GET'])

    manager.create_api(ws.schema.Area, methods=['GET'], primary_key='gid')
    manager.create_api(ws.schema.AreaType, methods=['GET'])

    manager.create_api(ws.schema.Artist, methods=['GET'], primary_key='gid')
    manager.create_api(ws.schema.ArtistType, methods=['GET'])
    manager.create_api(ws.schema.ArtistCredit, methods=['GET'])


    manager.create_api(ws.schema.Edit, methods=['GET'])
    manager.create_api(ws.schema.Editor, methods=['GET'])

    manager.create_api(ws.schema.Gender, methods=['GET'])

    manager.create_api(ws.schema.Language, methods=['GET'])

    manager.create_api(ws.schema.Recording, methods=['GET'])

    manager.create_api(ws.schema.Release, methods=['GET'], primary_key='gid', include_methods=['url'])
    manager.create_api(ws.schema.ReleasePackaging, methods=['GET'])
    manager.create_api(ws.schema.ReleaseStatus, methods=['GET'])

    manager.create_api(ws.schema.ReleaseGroup, methods=['GET'], primary_key='gid')
    manager.create_api(ws.schema.ReleaseGroupPrimaryType, methods=['GET'], primary_key='gid')

    manager.create_api(ws.schema.Script, methods=['GET'])

    manager.create_api(ws.schema.Work, methods=['GET'])
    manager.create_api(ws.schema.WorkType, methods=['GET'])

    return app
Beispiel #18
0
def create_application(name = __name__, env = 'testing'):
    
    app = Flask(__name__, static_path = '/static')

    # Load our default configuration
    load_configuration(app, env)
            
    # Setup Mail
    mail.init_app(app)
    
    # Setup OAuth2 Provider
    oauth.init_app(app)

    # Load our application's blueprints
    load_blueprints(app)

    rq.init_app(app)

    """
    Setup Flask Security 
    
    We cannot load the security information until after our blueprints
    have been loaded into our application.
    """
    from CommonsCloudAPI.models.user import user_datastore
    security.init_app(app, user_datastore)
    
    # Initialize our database and create tables
    db.init_app(app)
    db.app = app
    db.create_all()

    # Load default application routes/paths
    load_errorhandlers(app)

    def add_cors_header(response):
        response.headers['Access-Control-Allow-Origin'] = '*'
        response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, PATCH, DELETE, OPTIONS'
        response.headers['Access-Control-Allow-Headers'] = 'Authorization, Accept, Content-Type, X-Requested-With, Origin, Access-Control-Request-Method, Access-Control-Request-Headers, Cache-Control, Expires, Set-Cookie'
        response.headers['Access-Control-Allow-Credentials'] = True
        return response

    app.after_request(add_cors_header)

    return app
def create_app(config_name):
    """
    Flask app factory
    """
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    api = Api()
    db.init_app(app)

    from .resources import MonsterResource, MonsterListResource

    api.add_resource(MonsterListResource, '/monsters', endpoint='monsters')
    api.add_resource(MonsterResource, '/monster/<int:id>', endpoint='monster')
    api.init_app(app)
    app.after_request(add_cors_headers)

    return app
Beispiel #20
0
def create_app():
    app = Flask(__name__)
    app.config.from_object('polipoly2.default_settings')
    app.config.from_envvar('POLIPOLY2_SETTINGS', silent=True)

    register_converters(app)

    init_engine(app.config['DATABASE_URI'])

    def shutdown_session(response):
        session.remove()
        return response

    app.after_request(shutdown_session)

    from polipoly2.views import views
    app.register_module(views)

    return app
Beispiel #21
0
def create_app(config_file):
    """ Create the webservice application using the configuration provided in
    config_file, and initialize SQLAlchemy, Redis and OAuth services. Also
    installs webservice routes.
    """

    app = Flask(__name__.split(".")[0])
    app.config.from_pyfile(config_file)
    app.after_request(add_cors_header)

    # Initialize Flask extensions
    api = Api(app)
    db.init_app(app)
    cache.init_app(app)
    oauth_provider.init_app(app)

    # Initialize OAuth handler
    import bbws.oauth

    bbws.oauth.init(app)

    # Initialize custom endpoints
    import bbws.custom

    bbws.custom.init(app)

    # Initialize webservice routes
    import bbws.entity
    import bbws.revision
    import bbws.user
    import bbws.entityspecific
    import bbws.relationship
    import bbws.musicbrainz

    bbws.entity.create_views(api)
    bbws.revision.create_views(api)
    bbws.user.create_views(api)
    bbws.entityspecific.create_views(api)
    bbws.relationship.create_views(api)
    bbws.musicbrainz.create_views(api)

    return app
Beispiel #22
0
def create_app(config_obj=None):
    """
    Create a Flask application object.

    :return: a Flask application object
    :rtype: flask.Flask
    """
    app = Flask(__name__)
    if config_obj:
        app.config.from_object(config_obj)
    else:
        load_config(app)

    if app.config['ENV'] != 'development':
        if app.config['SECRET_KEY'] == 'replace-me-with-something-random':
            raise RuntimeError('You need to change the SECRET_KEY configuration for production')
    for config in ('AD_DOMAIN', 'AD_LDAP_URI', 'AD_USERS_GROUP', 'AD_ADMINS_GROUP',
                   'AD_SERVICE_USERNAME', 'AD_SERVICE_PASSWORD', 'SQLALCHEMY_DATABASE_URI'):
        if not app.config.get(config):
            raise RuntimeError('You need to set the "{0}" setting'.format(config))

    init_logging(app)
    db.init_app(app)
    migrations_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'migrations')
    Migrate(app, db, directory=migrations_dir)
    app.cli.command()(create_db)

    for status_code in default_exceptions.keys():
        app.register_error_handler(status_code, json_error)
    app.register_error_handler(ValidationError, json_error)
    app.register_error_handler(ConfigurationError, json_error)
    app.register_error_handler(ADError, json_error)

    app.after_request(insert_headers)
    app.register_blueprint(api_v1, url_prefix='/api/v1')

    jwt = JWTManager(app)
    jwt.token_in_blacklist_loader(BlacklistedToken.is_token_revoked)
    jwt.user_claims_loader(add_jwt_claims)
    app.cli.command()(prune_blacklisted_tokens)

    return app
Beispiel #23
0
def create_app(config):
    """
    This method is a factory for our Flask app which configures all the
    necessary behavior and register all the blueprints.

    All our views should belong to a blueprint and the blueprints mounted on
    the main App.

    To run our application you need only to instantiate a app using this
    function, given a config object, and call its run method.

    example:

        komoo_app = create_app(my_config_obj)
        komoo_app.run()

    """
    app = Flask('komoo')
    app.config.from_object(config)

    db = config.get_db()

    # flush pending mongodb requests
    def call_end_request(response):
        db.connection.end_request()
        return response

    # makes possible to access the db directly from any view
    # (possible, but **not encouraged**, avoid doing this)
    def add_db_to_request():
        g.db = db

    app.before_request(add_db_to_request)
    app.after_request(call_end_request)

    # register all blueprints
    for bp in blueprints:
        app.register_blueprint(bp[0], url_prefix=bp[1])

    return app
Beispiel #24
0
    def app(self):
        """ derive flask app based on the combination of command-line
            options and the contents of the .ini files
        """

        ## set flask specific things that are non-optional
        error = lambda k: 'Fatal: You need to specify a "flask" section ' + \
                'with an entry like  "'+k+'=..." in your .ini file'
        try: app_name = self['flask.app']
        except KeyError: raise SystemExit(error('app'))
        try: secret_key = self['flask.secret_key']
        except KeyError: raise SystemExit(error('secret_key'))
        app = Flask(app_name)
        app.secret_key = secret_key

        ## set flask specific things that are optional
        if 'flask.template_path' in self:
            app.jinja_loader = FileSystemLoader(self['template_path'])
        if 'flask.before_request' in self:
            before_request = self['flask.before_request']
            before_request = namedAny(before_request)
            app.before_request(before_request)
        if 'flask.after_request' in self:
            after_request = self['flask.after_request']
            after_request = namedAny(after_request)
            app.after_request(after_request)

        ## setup views
        try: view_holder = self['corkscrew.views']
        except KeyError:
            error = 'Fatal: could not "view=<dotpath>" entry in your .ini file'
            raise SystemExit(error)
        else:
            view_list = namedAny(view_holder)
            [ v(app=app, settings=self) for v in view_list]

            return app
redis_server = redis.StrictRedis(
        host=redis_url.hostname,
        port=redis_url.port,
        password=redis_url.password
)

store = RedisStore(redis_server)
kv_store = KVSessionExtension(store, app)

Health(app, checks=[db.health])

# Audit, error handling and after_request headers all handled by lrutils
Audit(app)
ErrorHandler(app)
app.after_request(eh_after_request)

if not app.debug:
    app.logger.addHandler(logging.StreamHandler())
    app.logger.setLevel(logging.INFO)

if app.config.get('BASIC_AUTH_USERNAME'):
    app.config['BASIC_AUTH_FORCE'] = True
    basic_auth = BasicAuth(app)

# Sentry exception reporting
if 'SENTRY_DSN' in os.environ:
    sentry = Sentry(app, dsn=os.environ['SENTRY_DSN'])

app.logger.debug("\nConfiguration\n%s\n" % app.config)
Beispiel #26
0
app.register_blueprint(shield_code, url_prefix="/shield")
app.register_blueprint(donate_coin, url_prefix="/donate")
app.register_blueprint(izhero_story, url_prefix="/izstory")
app.register_blueprint(coinlog, url_prefix="/coinlog")
app.register_blueprint(comic_shelf, url_prefix="/comic")
app.register_blueprint(gallery_sticker, url_prefix="/gallery")
app.register_blueprint(izhero_ann, url_prefix="/news")
app.register_blueprint(game_shelf, url_prefix="/games")
app.register_blueprint(iz_encyclopedia, url_prefix="/encyclopedia")
app.register_blueprint(iz_encycloarticle, url_prefix="/encyclopedia/pages")
app.register_blueprint(facebook, url_prefix="/share")
app.register_blueprint(card_shelf, url_prefix="/cards")
app.register_blueprint(dqmission_progress, url_prefix="/dqmissions")
app.register_blueprint(survey, url_prefix="/dqsurveys/item")
app.register_blueprint(answer, url_prefix="/dqsurveys/answer")
app.register_blueprint(dq_messenger, url_prefix="/messengers")
app.register_blueprint(dq_messengerlog, url_prefix="/messages")
app.register_blueprint(izhero_sub, url_prefix="/subscribe")
app.register_blueprint(survey_rcode, url_prefix="/dqresult")
app.register_blueprint(api_member, url_prefix="/memberships")
app.after_request(nocache)
Auth(app, is_mgo=True, userdb="IZHero", loader_name="user.js", loader_full=True, bp_prefix="/acct")
Upload(app, public_folders=["stickers", "comics", "encyclopedia", "lessons", "resources", "certificate"])
Drawing(app)
Certificate(app)
app.mandrill = Mandrill(app)

if __name__ == "__main__":
    raise Exception('Execute run.py instead')

Beispiel #27
0

def render_rst(content):
    input_file = StringIO(content)
    parser = ReStructuredTextParser()
    document_tree = parser.parse(input_file)
    document = Article(document_tree, OPTIONS, backend=pdf)
    pdf_output = BytesIO()
    document.render(file=pdf_output)
    pdf_output.seek(0)
    return pdf_output


ALLOW_ORIGIN = '*' if DEV_MODE else 'http://www.opqode.com'


def article_allow_origin(response):
    if request.path == '/wake':
        response.headers.add('Access-Control-Allow-Origin', ALLOW_ORIGIN)
    return response


app.after_request(article_allow_origin)


if __name__ == '__main__':
    app.run(debug=True)
else:
    os.chdir(os.path.dirname(__file__))

def create_app():
    from config import configs

    application = Flask(__name__)

    application.config.from_object(configs[os.environ["NOTIFY_ENVIRONMENT"]])

    init_app(application)
    statsd_client.init_app(application)
    logging.init_app(application, statsd_client)
    init_csrf(application)
    request_id.init_app(application)

    service_api_client.init_app(application)
    user_api_client.init_app(application)
    api_key_api_client.init_app(application)
    job_api_client.init_app(application)
    notification_api_client.init_app(application)
    status_api_client.init_app(application)
    invite_api_client.init_app(application)
    template_statistics_client.init_app(application)
    events_api_client.init_app(application)
    provider_client.init_app(application)
    organisations_client.init_app(application)

    login_manager.init_app(application)
    login_manager.login_view = "main.sign_in"
    login_manager.login_message_category = "default"
    login_manager.session_protection = None

    from app.main import main as main_blueprint

    application.register_blueprint(main_blueprint)

    from .status import status as status_blueprint

    application.register_blueprint(status_blueprint)

    proxy_fix.init_app(application)

    application.session_interface = ItsdangerousSessionInterface()

    application.add_template_filter(format_datetime)
    application.add_template_filter(format_datetime_24h)
    application.add_template_filter(format_datetime_normal)
    application.add_template_filter(format_datetime_short)
    application.add_template_filter(format_time)
    application.add_template_filter(syntax_highlight_json)
    application.add_template_filter(valid_phone_number)
    application.add_template_filter(linkable_name)
    application.add_template_filter(format_date)
    application.add_template_filter(format_date_normal)
    application.add_template_filter(format_date_short)
    application.add_template_filter(format_datetime_relative)
    application.add_template_filter(format_delta)
    application.add_template_filter(format_notification_status)
    application.add_template_filter(format_notification_status_as_time)
    application.add_template_filter(format_notification_status_as_field_status)
    application.add_template_filter(format_notification_status_as_url)

    application.after_request(useful_headers_after_request)
    application.after_request(save_service_after_request)
    application.before_request(load_service_before_request)

    @application.context_processor
    def _attach_current_service():
        return {"current_service": current_service}

    register_errorhandlers(application)

    setup_event_handlers()

    return application
Beispiel #29
0
Datei: app.py Projekt: maya/cfapi
app = Flask(__name__)
heroku = Heroku(app)
db = SQLAlchemy(app)
make_class_dictable(db.Model)

# -------------------
# Settings
# -------------------

def add_cors_header(response):
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Headers'] = 'Authorization, Content-Type'
    response.headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, PATCH, DELETE, OPTIONS'
    return response

app.after_request(add_cors_header)


# -------------------
# Types
# -------------------

class JsonType(Mutable, types.TypeDecorator):
    ''' JSON wrapper type for TEXT database storage.

        References:
        http://stackoverflow.com/questions/4038314/sqlalchemy-json-as-blob-text
        http://docs.sqlalchemy.org/en/rel_0_9/orm/extensions/mutable.html
    '''
    impl = types.Unicode
Beispiel #30
0
def create_app(config='config.ProductionDevelopmentConfig', apptype='profi'):
    app = Flask(__name__, static_folder='./static')

    app.config.from_object(config)

    app.teardown_request(close_database)

    app.debug = app.config['DEBUG'] if 'DEBUG' in app.config else False
    app.testing = app.config['TESTING'] if 'TESTING' in app.config else False

    app.before_request(load_database(app.config['SQLALCHEMY_DATABASE_URI']))
    app.before_request(lambda: load_user(apptype))
    app.before_request(setup_authomatic(app))

    def add_map_headers_to_less_files(response):
        response.headers.add('Access-Control-Allow-Origin', '*')
        if request.path and re.search(r'\.css$', request.path):
            mapfile = re.sub(r'\.css$', r'.css.map', request.path)
            if os.path.isfile(os.path.realpath(os.path.dirname(__file__)) + mapfile):
                response.headers.add('X-Sourcemap', mapfile)
        return response

    app.after_request(add_map_headers_to_less_files)

    @login_manager.user_loader
    def load_user_manager(user_id):
        return g.db.query(User).get(user_id)

    # if apptype in ['file', 'profi', 'static', 'front']:

    session_opts = {
        'session.type': 'ext:memcached',
        'session.cookie_domain': '.' + Config.MAIN_DOMAIN,
        'session.url': 'memcached.profi:11211'
    }

    class BeakerSessionInterface(SessionInterface):
        def open_session(self, app, request):
            return request.environ.get('beaker.session')

        def save_session(self, app, session, response):
            session.save()

    app.wsgi_app = SessionMiddleware(app.wsgi_app, session_opts)
    app.session_interface = BeakerSessionInterface()

    app.type = apptype
    login_manager.init_app(app)
    login_manager.session_protection = 'basic'

    if apptype == 'front':

        # relative paths
        def join_path(template, parent):
            return os.path.join(os.path.dirname(parent), template)

        app.jinja_env.join_path = join_path

        def load_portal():
            from profapp.models.portal import Portal
            portal = g.db.query(Portal).filter_by(host=request.host).first()
            g.portal = portal if portal else None
            g.portal_id = portal.id if portal else None
            g.portal_layout_path = portal.layout.path if portal else ''
            g.lang = g.portal.lang if g.portal else g.user_dict['lang'] if portal else 'en'

        app.before_request(load_portal)
        from profapp.controllers.blueprints_register import register_front as register_blueprints_front
        register_blueprints_front(app)
        update_jinja_engine(app)

        @app.errorhandler(404)
        def page_not_found(e):

            from flask import Flask, render_template
            from profapp.controllers.views_front import error_404
            return error_404()

    elif apptype == 'static':
        from profapp.controllers.blueprints_register import register_static as register_blueprints_static
        register_blueprints_static(app)
    elif apptype == 'file':
        from profapp.controllers.blueprints_register import register_file as register_blueprints_file
        register_blueprints_file(app)
    else:
        from profapp.controllers.blueprints_register import register_profi as register_blueprints_profi
        register_blueprints_profi(app)
        update_jinja_engine(app)

    if apptype in ['profi', 'front']:
        bootstrap.init_app(app)
        mail.init_app(app)

    return app