def create_app(test_config=None): """ Creates app """ app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( # Make sure to change debug to False in production env DEBUG=config('DEBUG', default=False), SECRET_KEY=config('SECRET_KEY', default='dev'), # CHANGE THIS!!!! # For in-memory db: default='sqlite:///:memory:'), DATABASE_URI=config('DATABASE_URI'), LOGFILE=config('LOGFILE', os.path.join( app.instance_path, 'logs/debug.log')), CACHE_TYPE=config('CACHE_TYPE', 'simple'), # Configure caching # Long cache times probably ok for ML api CACHE_DEFAULT_TIMEOUT=config('CACHE_DEFAULT_TIMEOUT', 300), TESTING=config('TESTING', default='TRUE'), REDISTOGO_URL=config('REDISTOGO_URL', default='redis://localhost:6379'), ) # Enable CORS header support CORS(app) # Enable caching cache.init_app(app) ############## ### Routes ### ############## app.register_blueprint(mock_routes) app.register_blueprint(admin_routes) app.register_blueprint(covid_dash) ############# ###Logging### ############# # Change logging.INFO to logging.DEBUG to get full logs. Will be a crapload of information. # May significantly impair performance if writing logfile to disk (or network drive). # To enable different services, see README.md gunicorn_logger = logging.getLogger('gunicorn.error') app.logger.handlers.extend(gunicorn_logger.handlers) app.logger.setLevel(gunicorn_logger.level) app.logger.info('Application logging Set') # File logging. Remove in PROD if app.config['TESTING'] == 'TRUE': app.logger.info('Using TESTING log config.') logging.basicConfig( filename=app.config['LOGFILE'], level=logging.INFO, format='[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S %z') logging.getLogger('flask_cors').level = logging.INFO # Register database functions. Will allow db.close() to run on teardown from api import db db.init_app(app) app.logger.info('Database functionality initialized. Click commands available.') return app
def create_app(): """ Create the application using Flask's application factory pattern """ configure_logging() # creating the application app = Flask(__name__, instance_relative_config=True) if app.env == 'development': logging.getLogger().setLevel(logging.DEBUG) # making sure that instance folder exists try: os.makedirs(app.instance_path) except OSError: pass # load in app configuration from api import config app.config.from_object(config.Config) from api import db db.init_app(app) register_blueprints(app) from api import errors errors.register_errors(app) return app
def create_app(): app = Flask( import_name='__main__', static_folder=rel_path('app/build', __file__), template_folder=rel_path('app/build', __file__), static_url_path='/' ) app.config.from_object(config) for attr in [a for a in dir(config) if not a.startswith('__')]: print(f'{attr:<35} = {getattr(config, attr)}', file=sys.stderr) db.init_app(app) flask_bcrypt.init_app(app) app.register_blueprint(blueprint, url_prefix='/api') @app.route('/') def index(): return render_template('index.html', token='Hello World') @app.errorhandler(404) def not_found(e): return render_template('index.html', token='Hello World') return app
def create_app(): """Creates a factory design Flask Application. Creates a Flask Instance, connects the app to the database, and sets up the url architecture. Returns: A flask application with a registered blueprint for url architecture build up and database connection. """ # create and configure the app app = Flask(__name__, instance_relative_config=True) @app.route('/') def index(): """Welcoming Page.""" return 'Phoenix Time' # set up url architecture /api/... app.register_blueprint(route.api_bp, url_prefix='/api') # set up database db.init_app(app) return app
def signup_admin(): # let's inicizlize db db.init_app(app) # let's create db with app.app_context(): db.create_all() name = 'admin' password = '******' user = User.query.filter_by(name=name).first( ) # if this returns a user, then the email already exists in database if user: # if a user is found, we want to redirect back to signup page so user can try again # return redirect(url_for('auth.signup')) return 'it is ALREADY exists ADMIN' # create new user with the form data. Hash the password so plaintext version isn't saved. new_user = User(public_id=str(uuid.uuid4()), name=name, password=generate_password_hash(password, method='sha256'), admin=True) # add the new user to the database db.session.add(new_user) db.session.commit()
def create_app(test_config=None): """Application factory for the app.""" app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( SECRET_KEY='the-key', DATABASE=os.path.join(app.instance_path, 'phone_bills.sqlite'), ) db.init_app(app) if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile('config.py', silent=True) else: # load the test config if passed in app.config.from_mapping(test_config) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass app.register_blueprint(api.blueprint) return app
def create_app(additional_config=None): # Init Flask app app = Flask(__name__) CORS(app) if additional_config: app.config.update(additional_config) # Database db.init_app(app) # Blueprints app.register_blueprint(permit.blueprint) app.register_blueprint(resident.blueprint) app.register_blueprint(visitor.blueprint) # Error handling app.register_error_handler(IOError, handle_io_error) app.register_error_handler(RuntimeError, handle_runtime_error) app.register_error_handler(WebDriverException, handle_selenium_errors) app.register_error_handler(ResidentNotFoundError, handle_resident_not_found_error) app.register_error_handler(VisitorNotFoundError, handle_visitor_not_found_error) return app
def register_extensions(app: Flask) -> None: """ Registers flask extensions like `sqlalchemy` and `jwt`. :param app: A flask application :returns: Nothing """ db.init_app(app) jwt_manager.init_app(app)
def create_app(): app = Flask(__name__) configure_app(app) api.init_app(app) migrate = Migrate() db.init_app(app) migrate = Migrate(app, db) return app
def init_db(cls, app): """ Initialize database session """ logger.info("Initializing database") cls.app = app # initialize SQLAlchemy from Flask app # will create .db file in directory that models.py is located in db.init_app(app) app.app_context().push() # purpose? db.create_all()
def db(app): """ Creates an app context for the db and closes the session after execution is completed :param app: :return: """ app.app_context().push() _db.init_app(app) _db.create_all() yield _db _db.session.close() _db.drop_all()
def setup_app(): db_uri = getenv( 'SQLALCHEMY_DATABASE_URI') # format: postgresql://user:pw@host:port/db if not db_uri: abort(401) app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = db_uri app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False api.init_app(app) cache.init_app(app) db.init_app(app) return app
def setUpClass(cls): app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///test_db.db" app.testing = True with app.app_context(): db.init_app(app)
def create_app(self): app.config['TESTING'] = True app.config[ 'SQLALCHEMY_DATABASE_URI'] = "postgresql://*****:*****@localhost/trackpack_testing" db.init_app(app) return app
# vim: set et sw=4 ts=4 sts=4: from flask import Flask from flask_bootstrap import Bootstrap from api import db app = Flask(__name__, instance_relative_config=True) Bootstrap(app) app.config.from_object('config') app.config.from_pyfile('config.py') db.init_app(app) import routes if __name__ == '__main__': app.run()
def create_app(test_config=None): """Create and configure an instance of the Flask application.""" app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( # a default secret that should be overridden by instance config SECRET_KEY="dev", # store the database in the instance folder ) if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile("config.py", silent=True) else: # load the test config if passed in app.config.update(test_config) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass from api import db db.init_app(app) mongo = db.get_db(app) @app.route("/top10/<field>") def top10(field): wikipedia = mongo.db["wikipedia"] countries = wikipedia["countries"] doc_result = countries.find({}, {"_id": 0, "name": 1, field: 1}).sort(field, -1).limit(10) return (list(doc_result)).__str__() @app.route("/get-by/language/<language>") def get_by_language(language): wikipedia = mongo.db["wikipedia"] countries = wikipedia["countries"] doc_result = countries.find({"languages":language}, {"_id": 0, "name": 1}) return (list(doc_result)).__str__() @app.route("/get-by/regime/<regime>") def get_by_regime(regime): wikipedia = mongo.db["wikipedia"] countries = wikipedia["countries"] doc_result = countries.find({"government":regime}, {"_id": 0, "name": 1}) return (list(doc_result)).__str__() @app.route("/get-by/timezone/<timezone>") def get_by_timezone(timezone): wikipedia = mongo.db["wikipedia"] countries = wikipedia["countries"] doc_result = countries.find({"timezone": timezone}, {"_id": 0, "name": 1}) return (list(doc_result)).__str__() @app.route("/get/<name>") def get_by_name(name): wikipedia = mongo.db["wikipedia"] countries = wikipedia["countries"] doc_result = countries.find_one({"name": name}, {"_id": 0, "name": 1, "languages": 1}) return (list(doc_result)).__str__() return app
def register_extensions(app: Flask) -> None: db.init_app(app) api.init_app(app) qrcode.init_app(app)
def create_app(self): app.config.from_object(config_by_env['test']) db.init_app(app) return app