def create_app(): # name is a pre-defined python variable which is set to the name of the module in which it is used # the flask object implements a WSGI application - once it is created it acts as a central repository # for view functions, url rules, template config, etc # should be created in main module or __init__.py of your package app = Flask(__name__) app.config['MONGODB_SETTINGS'] = { 'db': 'kart_db', 'host': '172.21.0.2', 'port': 27017, 'authentication_source': 'admin', 'username': '******', 'password': '******' } #print('cf: ' + str(dir(config_filename))) #app.config.from_object('settings') app.config.from_envvar('FLASK_MODULE_SETTINGS') #app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://root:[email protected]:3306/mange_takk_db' #app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # initialize extensions so that extension knows the name of the application object api.init_app(app) cors.init_app(app) # right now all cross origin requests are allowed - need to change this config # src: https://stackoverflow.com/questions/26980713/solve-cross-origin-resource-sharing-with-flask # cors = CORS(app, resources={r"/api/*": {"origins": "*"}}) db.init_app(app) jwt.init_app(app) return app
def init_extensions(app): # Init database from extensions import db db.init_app(app) # Init migration from extensions import migrate migrate.init_app(app, db) # Init bcrypt from extensions import bcrypt bcrypt.init_app(app) # Init Login manager from extensions import login_mgr login_mgr.login_view = 'auth.login' login_mgr.init_app(app) # Init mail from extensions import mail mail.init_app(app) # Init jwt from extensions import jwt jwt.init_app(app)
def register_extensions(app): db.init_app(app) migrate = Migrate(app, db) jwt.init_app(app) configure_uploads(app, image_set) patch_request_class(app, 10 * 1024 * 1024) cache.init_app(app) limiter.init_app(app) @jwt.token_in_blocklist_loader def check_if_token_in_blacklist(jwt_header, jwt_payload): jti = jwt_payload['jti'] return jti in black_list @app.before_request def before_request(): print('\n=============BEFORE REQUEST===============\n') print(cache.cache._cache.keys()) print('\n==========================================\n') @app.after_request def after_request(response): print('\n============AFTER REQUEST=================\n') print(cache.cache._cache.keys()) print('\n==========================================\n') return response @limiter.request_filter def ip_whitelist(): return request.remote_addr == '127.0.0.1'
def config_extension(app): """ init extension for app :return: """ mongo.init_app(app) jwt.init_app(app)
def create_app(): """App Factory. Returns: App: Flask app object. """ sentry_sdk.init( dsn="https://[email protected]/5184010", integrations=[FlaskIntegration()]) app = Flask(__name__) jwt.init_app(app) limiter.init_app(app) app.config["JWT_SECRET_KEY"] = config.JWT_SECRET_KEY app.config["JWT_ACCESS_TOKEN_EXPIRES"] = config.JWT_ACCESS_TOKEN_EXPIRES app.register_blueprint(auth) app.register_blueprint(users) app.register_blueprint(polls) app.register_blueprint(health) app.register_blueprint(handlers) return app
def register_extensions(app): db.init_app(app) migrate = Migrate(app, db) jwt.init_app(app) mail.init_app(app) cache.init_app(app) limiter.init_app(app)
def register_extensions(app): db.init_app(app) migrate = Migrate(app, db) jwt.init_app(app) configure_uploads(app, image_set) patch_request_class(app, 10 * 1024 * 1024) cache.init_app(app) limiter.init_app(app) @jwt.token_in_blacklist_loader def check_if_token_in_blacklist(decrypted_token): jti = decrypted_token['jti'] return jti in black_list @app.before_request def before_request(): print('\n==================== BEFORE REQUEST ====================\n') print(cache.cache._cache.keys()) print('\n=======================================================\n') @app.after_request def after_request(response): print('\n==================== AFTER REQUEST ====================\n') print(cache.cache._cache.keys()) print('\n=======================================================\n') return response
def create_app(): # Create the Flask's instance. app = Flask(__name__, static_folder="../dist/static", template_folder="../dist") # Set the project's config. app.config.from_object(ProdConfig) # Register blueprint app.register_blueprint(user) app.register_blueprint(article) app.register_blueprint(catalog) # Init the extensions' app db.init_app(app) cors.init_app(app) jwt.init_app(app) # swagger.init_app(app) # Page jump @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def catch_all(path): return render_template("index.html") return app
def create_app(): load_dotenv(".env", verbose=True) app = Flask(__name__) app.config.from_object("default_config") app.config.from_envvar("APPLICATION_SETTINGS") api = Api(app) @app.errorhandler(ValidationError) def handle_marshmallow_validation(err): return jsonify(err.messages), 400 @app.before_first_request def create_tables(): db.create_all() db.init_app(app) ma.init_app(app) login_manager.init_app(app) # authorize.init_app(app) jwt.init_app(app) babel.init_app(app) # Set up Casbin model config app.config['CASBIN_MODEL'] = './src/casbinmodel.conf' # Set headers where owner for enforcement policy should be located app.config['CASBIN_OWNER_HEADERS'] = {'Authorization'} # Set up Casbin Adapter adapter = FileAdapter('./src/security_policy.csv') casbin_enforcer.init_app(app, adapter) # casbin_enforcer = CasbinEnforcer(app, adapter) # casbin_enforcer = UpdatedCasbinEnforcer(adapter) @app.route("/") @casbin_enforcer.enforcer def index(): return jsonify({"hello": "world"}) from authz.resources.user import UserRegister, UserLogin, UserLogout api.add_resource(UserRegister, "/register") api.add_resource(UserLogin, "/login") api.add_resource(UserLogout, "/logout") # from authlogin.resources.security import NewGroup, GroupResource, UserGroup # api.add_resource(NewGroup, "/group") # api.add_resource(GroupResource, "/group/<int:_id>") # api.add_resource(UserGroup, "/usergroup/<int:_id>") # # api.add_resource(UserGroup, "/usergroup") from main.resources.store import NewStore, Store, StoreList api.add_resource(NewStore, "/store") api.add_resource(Store, "/store/<int:_id>") api.add_resource(StoreList, "/stores") return app
def register_extensions(app): from extensions import bcrypt, db, jwt app.config.from_envvar('ENV_FILE_LOCATION') bcrypt.init_app(app) db.init_app(app) jwt.init_app(app)
def register_extensions(application): db.init_app(application) migrate = Migrate(application, db) jwt.init_app(application) @jwt.token_in_blacklist_loader def check_if_token_in_blacklist(decrypted_token): jti = decrypted_token['jti'] return jti in black_list
def configure_extensions(app): app.config.setdefault('JWT_SECRET_KEY', SECRET_KEY) app.config['SQLALCHEMY_DATABASE_URI'] = db_path app.config[ 'SQLALCHEMY_TRACK_MODIFICATIONS'] = SQLALCHEMY_TRACK_MODIFICATIONS db.init_app(app) jwt.init_app(app) db.create_all(app=app)
def create_app(config=None): new_app = Flask(__name__, template_folder='../react_app/build', static_folder='../react_app/build/static') new_app.config.from_object(config) with new_app.app_context(): jwt.init_app(new_app) bcrypt.init_app(new_app) cors.init_app(new_app) mysql.init_app(new_app) mail.init_app(new_app) from model import temp_blacklist @jwt.token_in_blacklist_loader def check_if_token_in_blacklist(decrypted_token): return decrypted_token['jti'] in temp_blacklist # Let react handle routing @new_app.route('/', defaults={'path': ''}) @new_app.route('/<path:path>') def serve(path): if path and os.path.exists(safe_join(new_app.template_folder, path)): return send_from_directory(new_app.template_folder, path) else: return send_from_directory(new_app.template_folder, 'index.html') from resources.authentication import (UserRegistration, UserLogin, TokenRefresh, UnsetToken, AdminLogin, AdminRegister) from resources.user import GetUserInfo, UpdateUserInfo from resources.products import (TrackProduct, NewComments, GetComments, GetSpecificProduct) from resources.admin import Announcement api.add_resource(UserRegistration, '/register') api.add_resource(UserLogin, '/login') api.add_resource(TokenRefresh, '/refresh') api.add_resource(UnsetToken, '/revoke') api.add_resource(GetUserInfo, '/user') api.add_resource(UpdateUserInfo, '/user/<string:option>') api.add_resource(TrackProduct, '/product') api.add_resource(GetSpecificProduct, '/product/<string:retailer>/<string:pid>') api.add_resource(NewComments, '/comment') api.add_resource(GetComments, '/comment/<string:retailer>/<string:prod_id>') api.add_resource(AdminLogin, '/admin-login') api.add_resource(AdminRegister, '/admin-register') api.add_resource(Announcement, '/announcement') api_bp = Blueprint('api', __name__) api.init_app(api_bp) new_app.register_blueprint(api_bp, url_prefix='/api') return new_app
def register_extensions(app): db.app = app db.init_app(app) migrate = Migrate(app, db) jwt.init_app(app) @jwt.token_in_blacklist_loader def check_if_token_in_blacklist(decrypted_token): jti = decrypted_token["jti"] return jti in black_list
def configure_extensions(flask_app): db.init_app(flask_app) jwt.init_app(flask_app) sentry_sdk.init( dsn= "https://[email protected]/5536563", integrations=[FlaskIntegration()], traces_sample_rate=1.0) if flask_env == "development": swagger.init_app(flask_app)
def register_extensions(app): """Register Flask extensions.""" db.init_app(app) migrate.init_app(app, db) login_manager.init_app(app) bcrypt.init_app(app) if not scheduler.running: scheduler.init_app(app) scheduler.start() jwt.init_app(app)
def create_app(script_info=None): app = Flask(__name__) load_dotenv(".env", verbose=True) app_settings = os.environ.get("APP_SETTINGS") if not app_settings: raise ValueError( 'APP_SETTINGS environment variable is not set. Aborting.') app.config.from_object(app_settings) # Migration purposes from models import user, remaining_employee, company, address # NOQA jwt.init_app(app) db.init_app(app) api.init_app(app) ma.init_app(app) migrate.init_app(app, db) init_celery(app) mail.init_app(app) api.add_resource(UserLogin, "/login") api.add_resource(UserRegister, "/register") api.add_resource(UserRegister, "/register/<string:confirmation_token>") api.add_resource(User, "/user") api.add_resource(UserList, "/users") api.add_resource(UserInvite, "/invite") @app.route('/ping') def pong(): return 'pong' @api.errorhandler(Unauthorized) def unauthorized_page(error): return {"message": "401, change this on prod."}, 401 @api.errorhandler(Forbidden) def forbidden_page(error): return {"message": "403, change this on prod."}, 403 @api.errorhandler(NotFound) def page_not_found(error): return {"message": "404, change this on prod."}, 404 @api.errorhandler(MethodNotAllowed) def method_not_allowed(error): return {"message": "405, change this on prod."}, 405 @api.errorhandler(InternalServerError) def server_error_page(error): return {"message": "500, change this on prod."}, 500 return app
def register_extensions(app): """Register Flask extensions.""" bcrypt.init_app(app) # cache.init_app(app) db.init_app(app) ma.init_app(app) migrate.init_app(app, db) jwt.init_app(app) # redis_store.init_app(app) logging.config.dictConfig(app.config["LOGGING"]) return app
def register_extensions(app): db.init_app(app) migrate = Migrate(app, db) jwt.init_app(app) configure_uploads(app, image_set) patch_request_class(app, 10 * 1024 * 1024) @jwt.token_in_blacklist_loader def check_if_token_in_blacklist(decrypted_token): jti = decrypted_token['jti'] return jti in black_list
def configure_extensions(app): cors = CORS(app) jwt.init_app(app) # cors.init_app(app) db.init_app(app) migrate.init_app(app, db) global printer printer = Printer(app.config['PRINTER_IP'], app.config['PRINTER_PORT']) printer.setDaemon(True) printer.start()
def register_extension(app): db.init_app(app) # the callbacks needs to be supplied before init_app jwt.identity_callback = identity jwt.authentication_callback = authenticate jwt.init_app(app) api.add_resource(Item, '/item/<string:name>') api.add_resource(ItemList, '/items') api.add_resource(Store, '/store/<string:name>') api.add_resource(StoreList, '/stores') api.add_resource(UserRegistor, '/register') api.init_app(app)
def register_extensions(app): db.app = app db.init_app(app) migrate = Migrate(app, db) jwt.init_app(app) @jwt.token_in_blacklist_loader def check_if_token_in_blacklist_student(decrypted_token_students): jti = decrypted_token_students['jti'] return jti in black_list_student @jwt.token_in_blacklist_loader def check_if_token_in_blacklist_teacher(decrypted_token_teachers): jti = decrypted_token_teachers['jti'] return jti in black_list_teacher
def create_app(): app = Flask(__name__) app.secret_key = 'ChangeMe!' app.config['JWT_BLACKLIST_ENABLED'] = True app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access', 'refresh'] app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite://" app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.init_app(app) jwt.init_app(app) # In a real application, these would likely be blueprints register_endpoints(app) return app
def register_extensions(app): db.init_app(app) migrate = Migrate(app, db) jwt.init_app(app) configure_uploads(app, image_set) patch_request_class(app, 4 * 1024 * 1024) cache.init_app(app) limiter.init_app(app) @limiter.request_filter def ip_whitelist(): return request.remote_addr == '127.0.0.1' @jwt.token_in_blacklist_loader def check_if_token_in_blacklist(decrypted_token): jti = decrypted_token['jti'] return jti in blacklist
def create_app(conf=None) -> Flask: conf = conf or get_config() app = Flask(__name__) app.config.from_object(conf) # register with app db.init_app(app) migrate.init_app(app, db) api.init_app(app) middleware_manager.init_app(app) jwt.init_app(app) secret_generator_cli.init_app(app) if conf.DEBUG: code_generator.init_app(app) seeds.init_app(app) return app
def register_extensions(app): """function to initialize extensions""" db.app = app db.init_app(app) migrate.init_app(app, db) jwt.init_app(app) configure_uploads(app, image_set) patch_request_class(app, 10*1024*1024) cache.init_app(app) limiter.init_app(app) # check whether the token is on the blacklist @jwt.token_in_blacklist_loader def check_if_token_in_blacklist(decrypted_token): jti = decrypted_token['jti'] return jti in black_list
def create_app(db_uri, keys_dir_path): app = Flask(__name__) private_key = '' public_key = '' with open(keys_dir_path + '/jwtRS256.key', 'r') as content_file: private_key = content_file.read() with open(keys_dir_path + '/jwtRS256.key.pub', 'r') as content_file: public_key = content_file.read() app.config['JWT_ALGORITHM'] = 'RS256' app.config['JWT_PUBLIC_KEY'] = public_key app.config['JWT_PRIVATE_KEY'] = private_key app.config['JWT_IDENTITY_CLAIM'] = 'sub' app.config['JWT_USER_CLAIMS'] = 'payload' app.config['JWT_CLAIMS_IN_REFRESH_TOKEN'] = False app.config['JWT_ERROR_MESSAGE_KEY'] = 'message' app.config['JWT_TOKEN_LOCATION'] = ('headers', 'cookies') app.config['SQLALCHEMY_DATABASE_URI'] = db_uri app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['PROPAGATE_EXCEPTIONS'] = True from extensions import ( api, jwt, db, ) jwt.init_app(app) db.init_app(app) import models with app.app_context(): db.create_all() import resources resources.BaseResource.register(api) api.init_app(app) CORS(app) return app
def register_extensions_production(app): """Register Flask extensions.""" from extensions import api api.init_app(app) cors.init_app(app, supports_credentials=True) # need this for true prod cors.init_app( app, resources={ r"/*": {"origins": "https://www.icarusmed.com"} }, supports_credentials=True) jwt.init_app(app) csrf.init_app(app) return None
def create_app(): application = Flask(__name__) application.config.update(settings) mail.init_app(application) mongo.init_app(application) cache.init_app(application) jwt.init_app(application) limiter.init_app(application) for bp in http_blueprints: import_module(bp.import_name) application.register_blueprint(bp) application.cli.add_command(populate_users_command) application.cli.add_command(populate_transactions_command) return application
def create_app(): app = Flask(__name__) app.secret_key = os.getenv('SECRET_KEY') app.config['JSON_SORT_KEYS'] = False app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config[ 'SQLALCHEMY_DATABASE_URI'] = 'mysql://{0}:{1}@{2}/{3}?charset=utf8'.format( os.getenv('DB_USER'), os.getenv('DB_PASSWORD'), os.getenv('DB_HOST'), os.getenv('DB_NAME')) app.config['SQLALCHEMY_ECHO'] = True app.config['JWT_SECRET_KEY'] = os.getenv('JWT_SECRET_KEY') # Change this! app.config['JWT_TOKEN_LOCATION'] = [ 'headers' ] # headers', 'cookies', 'query_string', 'json' db.init_app(app) migrate.init_app(app, db) jwt.init_app(app) register_blueprints(app) return app