Пример #1
0
def create_app(config='config.ProductionDevelopmentConfig'):
    app = Flask(__name__)

    app.config.from_object(config)

    db.init_app(app)

    mixer.init_app(app)

    app.before_request(setup_authomatic(app))
    app.before_request(load_user)

    app.add_url_rule('/', 'index', index)

    app.register_blueprint(auth_bp, url_prefix='/auth')
    app.register_blueprint(issues_bp, url_prefix='/issues')
    app.register_blueprint(comments_bp, url_prefix='/comments')
    app.register_blueprint(organizations_bp, url_prefix='/organizations')

    admin = Admin(app)

    # add admin views.
    admin.add_view(AdminView(User, db.session))
    admin.add_view(AdminView(Issue, db.session))
    admin.add_view(AdminView(Comment, db.session))
    admin.add_view(AdminView(Organization, db.session))
    admin.add_view(AdminView(Vote, db.session))

    return app
Пример #2
0
def create_app():
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)

    app.config.from_object(Configuration)
    app.config["PERMANENT_SESSION_LIFETIME"] = datetime.timedelta(days=4000)

    db.init_app(app.config.get("LOCAL_DYNAMODB"), prefix=app.config["TABLE_PREFIX"])

    CORS(app, supports_credentials=True)

    mastodon_bp = make_mastodon_blueprint(
        app.config["SERVICE_NAME"],
        scope="read",
        instance_credentials_backend=OAuthDynamoDbMemoryBackend(),
    )
    app.register_blueprint(mastodon_bp, url_prefix="/login")

    app.before_request(populate_actor_info)

    app.register_blueprint(site, url_prefix="/")
    app.register_blueprint(groupAPI, url_prefix="/api")
    app.register_blueprint(groupViews, url_prefix="/group")

    return app
Пример #3
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
Пример #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
Пример #5
0
def register_before_request_handlers(application: Flask) -> None:
    """
        Register handlers that will be executed before each request.

        :param application: The application instance for which the handlers will be registered.
    """
    application.before_request(_extend_global_variable)
Пример #6
0
def includeme(config):
    app = Flask('annotator')  # Create the annotator-store app
    app.register_blueprint(store.store)  # and register the store api.

    # Set up the models
    settings = config.get_settings()
    if 'es.host' in settings:
        app.config['ELASTICSEARCH_HOST'] = settings['es.host']
    if 'es.index' in settings:
        app.config['ELASTICSEARCH_INDEX'] = settings['es.index']
    es.init_app(app)
    with app.test_request_context():
        Annotation.create_all()
        Document.create_all()

    # Configure authentication and authorization
    app.config['AUTHZ_ON'] = True
    app.before_request(before_request)

    # Configure the API views -- version 1 is just an annotator.store proxy
    api_v1 = wsgiapp2(app)

    config.add_view(api_v1, route_name='api')

    if not config.registry.queryUtility(interfaces.IStoreClass):
        config.registry.registerUtility(Store, interfaces.IStoreClass)
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
Пример #8
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
Пример #9
0
def create_app(config_name = 'default'):
    app = Flask(__name__, static_folder='static', static_url_path='')
    app.config.from_object(config[config_name])
    app.debug = True
    config[config_name].init_app(app)

    db.init_app(app)

    # attach routes and custom error pages here
    from hacer.api import api as api_blueprint
    app.register_blueprint(api_blueprint, url_prefix='/api')

    @app.route('/')
    def index():
        return app.send_static_file('index.html')

    # start discovery server
    with app.app_context():
        from discovery import run_discovery_server
        app.discovery_thread = Thread(target=run_discovery_server, kwargs={ "Session": scoped_session(sessionmaker(bind=db.engine)) })
        app.discovery_thread.daemon = True
        app.discovery_thread.start()

    app.before_request(create_before_request(app))
    return app
Пример #10
0
def create_app(settings_override=None):
    """Returns a `Flask` application instance configured.
    """

    app = Flask(__name__, instance_relative_config=True)

    app.config.from_object('fki_challenge.settings')
    app.config.from_pyfile('application.cfg', silent=True)
    app.config.from_object(settings_override)

    api = Api(app, prefix='/api', catch_all_404s=True)

    # ensure tables
    models.database.init(app.config['FKI_DATABASE_FILE'])
    models.database.connect()
    models.database.create_tables([models.Attribute, models.Person, models.PersonAttribute],
                                  safe=True)

    # register db request hooks
    app.before_request(_db_connect)
    app.teardown_request(_db_close)

    # wire resources
    api.add_resource(resources.Attribute, '/attributes/<int:attribute_id>')
    api.add_resource(resources.AttributeList, '/attributes/')
    api.add_resource(resources.Person, '/persons/<int:person_id>')
    api.add_resource(resources.PersonList, '/persons/')
    api.add_resource(resources.MatchList, '/matches/',
                     resource_class_kwargs={'error_rate': app.config['FKI_ERROR_RATE']})

    return app
