def test_get_close_db(app): with app.app_context(): db = get_db() assert db is get_db() with pytest.raises(sqlite3.ProgrammingError) as e: db.execute('SELECT 1') assert 'closed' in str(e)
def index(): add_post_form = PostForm() if request.method == "GET": # get the DB connection db = get_db() # retrieve all posts posts = db.execute( 'SELECT p.id, title, body, created, author_id, firstname , lastname, likes, dislikes' ' FROM post p JOIN user u ON p.author_id = u.id' ' ORDER BY created DESC' ).fetchall() # render 'blog' blueprint with posts # return render_template('blog/index.html', posts = posts ) else : if add_post_form.validate_on_submit(): # read post values from the form title = add_post_form.title.data body = add_post_form.body.data # read the 'uid' from the session for the current logged in user author_id = session['uid'] # get the DB connection db = get_db() # insert post into database try: # execute the SQL insert statement db.execute("INSERT INTO post (author_id, title, body) VALUES (?, ?,?);", (author_id, title, body)) # commit changes to the database db.commit() flash('You were successfully Add') return redirect('/posts') except sqlite3.Error as er: print(f"SQLite error: { (' '.join(er.args)) }") return redirect("/404") # if the user is not logged in, redirect to '/login' if "uid" not in session: return redirect('/login') # else, render the template return render_template("blog/index.html", form = add_post_form , posts = posts)
def app(): db_fd, db_path = tempfile.mkstemp() app = create_app({ 'TESTING': True, 'DATABASE': db_path, }) with app.app_context(): init_db() get_db().executescript(_data_sql) yield app os.close(db_fd) os.unlink(db_path)
def login(): """Log in a registered user by adding the user id to the session.""" if request.method == 'POST': username = request.form['username'] password = request.form['password'] db = get_db() error = None user = db.execute( 'SELECT * FROM user WHERE username = ?', (username,) ).fetchone() if user is None: error = 'Incorrect username.' elif not check_password_hash(user['password'], password): error = 'Incorrect password.' if error is None: # store the user id in a new session and return to the index session.clear() session['user_id'] = user['id'] return redirect(url_for('index')) flash(error) return render_template('auth/login.html')
def add_user(): if request.method == 'GET': # render add user blueprint return render_template('user/index.html') else: username = request.form['username'] first_name = request.form['first_name'] last_name = request.form['last_name'] password = request.form['password'] # get the DB connection db = get_db() # insert user into DB try: # execute our insert SQL statement db.execute( "INSERT INTO user (username, password, firstname, lastname) VALUES (?, ?, ?, ?);", (username, password, first_name, last_name)) # write changes to DB db.commit() return redirect(url_for('/home')) except sqlite3.Error as er: print('SQLite error: %s' % (' '.join(er.args))) return redirect("/404")
def add_post(): add_post_form = AddPostForm if add_post.validate_on_submit(): # read post values from the form title = add_post_form.title.data body = add_post_form.body.data # read the 'uid' from the session for the current logged in user author_id = session['uid'] # get the DB connection db = get_db() # insert post into database try: # execute the SQL insert statement db.execute("INSERT INTO post (author_id, title, body) VALUES (?, ?,?);", (author_id,title, body)) # commit changes to the database db.commit() return redirect('/posts') except sqlite3.Error as er: print('SQLite error: %s' % (' '.join(er.args))) return redirect("/404") else: # if the user is not logged in, redirect to '/login' if "uid" not in session: return redirect('/login') # else, render the template return render_template("blog/add-post.html")
def login(): #create an instance of the form login=LoginForm() if login.validate_on_submit(): #read values from loginform username=login.username.data password=login.password.data # get the DB connection db = get_db() # insert user into db try: # get user by username user= db.execute('SELECT * FROM user WHERE username LIKE ?',(username,)).fetchone() # check if username exists if user != None: # check if credentials are valid if user['username'] == username and user['password'] == password: # store the user ID in the session session['uid']= user['id'] session['username'] = user['username'] return redirect("/posts") except sqlite3.Error as er: print('SQLite error: %s' % (' '.join(er.args))) return redirect("/404")
def edit_user(): form = UserForm() eform = EditForm() if request.method == 'GET': # render add user blueprint return render_template('user/edit.html', formn=eform, formo=form) else: n_f_n = eform.first_name.data n_l_n = eform.last_name.data o_f_n = form.first_name.data o_l_n = form.last_name.data db = get_db() # get all users from the db try: # execute our insert SQL statement # db.execute("UPDATE user SET first_name=? ,last_name=? WHERE first_name=? ",(n_f_n,n_l_n,o_f_n)) # sql = "UPDATE user SET first_name = %s WHERE last_name = %s" # val = ("hiiii","blus") db.execute( "UPDATE user SET first_name = 'hiii' WHERE last_name = 'blus'") # write changes to DB db.commit() return redirect("/users") except sqlite3.Error as er: print('SQLite error: %s' % (' '.join(er.args))) return redirect("/404")
def add_user(): form = UserForm() if request.method == 'GET': # render add user blueprint return render_template('user/index.html', form=form) else: first_name = form.first_name.data last_name = form.last_name.data password = form.password.data # get the DB connection db = get_db() # insert user into DB try: # execute our insert SQL statement db.execute( "INSERT INTO user (first_name,last_name,password) VALUES (?,?,?);", (first_name, last_name, password)) # write changes to DB db.commit() return redirect("/users") except sqlite3.Error as er: print('SQLite error: %s' % (' '.join(er.args))) return redirect("/404")
def add_user(): #create an instance of the form signup_form = SignupForm() # add user blueprint if signup_form.validate_on_submit(): #read the username from the form username = signup_form.username.data password = signup_form.password.data # get the DB connection db = get_db() # insert user into DB try: print(f"trying to add {username}:{password}") # execute our insert SQL statement db.execute("INSERT INTO user (username, password) VALUES (?, ?);", (username, password)) # write changes to DB db.commit() return redirect("/users") except sqlite3.Error as er: print('SQLite error: %s' % (' '.join(er.args))) return redirect("/404") return render_template('user/index.html', form=signup_form)
def login(): if request.method == "GET": # render the login template return render_template('login/login.html') else: # read values from the login form username = request.form['username'] password = request.form['password'] # get the DB connection db = get_db() # insert user into db try: user = db.execute('SELECT * FROM user WHERE username LIKE ?', (username, )).fetchone() if user != None: if user['username'] == username and user[ 'password'] == password: session['uid'] = user['id'] return redirect("/posts") except sqlite3.Error as er: print('SQLite error: %s' % (' '.join(er.args))) return redirect("/404")
def add_user(): user = AddUserForm() if user.validate_on_submit(): username = user.username.data password = user.password.data first_name = user.first_name.data last_name = user.last_name.data biography = user.biography.data # get the DB connection db = get_db() # insert user into DB try: # execute our insert SQL statement db.execute( "INSERT INTO user (username, password , firstname , lastname , biography ) VALUES (?, ? , ? , ?, ?);", (username, password, first_name, last_name, biography)) # write changes to DB db.commit() return redirect("/users") except sqlite3.Error as er: print('SQLite error: %s' % (' '.join(er.args))) return redirect("/404") return render_template('user/index.html', form=user)
def add_post(): # create instance of our form add_post_form = AddPostForm() # handle form submission if add_post_form.validate_on_submit(): # read post values from the form title = add_post_form.title.data body = add_post_form.body.data # read the 'uid' from the session for the current logged in user author_id = session['uid'] # get the DB connection db = get_db() try: # insert post into database db.execute( "INSERT INTO post (author_id, title, body) VALUES (?, ?,?);", (author_id, title, body)) # commit changes to the database db.commit() return redirect('/posts') except sqlite3.Error as er: print('SQLite error: %s' % (' '.join(er.args))) return redirect("/404") # render the template return render_template("blog/add-post.html", form=add_post_form)
def register(): """Register a new user. Validates that the username is not already taken. Hashes the password for security. """ if request.method == 'POST': username = request.form['username'] password = request.form['password'] db = get_db() error = None if not username: error = 'Username is required.' elif not password: error = 'Password is required.' elif db.execute( 'SELECT id FROM user WHERE username = ?', (username,) ).fetchone() is not None: error = 'User {0} is already registered.'.format(username) if error is None: # the name is available, store it in the database and go to # the login page db.execute( 'INSERT INTO user (username, password) VALUES (?, ?)', (username, generate_password_hash(password)) ) db.commit() return redirect(url_for('auth.login')) flash(error) return render_template('auth/register.html')
def register(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] # Initializa db connection db = get_db() error = None # Validate register form input and if user exists on the database if not username: error = 'Username is required' elif not password: error = 'Password is required' elif db.execute('SELECT id FROM user WHERE username = ?', (username, )).fetchone() is not None: error = 'User {} is already registered'.format(username) if error is None: db.execute('INSERT INTO user (username, password) VALUES (?, ?)', (username, generate_password_hash(password))) db.commit() return redirect(url_for('auth.login')) flash(error) return render_template('auth/register.html')
def register(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] db = get_db() error = None # if username is not set if not username: error = 'Username is required.' # if password is not set elif not password: error = 'Password is required.' elif db.execute('SELECT id from user WHERE username = ?', (username, )).fetchone() is None: error = 'User {} is already registered.'.format(username) if error is None: db.execute('INSERT INTO user(username, password) VALUES (?,?)', (username, generate_password_hash(password))) db.commit() return redirect(url_for('auth.login')) flash(error) return render_template('auth/register.html')
def full_post(id): db = get_db() posts = db.execute("select title, body,created from post where id = ?", (id, )) if posts is None: abort(404, "Post doesn't exist.".format(id)) return render_template('article.html', posts=posts)
def delete_user(user_id): # get the DB connection db = get_db() db.execute(f"DELETE FROM user WHERE id = {user_id} ") db.commit() return redirect(url_for("user.get_users"))
def create_entry(): db = get_db() db.execute( 'insert into posts (title, content, created_at, updated_at) \ values (?, ?, date(\'now\'), date(\'now\'))', [request.form['title'], request.form['content']]) db.commit() return redirect(url_for('index'))
def load_logged_in_user(): user_id = session.get('user_id') if user_id is None: g.user = None else: g.user = get_db().execute('SELECT * FROM user WHERE id = ?', (user_id, )).fetchone()
def index(): db = get_db() posts = db.execute( 'SELECT p.id, title, body, created, author_id, username' ' FROM post p JOIN user u ON p.author_id = u.id' ' ORDER BY created DESC' ).fetchall() return render_template('blog/index.html', posts=posts)
def test_delete(client, auth, app): auth.login() response = client.post('/1/delete') assert response.headers['Location'] == 'http://localhost/' with app.app_context(): db = get_db() post = db.execute('SELECT * FROM post WHERE id = 1').fetchone() assert post is None
def test_update(client, auth, app): auth.login() assert client.get('/1/update').status_code == 200 client.post('/1/update', data={'title': 'updated', 'body': ''}) with app.app_context(): db = get_db() post = db.execute('SELECT * FROM post WHERE id = 1').fetchone() assert post['title'] == 'updated'
def delete_post(post_id): # get the DB connection db = get_db() db.execute(f"DELETE FROM post WHERE id = {post_id} ") db.commit() return redirect(url_for("blog.myposts"))
def index(): db = get_db() posts = db.execute( 'SELECT p.id, title, text, date, author_id, username' ' FROM post p JOIN user u ON p.author_id = u.id' ' ORDER BY date DESC' ).fetchall() return render_template('site/index.html', posts=posts)
def test_create(client, auth, app): auth.login() assert client.get('/create').status_code == 200 client.post('/create', data={'title': 'created', 'body': ''}) with app.app_context(): db = get_db() count = db.execute('SELECT COUNT(id) FROM post').fetchone()[0] assert count == 2
def get_users(): # get the DB connection db = get_db() # get all users from the db users = db.execute('select * from user').fetchall() # render 'list.html' blueprint with users return render_template('user/list.html', users=users)
def view_user(id): # get the DB connection db = get_db() # get user by id user = db.execute(f'''select * from user WHERE id = {id}''').fetchone() # render 'profile.html' blueprint with user return render_template('user/view-user.html', user=user)
def myposts(): # get the DB connection db = get_db() # retrieve all posts posts = db.execute(f'''select * from post WHERE author_id = {session['uid']}''').fetchall() # render 'blog' blueprint with posts return render_template('blog/myposts.html', posts = posts)
def edit_post(post_id): edit_post_form = EditPostForm() if request.method == "GET": db = get_db() current_post = db.execute(f"select * from post WHERE id = {post_id}").fetchone() edit_post_form.new_title.data = current_post['title'] edit_post_form.new_body.data = current_post['body'] if edit_post_form.validate_on_submit(): # read post values from the form new_title = edit_post_form.new_title.data new_body = edit_post_form.new_body.data # get the DB connection db = get_db() try: db.execute(f"UPDATE post SET title = '{new_title}', body = '{new_body}' WHERE id = '{post_id}' ") # commit changes to the database db.commit() return redirect(url_for("blog.myposts")) except sqlite3.Error as er: print(f"SQLite error: { (' '.join(er.args)) }") return redirect("/404") # if the user is not logged in, redirect to '/login' if "uid" not in session: return redirect('/login') # else, render the template return render_template("blog/edit_post.html", form = edit_post_form)