def setUp(self): app = Flask("tests", static_url_path="/static") app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:////tmp/test_idb.db" db.init_app(app) db.app = app db.configure_mappers() db.create_all()
def create_app(): app = Flask(__name__) app.secret_key = 'super~~~~~~~~~~~~' # url app.register_blueprint(welcome_page) app.register_blueprint(auth_page) # db if socket.gethostname() == 'lihaichuangdeMac-mini.local': print(1) app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://sctlee:[email protected]:3306/singledog' else: print(2) conn_string = 'mysql+pymysql://%s:%s@%s:%s/%s' % (os.getenv('MYSQL_USERNAME'), os.getenv('MYSQL_PASSWORD'),\ os.getenv('MYSQL_PORT_3306_TCP_ADDR'), os.getenv('MYSQL_PORT_3306_TCP_PORT'),\ os.getenv('MYSQL_INSTANCE_NAME')) print(conn_string) app.config['SQLALCHEMY_DATABASE_URI'] = conn_string db.init_app(app) from models import User db.create_all(app=app) # login manager login_manager.init_app(app) @app.before_request def before_request(): g.user = current_user return app
def run(self): db.drop_all() db.create_all() db.session.add(Group('Diggers', 'Preschool')) db.session.add(Group('Discoverers', 'Year R-2')) db.session.add(Group('Explorers', 'Years 3-6')) db.session.commit()
def home(): db.create_all() print request.values.get('From') + " said: " + request.values.get('Body') number = Numbers(request.values.get('From')) resp = twilio.twiml.Response() resp.message("Thx for stopping by Intro to API's at HackHERS! For all material, check out: https://goo.gl/2knLba") return str(resp)
def startup(): # db initializations db.create_all() settings = Settings(secret_key=pyotp.random_base32()) db.session.add(settings) db.session.commit()
def setUp(self): db.create_all() a_simple_model = SimpleModel() a_simple_model.app_name = "simple_app" db.session.add(a_simple_model) db.session.commit()
def test(): from cron import poll # Make sure tables exist. If not, create them try: db.session.query(User).first() db.session.query(Snipe).first() except Exception: db.create_all() soc = Soc() math_courses = soc.get_courses(640) open_courses = poll(640, result = True) for dept, sections in open_courses.iteritems(): open_courses[dept] = [section.number for section in sections] success = True for math_course in math_courses: course_number = math_course['courseNumber'] if course_number.isdigit(): course_number = str(int(course_number)) for section in math_course['sections']: section_number = section['number'] if section_number.isdigit(): section_number = str(int(section_number)) if section['openStatus'] and not section_number in open_courses[course_number]: raise Exception('Test failed') success = False return success
def setUp(self): """ Set up the database for use :return: no return """ db.create_all()
def init_db(): db.drop_all() db.create_all() type_ids = {} rate_type_ids = {} for type_name in ["office", "meeting", "other"]: t = ListingType(type_name) db.session.add(t) db.session.commit() type_ids[type_name] = t for type_name in ["Hour", "Day", "Week", "Month", "3 Months", "6 Months", "Year"]: t = RateType(type_name) db.session.add(t) db.session.commit() rate_type_ids[type_name] = t db.session.add(Listing(address="1500 Union Ave #2500, Baltimore, MD", lat="39.334497", lon="-76.64081", name="Headquarters for Maryland Nonprofits", space_type=type_ids["office"], price=2500, description="""Set in beautiful downtown Baltimore, this is the perfect space for you. 1800 sq ft., with spacious meeting rooms. Large windows, free wifi, free parking, quiet neighbors.""", contact_phone="55555555555", rate_type=rate_type_ids['Month'])) db.session.add(Listing(address="6695 Dobbin Rd, Columbia, MD", lat="39.186198", lon="-76.824842", name="Frisco Taphouse and Brewery", space_type=type_ids["meeting"], price=1700, description="""Large open space in a quiet subdivision near Columbia. High ceilings, lots of parking, good beer selection.""", rate_type=rate_type_ids['Day'], contact_phone="55555555555", expires_in_days=-1)) db.session.add(Account("admin", "*****@*****.**", "Pass1234")) db.session.commit()
def create_app(): app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///stress.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.init_app(app) with app.app_context(): db.create_all() return app
def create_app(): app = flask.Flask("app") app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' app.register_blueprint(api) db.init_app(app) with app.app_context(): db.create_all() return app
def run(app=app): """ Creates the database in the application context :return: no return """ with app.app_context(): db.create_all() db.session.commit()
def testdb(): #if db.session.query("1").from_statement("SELECT 1").all(): # return 'It works.' #else: # return 'Something is broken.' db.drop_all() db.create_all() return "i got here"
def setUp(self): self.app = create_app('test_config') self.test_client = self.app.test_client() self.app_context = self.app.app_context() self.app_context.push() self.test_user_name = 'testuser' self.test_user_password = '******' db.create_all()
def setUp(self): """ Set up the database for use :return: no return """ db.create_all() self.stub_library, self.stub_uid = StubDataLibrary().make_stub() self.stub_document = StubDataDocument().make_stub()
def create_app(): api = Flask('api') api.register_blueprint(person_blueprint) db.init_app(api) with api.app_context(): db.create_all() return api
def init_db(): if app.config['DB_CREATED']: app.logger.warning('Someone (%s) tried to access init_db' % get_client_ip()) return redirect( url_for('show_index') ) else: db.create_all() app.logger.info('%s created database tables with /init_db' % get_client_ip()) flash('Database created, please update config.py') return redirect( url_for('show_index') )
def init_db(): if app.config["DB_CREATED"]: app.logger.warning("Someone (%s) tried to access init_db" % get_client_ip()) return redirect(url_for("show_index")) else: db.create_all() app.logger.info("%s created database tables with /init_db" % get_client_ip()) flash("Database created, please update config.py") return redirect(url_for("show_index"))
def create_app(): """Create your application.""" app = Flask(__name__) app.config.from_object(settings) app.register_module(views) db.app = app db.init_app(app) db.create_all() return app
def create_app(): app = flask.Flask("app") app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://*****:*****@127.0.0.1/clientmanager' db.init_app(app) with app.app_context(): # Extensions like Flask-SQLAlchemy now know what the "current" app # is while within this block. Therefore, you can now run........ db.create_all() return None
def init_db(): """Create database with tables defined in models. Also create demo user""" app = create_app() with app.test_request_context(): db.init_app(app) db.create_all() # create user user = User(email='admin@localhost', password='******', active=True) db.session.add(user) db.session.commit()
def create_db(): db.drop_all() # db.configure_mappers() db.create_all() create_characters() create_houses() create_books() db.session.commit()
def createdb(testdata=False): """Initializes the database""" app = create_app() with app.app_context(): db.drop_all() db.create_all() if testdata: user = User(username='******', password='******') db.session.add(user) db.session.commit()
def create_app(): app = Flask(__name__, template_folder='templates') app.debug = True app.secret_key = 'secret' app.config.update({ 'SQLALCHEMY_DATABASE_URI': 'sqlite:///db.sqlite' }) db.init_app(app) with app.app_context(): db.create_all() return app
def setup_database(*args, **kwargs): file_path = 'tmp/reader.db' # Create tmp folder if it doesn't exist if not os.path.exists('tmp'): os.mkdir('tmp') # If an old database does not exist if not os.path.exists(file_path): # Make new database file = open(file_path, 'w+') file.close() db.create_all()
def configure_database(self): """ Database configuration should be set here """ #db = SQLAlchemy() db.init_app(self) with self.app_context(): db.create_all() #db = SQLAlchemy(self) pass
def setUpClass(cls): cls.app = app cls.app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://*****:*****@localhost:5432/test_factory_boy' cls.app.config['SQLALCHEMY_ECHO'] = True db.app = cls.app db.init_app(cls.app) cls._ctx = cls.app.test_request_context() cls._ctx.push() db.drop_all() db.create_all()
def create_app(config): iq_app = Flask(__name__) iq_app.config.from_object(config) iq_app.secret_key = '1ll#%@%^LJ2sd#lj23@$^-' with iq_app.app_context(): db.init_app(iq_app) db.create_all() iq_app.register_blueprint(iq_views) return iq_app
def create_json_app(config): app = Flask(__name__) CORS(app) app.config.from_object(config) for code in default_exceptions.iterkeys(): app.error_handler_spec[None][code] = make_json_error db.init_app(app) with app.app_context(): db.create_all() app.app_context().push() return app
def setUp(self): self.app = app.test_client() app.config['SQLALCHEMY_DATABASE_URI'] = \ 'postgresql+psycopg2://%(username)s:%(password)s@localhost/%(database_name)s' % { 'username': Config.DB_USER, 'password': Config.DB_PASSWORD, 'database_name': Config.TEST_DATABASE_URI } app.config['TESTING'] = True db.create_all()
def startup(): db.create_all()
def setup(): db.create_all()
def setUpClass(cls): db.drop_all() db.create_all() # populate test database with open('seed.py', "r") as f: exec(f.read())
# BEFORE we import our app, let's set an environmental variable # to use a different database for tests (we need to do this # before we import our app, since that will have already # connected to the database os.environ['DATABASE_URL'] = "postgresql:///warbler_test" # Now we can import app from app import app # Create our tables (we do this here, so we only create the tables # once for all tests --- in each test, we'll delete the data # and create fresh new clean test data db.create_all() class UserModelTestCase(TestCase): """Test views for messages.""" def setUp(self): """Create test client, add sample data.""" User.query.delete() Message.query.delete() Follows.query.delete() self.client = app.test_client() user1 = User( email="*****@*****.**",
def create_db(): db.create_all() return "Created"
from main import app from models import db, User, Course db.create_all(app=app) print('database initialized!')
def setUp(self): """Create test client and add sample data.""" db.drop_all() db.create_all() self.client = app.test_client() self.test_user_1 = User.signup("user1", "*****@*****.**", "password1") self.test_user_2 = User.signup("user2", "*****@*****.**", "password2") db.session.add(self.test_user_1) db.session.add(self.test_user_2) db.session.commit() self.uid_1 = self.test_user_1.id self.uid_2 = self.test_user_2.id self.song_a = Song( user_id=self.uid_1, title="Song A", artist="Artist 1", ) self.song_b = Song( user_id=self.uid_2, title="Song B", artist="Artist 2", ) self.song_c = Song( user_id=self.uid_1, title="Song C", artist="Artist 3", ) self.lyrics_test_song = Song( user_id=self.uid_1, title="Never Gonna Give You Up", artist="Rick Astley", ) self.test_setlist = Setlist(user_id=self.uid_1, name="Test Setlist 1") db.session.add(self.song_a) db.session.add(self.song_b) db.session.add(self.song_c) db.session.add(self.lyrics_test_song) db.session.add(self.test_setlist) db.session.commit() self.lyrics_song_id = self.lyrics_test_song.id self.setlist_id = self.test_setlist.id setlist_song_0 = SetlistSong(setlist_id=self.setlist_id, song_id=self.song_b.id, index=0) setlist_song_1 = SetlistSong(setlist_id=self.setlist_id, song_id=self.song_a.id, index=1) setlist_song_2 = SetlistSong(setlist_id=self.setlist_id, song_id=self.song_c.id, index=2) self.test_setlist.setlist_songs.append(setlist_song_0) self.test_setlist.setlist_songs.append(setlist_song_1) self.test_setlist.setlist_songs.append(setlist_song_2) db.session.add(self.test_setlist) db.session.commit()
def initdb_command(): db.drop_all() db.create_all() populateDB() print('Initialized the database.')
def create_database(): db.create_all()
def create_all(): db.create_all()
def create_app(): db.drop_all() db.create_all()
def test_db(test_app): db.drop_all() db.create_all() yield test_db db.session.remove() db.drop_all()
def setUp(self): """Add sample data. Create test client.""" # drop the database tables and recreate them db.drop_all() db.create_all() user1 = User.signup("*****@*****.**", "allison", "allison", "Allison", "McAllison", None) user1.id = 1111 user2 = User.signup("*****@*****.**", "jackson", "jackson", "Jackson", "McJackson", None) user2.id = 2222 db.session.commit() self.user1 = user1 self.user2 = user2 # Create a course course1 = Course(title="Jackson's Course Title", description="Jackson's Course Description", creator_id="2222") db.session.add(course1) db.session.commit() self.c = course1 # Add two videos to the course video1 = Video( title="Video1", description="Desc for Video1", yt_video_id="yfoY53QXEnI", yt_channel_id="video1video1", yt_channel_title="Video1 Channel", thumb_url="https://i.ytimg.com/vi/yfoY53QXEnI/hqdefault.jpg") video2 = Video( title="Video2", description="Desc for Video2", yt_video_id="1PnVor36_40", yt_channel_id="video2video2", yt_channel_title="Video2 Channel", thumb_url="https://i.ytimg.com/vi/1PnVor36_40/hqdefault.jpg") db.session.add(video1) db.session.add(video2) db.session.commit() self.v1 = video1 self.v2 = video2 vc1 = VideoCourse(course_id=self.c.id, video_id=self.v1.id, video_seq=1) vc2 = VideoCourse(course_id=self.c.id, video_id=self.v2.id, video_seq=2) db.session.add(vc1) db.session.add(vc2) db.session.commit() self.vc1 = vc1 self.vc2 = vc2 # set the testing client server self.client = app.test_client()
return TaskBase.__call__(self, *args, **kwargs) celery.Task = ContextTask return celery poll_io = Flask(__name__) poll_io.register_blueprint(api) # Load config setting from config.py poll_io.config.from_object('config') # Initialize and create Database db.init_app(poll_io) db.create_all(app=poll_io) migrate = Migrate(poll_io, db, render_as_batch=True) celery = make_celery(poll_io) admin = Admin(poll_io, name='Dashboard', index_view=TopicView(Topics, db.session, url='/admin', endpoint='admin')) admin.add_view(AdminView(Polls, db.session)) admin.add_view(AdminView(Options, db.session)) admin.add_view(AdminView(Users, db.session)) admin.add_view(AdminView(UserPolls, db.session))
def setUp(self): """ It creates the memory db """ db.create_all()
def trunCate(self): db.drop_all() db.create_all()
def setUp(self): app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db' app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False self.app = app.test_client() db.create_all()
def setUp(self): stripe.api_key = 'sk_test_OM2dp9YnI2w5eNuUKtrxd56g' db.drop_all() db.create_all()
def setUp(self): # camelCase required """ Sets up test music_logger app """ self.db_fd, music_logger.app.config['DATABASE'] = tempfile.mkstemp() self.client = music_logger.app.test_client() with music_logger.app.app_context(): db.create_all()
def create_db_command(): """Search for tables and if there is no data create new tables.""" print('DB Engine: ' + app.config['SQLALCHEMY_DATABASE_URI'].split(':')[0]) db.create_all(app=app) print('Initialized the database.')
jwt = JWTManager(app) # ------------------------------------------- migrate = Migrate() # ------------------------------------------------------------------------------------------------------------------------------------------------------------ # flask db init 명령은 최초 한번만 수행하면 된다. 앞으로 모델을 추가하고 변경할때는 flask db migrate와 flask db upgrade 명령 두개만 반복적으로 사용하면 된다. # flask db migrate - 모델을 신규로 생성하거나 변경할때 사용 # flask db upgrade - 변경된 내용을 적용할때 사용 # ------------------------------------------------------------------------------------------------------------------------------------------------------------ pymysql.install_as_MySQLdb() #mysql Connector가 pymysql을 사용 db.init_app(app) migrate.init_app(app, db) db.app = app db.create_all() # db를 초기화 해줌 테이블을 만든다 여기서 오류가 난다 @app.route('/') def main(): return render_template('main.html') @app.route('/post') def post(): return render_template('post.html') @app.route('/signup') def signup(): return render_template('signup.html') @app.route('/login') def login():
def tearDown(self): # db.session.rollback() # breakpoint() db.drop_all() db.create_all()
def tearDown(self): db.session.remove() db.drop_all() db.create_all()
def tearDown(self) -> None: """ Method runs after every test. Remove data from database. """ with self.app.app_context(): db.drop_all() db.create_all()
import hashlib import random import uuid from flask import Flask, render_template, request, make_response, redirect, url_for from models import User, db app = Flask(__name__) db.create_all() # create (new) tables in the database @app.route("/", methods=["GET"]) def index(): session_token = request.cookies.get("session_token") if session_token: user = db.query(User).filter_by(session_token=session_token).first() else: user = None return render_template("index.html", user=user) @app.route("/profile", methods=["GET"]) def profile(): session_token = request.cookies.get("session_token") # get user from the database based on her/his email address user = db.query(User).filter_by(session_token=session_token).first() if user:
def migration(): # aqui alteramos o banco engine = create_engine(environ.get('SQLALCHEMY_DATABASE_URI')) # <ClassModelName>.__table__.drop(engine) db.create_all()
def setUpClass(cls) -> None: """ Method runs once for the entire test class before tests. Creating connection to database. """ with cls.app.app_context(): db.drop_all() db.create_all()
def db_built(): db.drop_all() db.create_all()
def activate_job(): db.create_all()
def create_table(): db.create_all()