def create_app(): app = Flask(__name__, instance_relative_config=True) app.config.from_object(Config) from flaskr.models import db, login_manager db.init_app(app) login_manager.init_app(app) from flaskr.routes import view app.register_blueprint(view) return app
def kernel(self, test_config): self.app.config.from_mapping( CORS_HEADERS='Content-Type', SECRET_KEY='i4mth3b35tw3bm@5t3rh3r3', LOCAL_STORAGE=os.path.join(self.app.instance_path, 'flaskr.sqlite3'), SCHEMA=os.path.join(self.app.instance_path, 'schema.sql')) if test_config is None: self.app.config.from_pyfile('config.py', silent=True) else: self.app.config.from_mapping(test_config) try: os.makedirs(self.app.instance_path) except OSError: pass from flaskr.models import db db.init_app(self.app)
def create_app(test_config=None): # create and configure the app app = Flask(__name__, instance_relative_config=True) # configurations app.config.from_mapping( SECRET_KEY='dev', # DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'), SQLALCHEMY_TRACK_MODIFICATIONS=False, SQLALCHEMY_DATABASE_URI='sqlite:///app.db', ) 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) # initialize to app but not yet bind from flaskr.models import db db.init_app(app) # must go after loading config from flaskr.auth import login_manager login_manager.init_app(app) # initialize commands from . import commands commands.init_app(app) # init migration migrate = Migrate(app, db) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass # register blueprints from . import auth app.register_blueprint(auth.bp) return app
def create_app(test_config=None): # create and configure the app app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( SECRET_KEY='dev', SQLALCHEMY_DATABASE_URI= 'mysql+mysqlconnector://root:root@localhost:3306/test', SQLALCHEMY_TRACK_MODIFICATIONS=False) app.logger.debug(app.instance_path) 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 from flaskr.models import db db.init_app(app) from . import users app.register_blueprint(users.bp) @app.errorhandler(My_Exception) def handle_invalid_usage(error): response = jsonify(error.to_dict()) response.status_code = error.status_code return response # a simple page that says hello @app.route('/hello') def hello(): return 'Hello, World!' return app
def create_app(test_config=None): app = Flask(__name__, instance_relative_config=True) app.config.from_object(os.environ['APP_SETTINGS']) if test_config is None: app.config.from_pyfile('config.py', silent=True) else: app.config.from_mapping(test_config) try: os.makedirs(app.instance_path) except OSError: pass # Include all models from flaskr.db import init_db init_db() from flaskr.models import db db.init_app(app) # db.create_all() from flask_migrate import Migrate migrate = Migrate(app, db) # Include all routes from . import routes app.register_blueprint(routes.home) app.register_blueprint(routes.project) def list_routes(): return ['%s' % rule for rule in app.url_map.iter_rules()] print("Available Routes: ", list_routes()) return app
from config import Config, Logger from flaskr.models import db, Settings, Stats from flaskr import create_app print('Setup started (log to {0})'.format(Logger.LOG_FILENAME)) Logger.logger.debug('Setup started') database_file = Config.SQLALCHEMY_DATABASE_FILENAME if os.path.exists(database_file): Logger.logger.debug('Remove DB {0}'.format(database_file)) os.remove(database_file) app = create_app() with app.test_request_context(): app.config.from_object(Config) db.init_app(app) Logger.logger.debug('Create DB {0}'.format(database_file)) db.create_all() Logger.logger.debug('Populate Settings DB {0}'.format(database_file)) settings = Settings(temperatureUm='°C', humidityUm='%', pressureUm='mBar', readFromSensorInterval=10, minDeltaDataTrigger=0.5, temperatureCorrection=0.0, humidityCorrection=0, pressureCorrection=0, storeStatsDataLimit=0, showLastEvent=False) db.session.add(settings)
def create_app(test_config=None): # create and configure the app # true means will load config.py from the instance folder app = Flask(__name__, instance_relative_config=True, static_folder='../build', static_url_path='/') # ensure the instance folder exists (by creating the folder) try: os.makedirs(app.instance_path) except OSError: pass # from_mapping accepts **kwargs arguments (keyword pairs such as first ='Geeks', mid ='for', last='Geeks') app.config.from_mapping( SECRET_KEY='dev', # DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'), ) if test_config is None: # the config.py exists in the instance folder (neighbour to /flaskr) # load the instance config, if it exists, when not testing # loaded variables are config variables, not env variables # env variables are loaded by dot-env by default (should be specified in .flaskenv) app.config.from_pyfile('config.py', silent=True) elif test_config == 'azure': app.config.from_pyfile('azure_config.py', silent=True) else: # load the test config if passed in successfully app.config.from_mapping(test_config) # custom Encoder to parse datetime object app.json_encoder = custom_json_encoder.CustomJSONEncoder # initialize the SQLAlchemy plugin # this db has already been passed through model definitions db.init_app(app) # initialize JWT authentication system jwt_manager.init_app(app) # bind the db to this particular instance of app # no need to to clean up application context (with already handles that) # no need to clean up session of SQLAlchemy (Flask extension already handles that) with app.app_context(): # creating our tables db.create_all() # import parts of our application from flaskr.routes import anime_routes from flaskr.routes import user_routes # register our blueprints app.register_blueprint(anime_routes.bp) app.register_blueprint(user_routes.bp) # a simple page that tests deployment @app.route('/test_deploy') def test_deploy(): return 'Deploy on Azure successfully!' @app.route('/add_anime') def add_anime(): # committing mock data (probably real data right now) # can always commit airing_start_str additionally for i in range(len(id_anime)): to_add = Anime( anime_id=id_anime[i], name=name_anime[i], name_eng=name_eng_anime[i], name_jpn=name_jpn_anime[i], num_episodes=num_episodes_anime[i], source=source_anime[i], members=members_anime[i], favorites=favorites_anime[i], status=status_anime[i], rank=rank_anime[i], popularity=popularity_anime[i], scored_by=scored_by_anime[i], duration=duration_anime[i], synopsis=synopsis_anime[i], background=background_anime[i], rating=rating_anime[i], anime_type=type_anime[i], airing_start=airing_start_anime[i], airing_end=airing_end_anime[i], airing_str=airing_str_anime[i], anime_image_path=image_path_anime[i], mal_anime_image_path=mal_image_path_anime[i], trailer_url=trailer_url_anime[i] ) # SQL Alchemy automatically handle genre and studio models to us for j in anime_genre_rel[i]: to_add.genre.append(Genre(genre_id=j[0], genre_name=j[1])) for j in anime_studio_rel[i]: to_add.studio.append(Studio(studio_id=j[0], studio_name=j[1])) db.session.merge(to_add) db.session.commit() return '<img src="https://media1.tenor.com/images/678955ca4337fc9a61ceb342ecb26760/tenor.gif?itemid=7905894" title="i love emilia">' # a simple page that tests the React build directory @app.errorhandler(404) def not_found(e): return app.send_static_file('index.html') @app.route('/test') def test(): to_add = Favorites( user_id="0x2A5377A0BBF54DACBE9712008D001138", anime_id=33042) db.session.merge(to_add) db.session.commit() return '<img src="https://media1.tenor.com/images/72a449017113abf6716656a18ac85582/tenor.gif?itemid=17382357" title="yukino best girl">' @app.route('/test_review') def test_review(): to_add = Review( review_id = uuid.uuid4(), user_id = uuid.uuid4(), anime_id = "12345", review_rating = "100", review_content = "hi! this is alex" ) db.session.merge(to_add) db.session.commit() return 'test_review finished!' return app
def create_app(test_config=None): # create and configure the app app = Flask(__name__, instance_relative_config=True) # configurations app.config.from_mapping( SECRET_KEY='dev', # DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'), SQLALCHEMY_TRACK_MODIFICATIONS=False, SQLALCHEMY_DATABASE_URI='sqlite:///app.db', JWT_SECRET_KEY='hide-this-for-dear-life', SWAGGER_UI_DOC_EXPANSION='list', ) 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) CORS(app) import logging, logging.config, yaml # load the log configurations log_conf = yaml.safe_load(open('./logging.yaml')) # use the log configuration logging.config.dictConfig(log_conf) # init a log instance log = logging.getLogger('werkzeug') log.disabled = False # register the SQLAlchemy instance with flask from flaskr.models import db db.init_app(app) # register the Marshmallow instance with flask from flaskr.schemas import ma ma.init_app(app) # register the Login_Manager instance with flask from flaskr.auth import login_manager login_manager.init_app(app) # register the API from flaskr.swagger import api api.init_app(app) # registers the custom commands with flask from . import commands commands.init_app(app) # registers the migrations with flask migrate = Migrate(app, db) # registers the api blueprints with flask from . import auth, admin, product, data, swagger, service app.register_blueprint(auth.bp) app.register_blueprint(admin.bp) app.register_blueprint(product.bp) app.register_blueprint(data.bp) app.register_blueprint(swagger.bp) app.register_blueprint(service.bp) from flaskr.jwt import jwt jwt.init_app(app) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass return app
def initialize_app(flask_app: Flask) -> None: configure_app(flask_app) api.init_app(flask_app) db.init_app(flask_app) db.create_all(app=flask_app)
def create_app(test_config=None): # create and configure the app app = Flask(__name__, instance_relative_config=True) ENV = 'dev' if ENV == 'dev': app.debug = True app.config[ 'SQLALCHEMY_DATABASE_URI'] = 'postgresql://*****:*****@localhost/blog' else: app.debug = False app.config[ 'SQLALCHEMY_DATABASE_URI'] = 'postgres://*****:*****@ec2-54-163-47-62.compute-1.amazonaws.com:5432/d7u95b7c4klkag' app.config.from_mapping(SQLALCHEMY_TRACK_MODIFICATIONS=False, SECRET_KEY='dev') # Here we enable CSRF protection for our app csrf.init_app(app) # Here we initalize db with app, this make is more abstract and give us a better flexibility in package db.init_app(app) # We add Flask Migrate for easyer work on database migrate = Migrate(app, db) login_manager = LoginManager() login_manager.login_view = "auth.login" login_manager.init_app(app) # This associate user cookie with user model id @login_manager.user_loader def load_user(user_id): return User.query.get(user_id) 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 # a simple page that says hello @app.route('/hello') def hello(): return "Hello, World!" # Blueprints section from flaskr.auth import auth app.register_blueprint(auth) from flaskr.blog import blog app.register_blueprint(blog) app.add_url_rule("/", endpoint='index') return app
def create_app(): db.init_app(app) return app