class BaseOpenstackDummy(Resource):
    """
    This class is the base class for all openstack entrypoints of son-emu.
    """

    def __init__(self, listenip, port):
        self.ip = listenip
        self.port = port
        self.compute = None
        self.manage = None
        self.playbook_file = '/tmp/son-emu-requests.log'
        with open(self.playbook_file, 'w'):
            pass

        # setup Flask
        self.app = Flask(__name__)
        self.api = Api(self.app)

    def _start_flask(self):
        LOG.info("Starting %s endpoint @ http://%s:%d" % (__name__, self.ip, self.port))
        if self.app is not None:
            self.app.before_request(self.dump_playbook)
            self.app.run(self.ip, self.port, debug=True, use_reloader=False)

    def dump_playbook(self):
        with self.manage.lock:
            with open(self.playbook_file, 'a') as logfile:
                if len(request.data) > 0:
                    data = "# %s API\n" % str(self.__class__).split('.')[-1].rstrip('\'>')
                    data += "curl -X {type} -H \"Content-type: application/json\" -d '{data}' {url}".format(type=request.method,
                                                                                            data=request.data,
                                                                                            url=request.url)
                    logfile.write(data + "\n")
Пример #12
0
def create_app(config_file):
    app = Flask(__name__)

    # configuration settings are loaded from the `config.py` module
    # and (optionally) from a file `XSNIPPET_SETTINGS` env var points to
    app.config.from_pyfile(config_file)
    app.config.from_envvar('XSNIPPET_WEBUI_SETTINGS', silent=True)

    # set jinja2 global vars to be used in all templates
    app.jinja_env.globals.update(
        {
            "title": app.config["TITLE"],
            "abs_url_for": abs_url_for,
            "lang_by_short_name": lang_by_short_name
        }
    )
    # set assets env
    assets.Environment(app)

    app.register_blueprint(webui)

    # register all needed hooks
    app.before_request(create_http_object)

    # create cache connection (it's thread-safe)
    app.cache = create_cache_connection(app, key_prefix="webui_")

    return app
Пример #13
0
def create_app():
    # 创建flask app
    app = Flask(__name__)

    # 加载配置
    from .config import Config
    from .extensions import db, markdown
    from .lang import text
    from .helper import siteconfig, categories, menus
    from . import lang

    app.config.from_object(Config)
    db.init_app(app)
    lang.setup(app.config.get('LANGUAGE', 'en_GB'))
    app.jinja_env.globals.update(__=text)
    app.jinja_env.globals.update(site=siteconfig, site_categories=categories, menus=menus, enumerate=enumerate)
    app.jinja_env.filters['markdown'] = markdown.convert

    # 注册蓝图
    from .controller import admin_bp, site_bp
    from .views import home
    app.register_blueprint(admin_bp)
    app.register_blueprint(site_bp)
    app.register_blueprint(home)

    # 注册钩子方法
    app.before_request(init_user)

    return app
Пример #14
0
class ChainApi(Resource):
    """
    The chain API is a component that is not used in OpenStack.
    It is a custom built REST API that can be used to create network chains and loadbalancers.
    """

    def __init__(self, inc_ip, inc_port, manage):
        # setup Flask
        self.app = Flask(__name__)
        self.api = Api(self.app)
        self.ip = inc_ip
        self.port = inc_port
        self.manage = manage
        self.playbook_file = '/tmp/son-emu-requests.log'
        self.api.add_resource(ChainVersionsList, "/",
                              resource_class_kwargs={'api': self})
        self.api.add_resource(ChainList, "/v1/chain/list",
                              resource_class_kwargs={'api': self})
        self.api.add_resource(ChainVnfInterfaces, "/v1/chain/<src_vnf>/<src_intfs>/<dst_vnf>/<dst_intfs>",
                              resource_class_kwargs={'api': self})
        self.api.add_resource(ChainVnfDcStackInterfaces,
                              "/v1/chain/<src_dc>/<src_stack>/<src_vnf>/<src_intfs>/<dst_dc>/<dst_stack>/<dst_vnf>/<dst_intfs>",
                              resource_class_kwargs={'api': self})
        self.api.add_resource(BalanceHostList, "/v1/lb/list",
                              resource_class_kwargs={'api': self})
        self.api.add_resource(BalanceHost, "/v1/lb/<vnf_src_name>/<vnf_src_interface>",
                              resource_class_kwargs={'api': self})
        self.api.add_resource(BalanceHostDcStack, "/v1/lb/<src_dc>/<src_stack>/<vnf_src_name>/<vnf_src_interface>",
                              resource_class_kwargs={'api': self})
        self.api.add_resource(QueryTopology, "/v1/topo",
                              resource_class_kwargs={'api': self})
        self.api.add_resource(Shutdown, "/shutdown")

        @self.app.after_request
        def add_access_control_header(response):
            response.headers['Access-Control-Allow-Origin'] = '*'
            return response

    def _start_flask(self):
        logging.info("Starting %s endpoint @ http://%s:%d" % ("ChainDummyApi", self.ip, self.port))
        if self.app is not None:
            self.app.before_request(self.dump_playbook)
            self.app.run(self.ip, self.port, debug=True, use_reloader=False)

    def dump_playbook(self):
        with self.manage.lock:
            with open(self.playbook_file, 'a') as logfile:
                data = "# CHAIN API\n"
                if len(request.data) > 0:
                    data += "curl -X {type} -H \"Content-type: application/json\" -d '{data}' {url}".format(type=request.method,
                                                                                        data=request.data,
                                                                                        url=request.url)
                else:
                    data += "curl -X {type} -H \"Content-type: application/json\" {url}".format(
                        type=request.method,
                        url=request.url)
                logfile.write(data + "\n")
