def create_app(env, **kwargs): from config import Config from app.routes import register_routes from app.error_handlers import register_error_handler from commands import register_commands app = Flask(__name__) cors = CORS(app) app.config['CORS_HEADERS'] = 'Content-Type' if kwargs.get("celery"): init_celery(kwargs.get("celery"), app) app.config.from_object(Config(env)) app.config.from_envvar("USI_CONFIG", silent=True) register_error_handler(app) api = Api(app, title='User Service API', version='0.0.1') register_routes(api, app) db.init_app(app) Migrate(app, db) register_commands(app) return app
def create_app(env=None): from app.config import config_by_name from app.routes import register_routes app_version = pkg_resources.require("app")[0].version app_info = {"name": __name__.split(".")[1], "version": app_version} # Application Configuration app = Flask(__name__) app.config.from_object(config_by_name[env or "test"]) api = Api(app, title=__name__, version=app_version) register_routes(api, app) # Telemetry register_errorhandlers(app) configure_logger(app) # Meta Routes @app.route("/health") def health(): return jsonify(app_info) @app.route("/version") def version(): return jsonify({"version": app_version}) register_routes(api, app) return app
def init_app(): app = Flask(__name__, instance_relative_config=True, template_folder='site/templates', static_folder='site/static') app.config.from_object(app_config[get_config().get_flask_config()]) app.config['SQLALCHEMY_DATABASE_URI'] = get_config().get_db_config() app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SECRET_KEY'] = get_config().get_secret_key() login_manager.init_app(app) login_manager.login_message = "You must be logged in to access this page." login_manager.login_view = "auth.login" CORS(app, headers=['Content-Type'], expose_headers=['Access-Control-Allow-Origin'], supports_credentials=True) DATABASE.init(app) api = Api(version='1.0', title='api') api_user = Api(version='1.0', title='api_user') api_admin = Api(version='1.0', title='api_admin') register_routes(app, api, api_user, api_admin) register_custom_errors(app) login_manager.user_loader(auth_utils.load_user) return app
def create_test_app(cls): from app.routes import register_routes application = Flask(__name__) application.config.from_object(conf.TestConfig) cls.db = SQLAlchemy(application) Marshmallow(application) register_routes(application) return application
def create_app(is_test=False): app = Flask(__name__, instance_relative_config=True) init_setup(app) CORS(app) register_routes(app) db.init_app(app) ma.init_app(app) Migrate(app, db) init_errorhandler(app) init_log(app) return app
def create_app(config_object=None): """Create and configure an instance of the Flask application.""" app = Flask(__name__) config = config_object if config_object else Config app.config.from_object(config) register_extensions(app) register_routes(app) register_commands(app) return app
def create_app(env=None): from app.config import config_by_name, version from app.routes import register_routes app = Flask(__name__) app.config.from_object(config_by_name[env or "test"]) api = Api(app, title="Flask Interview API", version=version) register_routes(api, app, version) db.init_app(app) return app
def init_app(): app = Flask(__name__, instance_relative_config=True, template_folder='site/templates', static_folder='site/static') app.config[ 'SQLALCHEMY_DATABASE_URI'] = 'postgres://*****:*****@0.0.0.0:5566/sdn_db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False DATABASE.init(app) api = Api(version='1.0', title='api') register_routes(app, api) return app
def create_app(self, config_file='settings.py') -> Flask: try: app = Flask(__name__) app.config.from_pyfile( sep.join([getcwd(), 'app', 'config', config_file])) self.__logger.init_app(app) mongo_db.init_app(app) type(self).register_middlewares(app) register_routes(app) self.__error_handlers.init_app(app) return app except Exception as err: exit(f'Bootstrap Flask server failure|description: {err}')
def create_app(type="app", test=False): app = Flask(__name__) cfg = DevConfig() if test: cfg = TestConfig() app.config.from_object(cfg) configure_celery(app, tasks.celery) init_mongo(app) register_error_handlers(app) register_routes(app) return app if type == "app" else tasks.celery
def create_app(env=None): from app.config import config_by_name from app.routes import register_routes app = Flask(__name__, instance_relative_config=True) app.config.from_object(config_by_name[env or 'test']) api = Api(app, title='SportBud API', version='0.1.0') register_routes(api, app) db.init_app(app) @app.route('/health') def health(): return jsonify('healthy') return app
def create_app(env=None): from app.config import config_by_name from app.routes import register_routes app = Flask(__name__) app.config.from_object(config_by_name[env or "test"]) api = Api(app, title="Flaskerific API", version="0.1.0") register_routes(api, app) db.init_app(app) @app.route("/health") def health(): return jsonify("healthy") return app
def create_app(env: str = None) -> Flask: """ Flask Application Factory """ dictConfig({ 'version': 1, 'formatters': { 'default': { 'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s', } }, 'handlers': { 'wsgi': { 'class': 'logging.StreamHandler', 'stream': 'ext://flask.logging.wsgi_errors_stream', 'formatter': 'default' } }, 'root': { 'level': 'INFO', 'handlers': ['wsgi'] } }) from app.config import config_by_name from app.routes import register_routes app = Flask(__name__) app.config.from_object(config_by_name[env or "test"]) db.init_app(app) ma.init_app(app) login.init_app(app) csrf.init_app(app) encrypt.init_app(app) register_routes(app) @app.route("/health") def health() -> Response: """ Health check route """ return jsonify("healthy"), 200 return app
def create_app(env=None): from app.config import config_by_name from app.routes import register_routes app = Flask(__name__) app.config.from_object(config_by_name[env or "dev"]) register_routes(app) mongo.init_app(app) jwt.init_app(app) bcrypt.init_app(app) mailer.init_app(app) @app.route("/health") def health(): return jsonify("healthy") return app
def create_app(): app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = conn_url.__to_string__( hide_password=False) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI']) blueprint = Blueprint('clinic_appointment_api', __name__) api = Api(blueprint, version='1.0', prefix='/api/v1', title='Clinic Appointment', description='Clinic Appointment API') register_routes(api, app) app.register_blueprint(blueprint) db.init_app(app) return app
def create_app(env=None): from app.config import config_by_name from app.routes import register_routes from app.errors import register_error_handlers # Creamos la aplicación de Flask app = Flask(__name__, template_folder='./templates') config = config_by_name[env or "test"] app.config.from_object(config) # Creacmos el objeto `api` api_title = os.environ.get('APP_TITLE', config.TITLE) api_version = os.environ.get('APP_VERSION', config.VERSION) api_description = """ API del Conatel Switch Manager """ api = ApiFlask(app, title=api_title, version=api_version, description=api_description, license='MIT', licence_url='https://opensource.org/licenses/MIT', endpoint='', ) # Registramos las rutas register_routes(api, app) # Registramos loa error_handlers register_error_handlers(app) # Inicializamos la base de datos db.init_app(app) # Configuración de página de documentación @api.documentation # pylint: disable=unused-variable def custom_ui(): return render_template('api_docs.html') # return apidoc.ui_for(api) # Creamos una ruta para chequear la salud del sistema @app.route('/healthz') # pylint: disable=unused-variable def healthz(): """ Healthz endpoint """ return jsonify({"ok": True}) # Retornamos la aplicación de Flask return app, api
def create_app(env=None): from app.config import config_by_name from app.routes import register_routes app = Flask(__name__) app.config.from_object(config_by_name[env or "test"]) api = Api(app, title="Nessus API", version="0.1.0") register_routes(api, app) app.elasticsearch = Elasticsearch([app.config['ELASTICSEARCH_URL']]) \ if app.config['ELASTICSEARCH_URL'] else None @app.route("/health") def health(): return jsonify("healthy") return app
def create_app(env=None): from app.config import config_by_name from app.routes import register_routes app = Flask(__name__) app.config.from_object(config_by_name[env or 'test']) db.init_app(app) ma.init_app(app) from flask import Blueprint api_v1 = Blueprint('api_v1', __name__) api = Api( api_v1, title="In Scholaris API", version="0.1.0", ) register_routes(api, app) app.register_blueprint(api_v1, url_prefix="/v1") @app.route("/health") def health(): return Response.success({"status": "Running"}, HttpStatusCode.CREATED, "Successfully working") @app.route("/raise_form_error") def form_error(): return Response.error({"name": "Required"}, HttpStatusCode.BAD_REQUEST, "Field Required", BusinessErrorCode.INVALID_USER) @api.errorhandler(TypeError) def handle_type_error_exception(error): return Response.error( {"exception": str(error)}, HttpStatusCode.BAD_REQUEST, str(error), ) return app
def create_app(env: str = None) -> Flask: """Flask Application Factory Keyword Arguments: env: Name of the configuartion to launch - 'development', 'testing', 'production' Returns: Flask() -- The Flask app """ from app.config import config_by_name app = Flask(__name__) if environ.get('FLASK_ENV') == 'production': app.wsgi_app = ReverseProxied(app.wsgi_app) app.config.from_object(config_by_name[env or "test"]) db.init_app(app) migrate.init_app(app, db) csrf.init_app(app) login.init_app(app) principals.init_app(app) api.init_app(app) from app.routes import register_routes register_routes(api, app) # In testing environemt need to mimic setting Flask_Principals permissions if environ.get('FLASK_ENV') == 'test': @app.before_request def determine_identity() -> None: identity_changed.send(current_app._get_current_object(), identity=Identity('*****@*****.**')) # Health test @app.route("/health") def health() -> Response: return jsonify("healthy") return app
def create_app(env=None): from app.config import config_by_name from app.routes import register_routes app = Flask(__name__) app.config.from_object(config_by_name[env or "dev"]) api = Api(app, title="") register_routes(api, app) db.init_app(app) cors.init_app(app) Session(app) @app.route("/health") def healthCheck(): return jsonify('healthy') return app
def create_app(config_mode): from app.routes import register_routes app = Flask(__name__, instance_relative_config=True) config_obj = config_by_name[config_mode] app.config.from_object(config_obj) api = Api(app, title='SignCoach RPI API', version='0.1.0', doc=config_obj.SWAGGER_URI) register_routes(api, app) info.build(config_obj.INFO_FILE_LOC) @app.route('/health') def health(): return jsonify('healthy') return app
def create_app(config_object=None): """Create and configure an instance of the Flask application.""" app = Flask(__name__) config = config_object if config_object else Config app.config.from_object(config) register_extensions(app) register_routes(app) register_commands(app) @api.errorhandler(Exception) def default_error_handler(error): app.logger.error(str(error)) app.logger.error('REQUEST\n' + str(request)) app.logger.error('HEADERS\n ' + str(request.headers)) return { 'status': getattr(error, 'code', 500), 'message': str(error), }, getattr(error, 'code', 500) return app
def create_app(env=None): from .db import db from .ext import ma, migrate from .config import config_by_name from app.routes import register_routes app = Flask(__name__) app.config.from_object(config_by_name[env or "dev"]) api = Api(app, title="Credit Collection API", version="0.1.0") register_routes(api, app) db.init_app(app) ma.init_app(app) migrate.init_app(app, db) seeder = FlaskSeeder() seeder.init_app(app, db) CORS(app) return app
def create_app(): global app global db global s3 global login_manager # Flask app = Flask(__name__, static_folder='static/dist/', static_url_path='/static') app.config.from_object('config.flask_config') # SQLAlchemy db = SQLAlchemy(app) # Amazon S3 s3 = S3(app) # Debug app.config['DEBUG'] = (len(argv) == 2 and argv[1] == 'debug') from app.routes import register_routes register_routes(app, db) return app, db
def create_app(env=None): from app.config import config_by_name, get_db_url_modifies from app.routes import register_routes app = Flask(__name__) app.config.from_object(config_by_name[env or "test"]) # app.config["SQLALCHEMY_DATABASE_URI"] = get_db_url_modifies("sqlite:///data.db") api = Api(app) jwt = JWTManager(app) print(get_db_url_modifies("couldn't find db URL")) db.app = app db.init_app(app) db.create_all() DBMan.create_tables( app) # TODO: find a better place for creating tables later register_routes(api, app) @app.route("/health") def healthy(): return jsonify("healthy") # region JWT config methods @jwt.additional_claims_loader def add_claims_to_jwt(identity): """ This method is used to attach the information of the user to the JWT access token. """ user = UserModelService.retrieve_by_user_id(identity, app) if user: return { "user_id": user.user_id, "username": user.username, "email": user.email, "is_admin": user.is_admin == 1, } return { "description": "User is not logged in", "error": "not_logged_in" }, 401 @jwt.token_in_blocklist_loader # callback to chick if the jwt exists in the jwt blocklist database def check_if_token_revoked(jwt_header, jwt_payload): jti = jwt_payload["jti"] token = db.session.query( TokenBlocklistModel.id).filter_by(jti=jti).scalar() return token is not None @jwt.expired_token_loader # going to be called when the toke expires def expired_token_callback(jwt_header, jwt_payload): return ( jsonify({ "description": "The token has expired", "error": "token_expired" }), 401, ) @jwt.invalid_token_loader # going to be called when the authentication is not jwt for example auth using jwt instead of Bearer when using flask_jwt_extended def invalid_token_callback(error): return jsonify({"description": error, "error": "invalid_token"}), 401 @jwt.unauthorized_loader # going to be called when they don't send us a jwt at all def missing_token_callback(reason): return jsonify({ "description": reason, "error": "authorization_required" }), 401 @jwt.needs_fresh_token_loader # going to be called when the token is not fresh and a fresh one is needed def token_not_fresh_callback(jwt_header, jwt_payload): return ( jsonify({ "description": "The token is not fresh", "error": "fresh_token_required", }), 401, ) @jwt.revoked_token_loader # the toke has been revoked for example if the user is logged out def revoked_token_callback(jwt_header, jwt_payload): return ( jsonify({ "description": "The token has been revoked", "error": "token_revoked" }), 401, ) # endregion # adding admin admin: UserModelInterface = dict( username="******", is_admin=1, email="*****@*****.**", password="******", first_name="Abdelaziz", last_name="Rashed", ) UserModelService.create(admin, app, db) return app
import os from flask import Flask from app.routes import register_routes from app.extensions import api, db, ma, migrate, bcrypt def create_app(): app = Flask(__name__.split('.')[0]) app_settings = os.getenv('APP_SETTINGS') app.config.from_object(app_settings) register_extensions(app) return app def register_extensions(app): db.init_app(app) ma.init_app(app) api.init_app(app) migrate.init_app(app, db) bcrypt.init_app(app) register_routes() app = create_app()
def init_app(): app = Flask(__name__) CORS(app) app.config.from_object(Config) api = Api(app) init_extensions(app) app.cli.add_command(cli_commands) from app.controllers.ottd import OpenTTDConnection # noqa from app.controllers.company import CompanyTimescaleController # noqa from app.controllers.vehicle import VehicleTimescaleController, VehicleController from app.controllers.town import TownController, TownTimescaleController def interrupt(signal_received, frame): info("Shutting Down...") global shutting_down ottd_connection.disconnect() shutting_down = True sleep(2) os.kill(os.getpid(), signal.SIGTERM) def do_connection_thread(): sleep(1) global connection_thread global ottd_connection global current_date global month_last_update global year_last_update global shutting_down ottd_connection.req_data() current_date = ottd_connection.sync_data()() if month_last_update != current_date.month: # Trigger Vehicle Sync info(f" [ New Month {current_date.year}-{current_date.month} ]") info(f" [ Requesting Vehicle Updates ] ") ottd_connection.refresh_db_vehicles() month_last_update = current_date.month if year_last_update != current_date.year: info(f" [ New Year {current_date.year} ] ") info(f" [ Requesting City & Vehicle Updates ] ") year_last_update = current_date.year # ottd_connection.refresh_db_vehicles() # ottd_connection.refresh_db_towns() # Set the next thread to happen if not shutting_down: connection_thread = AppContextThread(target=do_connection_thread) connection_thread.start() def start_connection_thread(app): # Do initialisation stuff here global connection_thread global ottd_connection # Create your thread with app.app_context(): connection_thread = AppContextThread(target=do_connection_thread) ottd_connection = OpenTTDConnection() # ottd_connection.scan_vehicles(20) info(f" [ Start Town Scan ]") # ottd_connection.schedule_next_town_scan_batch(947, 10) connection_thread.start() def start_timescale_thread(app): global timescale_updater_thread with app.app_context(): timescale_updater_thread = AppContextThread( target=do_timescale_thread ) timescale_updater_thread.start() def do_timescale_thread(): sleep(1) global timescale_updater_thread global current_date global shutting_down CompanyTimescaleController.capture_data(current_date) VehicleTimescaleController.capture_data(current_date) TownTimescaleController.capture_data(current_date) if not shutting_down: timescale_updater_thread = AppContextThread( target=do_timescale_thread ) timescale_updater_thread.start() # Only run tasks if flask is being run. flask = "flask/__main__.py" if Config.WORKER: start_connection_thread(app) start_timescale_thread(app) signal.signal(signal.SIGINT, interrupt) # ctlr + c from app import routes, models routes.register_routes(app, api) return app
def init_app(ENV): app = Controller(ENV) routes.register_routes(app) wsgi_app = app.wsgi_app return app
import dash import dash_bootstrap_components as dbc import dash_html_components as html from app.layout import Root from app.callbacks import register_callbacks from app.routes import register_routes # Initial app configuration app = dash.Dash(__name__, external_stylesheets=[dbc.themes.LUX, './assets/custom.css']) app.layout = html.Div(Root()) app.title = 'Playground | ICRS' app.config['suppress_callback_exceptions'] = True register_callbacks(app) register_routes(app) # This is the main entry point of the app if __name__ == '__main__': app.run_server(debug=True, dev_tools_hot_reload=True)
from app import create_app from app.data_access import MariaDBRecordProvider, TextFileMasterPasswordProvider from app.routes import register_routes from app.auth import AuthProvider app = create_app() db = MariaDBRecordProvider(app.config) pwd_store = TextFileMasterPasswordProvider(app.instance_path) auth = AuthProvider(pwd_store, app.config['SECRET_KEY']) register_routes(app, db, db, auth)