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 home(): db.create_all() page = request.args.get('page', 1, type=int) posts = Post.query.order_by(Post.date_posted.desc()).paginate(page=page, per_page=5) return render_template('home.html', posts=posts)
def genData(): #db.drop_all() db.create_all() print('just reset database inside genData') for x in employeeData: newEmployee = Employees(Employee_ID=x[0], name=x[1], title=x[2], salary=x[3], join_date=x[4]) print(newEmployee) db.session.add(newEmployee) hashed_password = bcrypt.generate_password_hash('Password123').decode( 'utf-8') user = User(username='******', email='*****@*****.**', password=hashed_password) db.session.add(user) try: db.session.commit() except: db.session.rollback()
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 home(): db.create_all() queriest = QueryT.query.filter_by(user_id=session.sid) try: queriest[0] except IndexError: flash(Markup('''Create a <a href="/queriest/new">new query!</a>'''), 'success') page = request.args.get('page', 1, type=int) queriest = queriest.order_by(QueryT.date_posted.desc()).paginate(page=page, per_page=5) return render_template('home.html', queriest=queriest, active1="active", active2="")
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 register(): #if current_user.is_authenticated: # return redirect(url_for('main.home')) form = RegistrationForm() if form.validate_on_submit(): hashed_pw = bcrypt.generate_password_hash(form.password.data).decode('utf-8') user = User(username=form.username.data,email=form.email.data,password=hashed_pw) db.create_all() db.session.add(user) db.session.commit() flash(f'You account has been created successfully !!','success') return redirect(url_for('users.login')) return render_template('register.html', title='Register', form=form)
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 new_post(): form = PostForm() if form.validate_on_submit(): post = Post(title=form.title.data, content=form.content.data, author=current_user) db.session.add(post) db.session.commit() db.create_all() flash('Your post has been created!', 'success') return redirect(url_for('main.home')) return render_template('create_post.html', title='New Post', form=form, legend='New Post')
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 register(): """registration authentication""" if current_user.is_authenticated: return redirect(url_for("main.home")) form = RegistrationForm() # tells if form was validated during submission if form.validate_on_submit(): db.create_all() hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8') user = User(username=form.username.data, email=form.email.data, password=hashed_password) db.session.add(user) db.session.commit() flash("Your account has been created. You may now log in!", "success") return redirect(url_for("users.login")) return render_template("register.html", title="Register", form=form)
def signup(): if current_user.is_authenticated: return redirect(url_for('user_again')) form = Registration() if form.validate_on_submit(): db.create_all() hash_pass = bcrypt.generate_password_hash( form.password.data).decode('utf-8') user1 = People(username=form.username.data, email=form.username.data, password=hash_pass) db.session.add(user1) db.session.commit() flash('Your account has been created..You can now Login ', 'success') return redirect(url_for('user')) return render_template("signup.html", title="register", form=form)
def reset_token(token): """this is where they enter a new password, after verifying the email""" if current_user.is_authenticated: return redirect(url_for("main.home")) user = User.verify_reset_token(token) if user is None: flash("That is an invalid or expired token", "warning") return redirect(url_for("users.reset_request")) form = ResetPasswordForm() if form.validate_on_submit(): db.create_all() hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8') user.password = hashed_password db.session.commit() flash("Your password has been reset. You may now log in!", "success") return redirect(url_for("users.login")) return render_template("reset_token.html", title="Reset Password", form=form)
def comment_post(post_id): post = Post.query.get_or_404(post_id) form = AddCommentForm() if form.validate_on_submit(): db.create_all() if current_user.is_authenticated: comment = Comment(body=form.body.data, post_id=post_id, username=current_user.username, comment_user_id=current_user.id) else: comment = Comment(body=form.body.data, post_id=post_id, username='******') db.session.add(comment) db.session.commit() flash('Your comment has been added to the post', 'success') return redirect(url_for('post', post_id=post_id)) return render_template('post.html', title=post.title, form=form, post=post)
class Post(db.Model): __tablename__ = "post" 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) def __repr__(self): return f"Post('{self.title}', '{self.date_posted}')" db.create_all()
def home(filter=1): db.create_all() page = request.args.get(str(filter) + 'page', 1, type=int) if (filter == 1): posts = Post.query.order_by(Post.date_posted.desc()).paginate( page=page, per_page=5) elif (filter == 2): posts = Post.query.order_by(Post.date_posted.asc()).paginate( page=page, per_page=5) elif (filter == 3): posts = db.session.query(Post).join(UpVote).group_by(Post.id).order_by( func.count().desc()).paginate(page=page, per_page=5) #if user is logged in he must have right to like post if current_user.is_authenticated: return render_template('home.html', posts=posts, upvote=get_current_user_like(), likelist=get_total_post_like()) #if user is logged out he can only see total likes else: return render_template('index.html', posts=posts, likelist=get_total_post_like())
def __repr__(self): return '<Event %r %r %r>' % self.date % self.time % self.np class Club(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(60), nullable=False) address = db.Column(db.String(240), nullable=False) phone = db.Column(db.String(60), nullable=False, unique=True) events_2 = db.relationship('Event', backref='place', lazy=True) def __repr__(self): return '<Club %r %r %r>' % self.name % self.address % self.phone class Sport(db.Model): __tablename__ = 'sport' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(60), nullable=False) sport_played = db.relationship('SportPlayed', foreign_keys=[SportPlayed.s_id], backref='sport', lazy=True) events_4 = db.relationship('Event', backref='sportevent', lazy=True) def __repr__(self): return '<Sport %r>' % self.name db.create_all()
def create_tables(): db.create_all()
from flaskblog import db, create_app import os if os.path.exists( os.path.join( os.getcwd(), 'flaskblog', os.getenv('SQLALCHEMY_DATABASE_URI').split('///')[1])) is False: db.create_all(app=create_app()) app = create_app() if __name__ == '__main__': app.run(debug=True, port=8080)
id = db.Column(db.Integer, primary_key=True) image_file = db.Column(db.String(20), nullable=False, default='carousel/boats.jpg') description = db.Column(db.String(100), nullable=False) date_posted = db.Column(db.DateTime, index=True, nullable=False, default=datetime.utcnow) seller_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) def __repr__(self): return f"Post('{self.description}', '{self.date_posted}')" ''' from flaskblog import db db.create_all() from flaskblog.models import Seller s1 = User(username='******', fullname='Haresh Hambire', email='*****@*****.**', address='Mahim',password='******', points=0) db.session.add(s1) db.session.commit() Seller.query.all() Seller.query.filter_by(username='******').all() ... returns list Seller.query.filter_by(username='******').first() ... returns single item u2.followed.append(u1) >>> u1.followers <sqlalchemy.orm.dynamic.AppenderBaseQuery object at 0x7f58877ea470> >>> u1.followers.username
def setUp(self): self.app = app.test_client() db.create_all() self.assertEqual(app.debug, False)
def initdb(): db.create_all()
'date': 'Aug. 27th 2019', 'content': 'This is Pavly Salah\'s submission for the \ Digizilla Task. \ Framework used: Flask' }, { 'author': 'John Doe', 'title': 'Dummy Title', 'date': 'Aug. 27th 2019', 'content': 'Hello, my name is John Doe and I do not really exist!' }] home_title = 'Home Page' about_title = 'About Page' db.create_all( ) # To create the database containing User and Post from models.py # Home page @app.route("/") # Decorator @app.route("/home" ) # Having two decorators for a single page -- '/home' and '/' def home(): return render_template( 'home.html', posts=posts, title=home_title ) # Rendering a template page. Passing the 'posts' variable in order to be able to access it in the HTML template. Note that these paramters are user-defined # About Page @app.route("/about") def about():
def setUp(self): app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' db.create_all()
def init_db(): db.create_all() 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")))
def home(): db.create_all() posts = Post.query.limit(5).all() return render_template('home.html', posts=posts)
def home(): db.create_all() return render_template('home.html', posts=posts)