def setUp(self): self.app = create_app() self.client = self.app.test_client setup_db(self.app, 'trivia_test') db.drop_all() db.create_all() self.temp_categories = [ Category('Science'), Category('Art'), Category('Geography'), Category('History'), Category('Entertainment'), Category('Sports') ] self.temp_questions = [ Question('Whose autobiography is entitled \'I Know Why the Caged Bird Sings\'?', 'Maya Angelou', 2, 4), Question('What boxer\'s original name is Cassius Clay?', 'Muhammad Ali', 1, 4), Question('The Taj Mahal is located in which Indian city?', 'Agra', 2, 3), Question('Which Dutch graphic artist–initials M C was a creator of optical illusions?', 'Escher', 1, 2), Question('What is the heaviest organ in the human body?', 'The Liver', 4, 1) ] db.session.add_all(self.temp_categories) db.session.add_all(self.temp_questions) db.session.commit()
def setUp(self): self.app = create_app() self.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{}'.format( path.join(path.dirname(__file__), 'test.db')) self.client = self.app.test_client() with self.app.app_context(): db.create_all()
def test_get_categories_fail_no_categories(self): db.drop_all() db.create_all() res = self.client().get('/categories') status = res.status_code data = json.loads(res.data) # check status and data self.assertEqual(status, 404) self.assertTrue('success' in data) self.assertTrue('error' in data) self.assertTrue('description' in data) self.assertTrue('message' in data) # check success self.assertFalse(data['success']) self.assertEqual(data['error'], 404) self.assertEqual(data['description'], 'no categories found') self.assertEqual(data['message'], 'not found')
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) Logger.logger.debug('Populate Stats DB {0}'.format(database_file))
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
from flaskr import app from flaskr.models import db, User, session from flaskr import views import sys print("db.create_all()") db.create_all() # create database if not already there users = session().query(User).all() print(users) print(f"app.run() sys.argv={sys.argv[1:]}") # start Flask web service if '--local' in sys.argv: app.run(host='127.0.0.1', debug=True, port=80) else: app.run(host='0.0.0.0', debug=True, port=80)
def create_db(): db.drop_all() db.create_all() db.session.commit() print('Done\n')
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 init_db(): with app.app_context(): db.create_all()