def test_noninstrospectable_hooks_dont_crash_everything():
    app = Flask(__name__)

    def do_nothing():
        pass

    app.before_request(partial(do_nothing))

    # It'd crash here
    FlaskInjector(app=app)
Пример #16
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
Пример #17
0
def create_app(config={}):
    app = Flask(__name__)
    app.config.from_object('App.config_dev')
    app.config.update(config)
    db.init_app(app)

    register_all_views(app)
    login_manager.init_app(app)
    app.before_request(before_request)

    return app
Пример #18
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
Пример #19
0
def create_app(config=None):
    app = Flask(__name__)
    app.name = APP_NAME

    app.config.update(default_config)
    if config is not None:
        app.config.update(config)

    app.before_request(ensure_session)
    app.register_blueprint(api.blueprint)

    return app
Пример #20
0
def create_app():
  app = Flask(__name__)
  app.config.from_object('doc_indexer.config')

  # Flask-SQLAlchemy
  db.init_app(app)
  app.before_request(db_start_session)
  app.teardown_request(db_commit_session)

  # Flask-Uploads
  configure_uploads(app, (document_uploads,))

  register_blueprints(app)
  return app
Пример #21
0
    def test_requestdebugging(self):

        custom_app = Flask(__name__)
        custom_app.before_request(log_request)

        @custom_app.route('/foo')
        def foo():
            return ''

        with custom_app.test_request_context('/foo'):
            with custom_app.test_client() as client:
                with patch('flask.current_app.logger.debug') as mocked_debug:
                    client.get('/foo')

        self.assertEqual(mocked_debug.call_count, 1)
Пример #22
0
def _create_app(config):
    app = Flask(__name__)
    api = ExceptionHandlingApi(app)
    api_doc_route = '/api-docs'

    api.add_resource(DataSetSearchResource, config.app_base_path)
    api.add_resource(ApiDoc, api_doc_route)
    api.add_resource(MetadataEntryResource, config.app_base_path + '/<entry_id>')
    api.add_resource(DataSetCountResource, config.app_base_path + '/count')
    api.add_resource(ElasticSearchAdminResource, config.app_base_path + '/admin/elastic')

    security = Security(auth_exceptions=[api_doc_route])
    app.before_request(security.authenticate)

    return app
Пример #23
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
Пример #24
0
def init_app():
    app = Flask(__name__)
    app.config.from_object(config)
    app.before_request(get_current_user)
    app.before_request(db_session)
    blueprints = Blueprints(app)
    app = blueprints.register()
    login_manager.init_app(app)
    mail = Mail(app)
    Base = declarative_base()
    db = SQLAlchemy(app)

    class UserModify(db.Model, User):
        pass
    db_adapter = SQLAlchemyAdapter(db, UserModify)
    user_manager = UserManager(db_adapter, app)
    return app
Пример #25
0
class RestProvider(APIProvider):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.app = Flask("iris-rest")

        # Make sure we have config
        if 'rest' not in self.daemon.config.providers:
            raise Exception("No config for RestProvider (need config.providers.rest)")

        self.config = self.daemon.config.providers['rest']

        # Grab config vars
        self.host = self.config.get("host", "0.0.0.0")
        self.port = self.config.get("port", "8080")
        self.auth = self.config.get("auth")

        # Meta Registers
        self.app.register_error_handler(APIBase, self.handle_response)
        self.app.before_request(self.before_request)

        self.app.add_url_rule('/', 'index', self.route_index)

        # Controllers
        self.app.register_blueprint(ShardController(self).bp)
        self.app.register_blueprint(EntryController(self).bp)

    def before_request(self):
        if self.auth and request.headers.get("IRIS_AUTH") != self.auth:
            raise APIError("Invalid Credentials", 1000)

    def handle_response(self, obj):
        return jsonify(obj.data)

    def run(self):
        super().run()
        self.app.run(host=self.host, port=self.port)

    def route_index(self):
        raise APIResponse({
            "stats": {
                "uptime": float("{0:.4f}".format(time.time() - self.daemon.start_time)),
            },
            "version": __VERSION__
        })
