def app_with_test_data_in_db(): app = create_test_app() with app.app_context(): db.create_all() test_user_1 = User(username="******", email="*****@*****.**", password=bcrypt.generate_password_hash( "Password1!").decode('utf-8'), is_activated=True) test_post_1 = Post(title="test_title1", date_posted=datetime(2013, 10, 12, 8, 25, 43), content="test_content1", author=test_user_1) test_user_2 = User(username="******", email="*****@*****.**", password=bcrypt.generate_password_hash( "Password1!").decode('utf-8'), is_activated=True) test_post_2 = Post(title="test_title2", date_posted=datetime(2013, 10, 12, 8, 25, 43), content="test_content2", author=test_user_2) db.session.add(test_user_1) db.session.add(test_post_1) db.session.add(test_user_2) db.session.add(test_post_2) db.session.commit() yield app db.drop_all()
def client(): app = create_app(TestConfig) with app.app_context(): db.create_all() with app.test_client() as test_client: yield test_client with app.app_context(): db.drop_all()
def setUp(self): app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False app.config['DEBUG'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' self.app = app.test_client() db.drop_all() db.create_all() self.assertEqual(app.debug, False)
def db(app): """ Session scoped fixture that assigns the app to the database, creates the tables, yields the database object, and drops all tables once the testing session is complete. """ _db.app = app _db.create_all() yield _db _db.drop_all()
def populate(db): db.drop_all() db.create_all() user_1 = User(username='******', email='*****@*****.**', password='******') db.session.add(user_1) db.session.commit() user_2 = User(username='******', email='*****@*****.**', password='******') db.session.add(user_2) db.session.commit() user_3 = User(username='******', email='*****@*****.**', password='******') db.session.add(user_3) db.session.commit() post_1 = Post(title='Post One Title', content='Post One Content', user_id=user_1.id) db.session.add(post_1) db.session.commit() post_2 = Post(title='Post Two Title', content='Post Two Content', user_id=user_1.id) db.session.add(post_2) db.session.commit() post_3 = Post(title='Post Three Title', content='Post Three Content', user_id=user_2.id) db.session.add(post_3) db.session.commit() post_4 = Post(title='Post Four Title', content='Post Four Content', user_id=user_1.id) db.session.add(post_4) db.session.commit() post_5 = Post(title='Post Five Title', content='Post Five Content', user_id=user_2.id) db.session.add(post_5) db.session.commit() post_6 = Post(title='Post Six Title', content='Post Six Content', user_id=user_3.id) db.session.add(post_6) db.session.commit() post_4 = Post(title='Post Seven Title', content='Post Seven Content', user_id=user_1.id) db.session.add(post_4) db.session.commit()
def login(): user1 = Sessions.query.first() if user1: timea=user1.times+600 timeb=time() print timea print timeb if timeb >= timea: db.drop_all() db.create_all() return redirect(url_for('home')) else: return redirect(url_for('back')) return redirect(url_for('home'))
def init_database(): # Create the database and the database table db.create_all() # Insert user data. Two users for us to test with in our functional tests user1 = User('test_username1', '*****@*****.**', 'Passw0rd') user2 = User('user2', '*****@*****.**', 'Test123!') db.session.add(user1) db.session.add(user2) # Commit the changes for the users db.session.commit() yield db # this is where the testing happens! db.drop_all()
def tearDown(self): db.drop_all()
from flaskblog import db from flaskblog.models import User, Post db.drop_all() db.create_all() # user_1 = User(username='******', email='*****@*****.**', password='******') # db.session.add(user_1) # db.session.commit()
def db_initialize(): """ Initialize database and pre-load with data. """ db_up, _ = _check_status() if db_up == False: print("Failed DB check, aborting DB initialize.") return print("Creating schema...") try: # drop all may error if tables don't exist, eat it and assume create will work db.drop_all() except Exception as ex: print(repr(ex)) db.create_all() # try: # # just see if we can load and read the db schema for use of concept elsewhere # with current_app.open_resource("db/schema.sql") as f: # print(f.read().decode("utf8")) # # db.executescript(f.read().decode("utf8")) # except Exception as ex: # print(repr(ex)) # flash("Post deleted.", "success") print("Populating schema...") # load json data file with current_app.open_resource("db/preload.json") as preload_file: # print(f.read().decode("utf8")) data = json.load(preload_file) # app.root_path --> root of app # app.static_folder --> {app root}\static # filename = os.path.join(app.root_path, "db\\preload.json") # with open(filename) as preload_file: # data = json.load(preload_file) # populate users for user_data in data["users"]: hashed_password = bcrypt.generate_password_hash( user_data["password"]).decode("utf-8") user = User( username=user_data["username"], email=user_data["email"], password=hashed_password, ) db.session.add(user) db.session.commit() print("{} users added.".format(_get_count("user"))) # populate posts for post_data in data["posts"]: user_id = int(post_data["user_id"]) # https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior # datetime_obj = datetime.strptime(post_data["posted"], "%b %d %Y %I:%M%p") datetime_obj = datetime.strptime(post_data["posted"], "%b %d %Y %H:%M:%S") post = Post( title=post_data["title"], content=post_data["content"], user_id=user_id, posted=datetime_obj, ) db.session.add(post) db.session.commit() print("{} posts added.".format(_get_count("post")))
class Post(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100), nullable=False) date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) content = db.Column(db.Text, nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) #the reasone of 'user' in foreignkey is lowercase is because we actually refrencing the table name and column name def __repr__(self): return f"Post('{self.title}', '{self.date_posted}')" """ To create the data base: 1- open terminal and type python 2- from flaskblog import db 3- db.create_all() then the .db file will created in the path To add new data: 1- from flaskblog import User, Post 2- user_1 = User(username="******",email="*****@*****.**",password="******") : creating new user 3- db.session.add(user_1) : adding created user to db 4- db.session.commit(): commit our changes to database Some queries with SQLAlchemy: User.query.all() :will run __repr__ per each user User.query.first() User.query.filter_by(username='******').all() User.query.filter_by(username='******').first()
def tearDown(self): db.session.remove() db.drop_all()
def dropdb(): if prompt_bool("Are you sure you want to lose all your data"): db.drop_all() print('Dropped the database')
user_1=User(username='******',email='*****@*****.**',password='******') db.session.add(user_1) user_2=User(username='******',email='*****@*****.**',password='******') db.session.add(user_2) db.session.commit() #Commit to the database #Example of query to check print(User.query.all()) print(User.query.first()) print(User.query.filter_by(username='******').all()) print(User.query.filter_by(username='******').first()) user_c=User.query.filter_by(username='******').first() print(user_c) print(user_c.id) print(user_c.query.get(1)) print(user_c.posts) post_1=Post(title='Blog1',content='First Post Content',user_id=user_c.id) post_2=Post(title='Blog2',content='First Post Content',user_id=user_c.id) db.session.add(post_1) db.session.add(post_2) db.session.commit() print(user_c.posts) for post in user_c.posts: print(post.title) post_c=Post.query.first() print(post_c.user_id) print(post_c.author)#Works given backref db.drop_all()#Drops all data so far
def dropdb(): db.drop_all()