Ejemplo n.º 1
0
class ApplicationContext:
    BLUEPRINTS = [
        ("game", game_blueprint),
        ("record", record_blueprint),
        ("template", template_blueprint),
    ]

    def __init__(self, app):
        self.config = configure()

        self.__initialize_app(app)
        self.__initialize_csrf(app)
        self.__initialize_healthcheck(app)
        self.__initialize_mongo(app)
        self.__initialize_daos()
        self.__initialize_services()
        self.__initialize_auth(app)
        self.__register_blueprints(app)
        self.__register_error_handlers(app)

    def __initialize_app(self, app):
        self.config["REMEMBER_COOKIE_DURATION"] = timedelta(
            days=self.config.get('remember_cookie_duration_days', 365))
        app.config.update(self.config)

    def __initialize_healthcheck(self, app):
        healthcheck_endpoint = self.config["endpoint_prefixes"]["healthcheck"]
        LOGGER.debug(
            f"Setting up healthcheck endpoint at {healthcheck_endpoint}")
        health = HealthCheck(app, healthcheck_endpoint)

        def mongo_okay():
            db = get_db()
            stats = db.command("dbstats")
            return bool(stats["ok"]), "Mongo Database is UP" if stats[
                "ok"] else "ERROR: Mongo Database is DOWN"

        health.add_check(mongo_okay)

    def __initialize_csrf(self, app):
        self.csrf = CSRFProtect(app)
        self.csrf.exempt(apply_move_to_game)

    def __initialize_mongo(self, app):
        MongoEngine(app)

    def __initialize_daos(self):
        self.move_dao = MongoDao(Move)
        self.game_dao = MongoDao(Game)
        self.user_dao = MongoDao(User)

    def __initialize_services(self):
        self.user_service = UserService(self.user_dao)
        self.game_service = GameService(self.game_dao)
        self.move_service = MoveService(self.move_dao, self.game_service)

        self.record_service = RecordService(self.game_service)

        self.ambiguous_move_service = AmbiguousMoveService()
        self.possible_move_service = PossibleMoveService(
            self.game_service,
            BOARD_SQUARES_FOR_GAME_TYPE,
            BOARD_MIDDLE_SECTION_FOR_GAME_TYPE,
        )

        self.move_update_services = (
            PlaceMoveUpdateService(self.game_service),
            MoveMoveUpdateService(self.game_service,
                                  self.possible_move_service),
            ReplaceMoveUpdateService(self.game_service),
        )

        self.move_application_service = MoveApplicationService(
            self.game_service,
            self.move_service,
            self.move_update_services,
        )

    def __initialize_auth(self, app):
        initialize_authentication(
            app=app,
            user_service=self.user_service,
            auth_secret_key=self.config["app_secret_key"],
            auth_blueprint_prefix=self.config["endpoint_prefixes"].get(
                "auth", ""),
            login_view="/login",
        )

    def __register_blueprints(self, app):
        for name, blueprint in ApplicationContext.BLUEPRINTS:
            LOGGER.debug(
                f"Registering {name} blueprint with prefix '{self.config['endpoint_prefixes'][name]}'"
            )
            app.register_blueprint(
                blueprint, url_prefix=self.config["endpoint_prefixes"][name])

    def __register_error_handlers(self, app):
        @app.errorhandler(InvalidMoveException)
        def handle_invalid_move_error(error):
            return jsonify(
                message=
                f"Failed to apply invalid move ({error.move}), reason: {error.reason}",
                move=error.move.to_dict("startSquare", "destinationSquare",
                                        "type"),
            ), 400

        @app.errorhandler(InvalidGameParameterException)
        def handle_invalid_game_parameter_error(error):
            return jsonify(message=error.message), 400

        @app.errorhandler(ForbiddenMoveException)
        def handle_forbidden_move_error(error):
            return jsonify(
                message=
                f"User '{current_user.username}' is not authorized to perform move ({error.move})",
                move=error.move.to_dict("startSquare", "destinationSquare",
                                        "type"),
            ), 403

        @app.errorhandler(DuplicateMoveException)
        def handle_duplicate_move_exception(_):
            return jsonify(
                message=
                f"Failed to persist move to game state that has already had a move applied"
            ), 400
Ejemplo n.º 2
0
# 初始化app
app = Flask(__name__)

#注册蓝图
app.register_blueprint(cms_bp)
app.register_blueprint(front_bp)
app.register_blueprint(common_bp)

#导入配置文件
app.config.from_object(config)
db.init_app(app)

#注册csrf模块
csrf = CSRFProtect()
csrf.exempt(front_bp)
csrf.exempt(cms_bp)
csrf.exempt(common_bp)
csrf.init_app(app)


# 处理404错误
@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404


#处理500错误
@app.errorhandler(500)
def page_not_found(e):
    return render_template('404.html'), 500
Ejemplo n.º 3
0
 def configure_wtf(self):
     if self.config["WTF_CSRF_ENABLED"]:
         csrf = CSRFProtect(self.flask_app)
         csrf_exempt_list = self.config["WTF_CSRF_EXEMPT_LIST"]
         for ex in csrf_exempt_list:
             csrf.exempt(ex)
Ejemplo n.º 4
0
import json
from redis import Redis
import rq
from sqlalchemy import func, asc, desc
from flask_wtf import CSRFProtect

queue = rq.Queue('enricher', connection=Redis.from_url('redis://'))
from lib import add_db_entry, get_comments, time_ago, escape_jquery, get_user_info, escape_jquery, parse_indicators

main = Blueprint('main', __name__)

app = create_app()
app.app_context().push()

csrf = CSRFProtect(app)
csrf.exempt("api.api_indicators_list")
csrf.exempt("app.api_indicator_get")

#these need to be imported after app is created
import reports
import requirements
import consumers
import indicators
import settings
import api


def enrich_pipeline(json_str):
    json_data = json.loads(json_str)
    indicator = json_data.get('indicator')
    org_id = json_data.get('organization')