Пример #26
0
def includeme(config):
    """Include the annotator-store API backend.

    Example INI file:

        [app:h]
        consumer_key: primary_consumer
        consumer_secret: 00000000-0000-0000-0000-000000000000

    """

    settings = config.get_settings()

    if not settings.has_key('h.consumer_key'):
        raise KeyError('h.consumer_key')

    if not settings.has_key('h.consumer_secret'):
        raise KeyError('h.consumer_secret')

    # Create the annotator-store app
    app = Flask(__name__)
    app.register_blueprint(store.store)

    # Set up the models
    es.init_app(app)
    with app.test_request_context():
        try:
            Annotation.create_all()
        except:
            Annotation.update_settings()
            Annotation.create_all()

    # Configure authentication (ours) and authorization (store)
    authenticator = auth.Authenticator(consumer_fetcher)
    def before_request():
        g.auth = authenticator
        g.authorize = authz.authorize
    app.before_request(before_request)

    # Configure the API views
    config.add_view(wsgiapp2(app), route_name='api')
    config.add_view(token, route_name='token', permission='authenticated')
    config.add_view(users, route_name='users', request_method='GET',
                    permission='authenticated',
                    renderer='json')
Пример #27
0
Файл: eapp.py Проект: Inkvi/ella
def create_app():
    app = Flask(__name__)
    with open('/etc/ella/settings.yml') as f:
        app.config.update(**yaml.load(f))

    ELLIPTICS_HOSTNAME = app.config.get('ELLIPTICS_HOSTNAME')

    if ELLIPTICS_HOSTNAME:
        app.node = init_elliptics(ELLIPTICS_HOSTNAME)
    else:
        app.before_request(before)

    app.add_url_rule('/', 'home', view_func=views.home, methods=['GET', 'POST'])
    app.add_url_rule('/routing', view_func=views.routing)
    app.add_url_rule('/stats', view_func=views.stats)
    app.add_url_rule('/find', view_func=views.find)
    app.add_url_rule('/download/<string:key>', view_func=views.download)
    return app
Пример #28
0
def create_app(config_object=None):
    app = Flask(__name__)

    app.config.from_object('config.default')
    if config_object:
        app.config.from_object(config_object)

    app.add_url_rule('/', view_func=views.get_apps, methods=['GET'])
    app.add_url_rule('/login', view_func=views.get_login, methods=['GET'])
    app.add_url_rule('/login', view_func=views.do_login, methods=['POST'])
    app.add_url_rule('/logout', view_func=views.do_logout, methods=['GET'])
    app.add_url_rule('/deploy', view_func=views.do_deploy, methods=['POST'])
    app.add_url_rule('/ping/ping', view_func=views.healthcheck, methods=['GET'])
    app.register_error_handler(WBAPIHTTPError, views.wb_error_handler)
    app.register_error_handler(Exception, views.generic_error_handler)
    app.before_request(get_api_before_request)

    return app
Пример #29
0
def test_enforce_auth():
    app = Flask(__name__)
    app.config['AUTH_KEY'] = 'secretpassword'

    app.before_request(corral.util.enforce_auth)

    @app.route('/admin')
    def admin_panel():
        return 'Admin panel.\n'

    with app.test_client() as c:
        rv = c.get('/admin')
        assert b'You must be authenticated' in rv.data
        assert rv.status_code == 403

        rv = c.get('/admin', headers={'Cookie': 'key=secretpassword'})
        assert rv.data == b'Admin panel.\n'
        assert rv.status_code == 200
Пример #30
0
def test_detect_auth():
    app = Flask(__name__)
    app.config['AUTH_KEY'] = 'secretpassword'

    app.before_request(corral.util.detect_auth)

    @app.route('/checkauth')
    def check_auth():
        return jsonify({'authed': g.authed})

    with app.test_client() as c:
        rv = c.get('/checkauth')
        data = json.loads(rv.data.decode('utf-8'))
        assert data['authed'] == False

        rv = c.get('/checkauth', headers={'Cookie': 'key=secretpassword'})
        data = json.loads(rv.data.decode('utf-8'))
        assert data['authed'] == True