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.value)
def update(id): podcast = get_podcast(id) if request.method == 'POST': podcast_name = request.form['podcast_name'] podcast_id = request.form['podcast_id'] token = request.form['token'] error = None if not podcast_name: error = "A Name is required" elif not podcast_id: error = "An ID is required" elif not podcast_id.isnumeric(): error = "Invalid ID" elif not token: error = "A token is required" elif not Manager(podcast_id, token).ok(): error = "No Buzzsprout Account with given ID and Token" if error is not None: flash(error) else: db = get_db() db.execute( 'UPDATE podcast SET podcast_name = ?, podcast_id = ?, token = ?' ' WHERE id = ?', (podcast_name, podcast_id, token, id)) db.commit() return redirect(url_for('manager.manager')) return render_template('manager/update.html', podcast=podcast)
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 create(): if request.method == 'POST': podcast_name = request.form['podcast_name'] podcast_id = request.form['podcast_id'] token = request.form['token'] error = None if not podcast_name: error = "A Name is required" elif not podcast_id: error = "An ID is required" elif not podcast_id.isnumeric(): error = "Invalid ID" elif not token: error = "A token is required" elif not Manager(podcast_id, token).ok(): error = "No Buzzsprout Account with given ID and Token" if error is not None: flash(error) else: db = get_db() db.execute( 'INSERT INTO podcast (podcast_id, token, podcast_name, user_id)' ' VALUES (?, ?, ?, ?)', (podcast_id, token, podcast_name, g.user['id'])) db.commit() return redirect(url_for('manager.manager')) return render_template('manager/create.html')
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 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() assert db.execute( 'SELECT * FROM podcast WHERE id = 1').fetchone() is None
def update_manager(i_manager): """ Update session to include cache info for BSM_Manager. Avoids making too many API calls to buzzsprout """ db = get_db() blob = pickle.dumps(i_manager) db.execute( 'UPDATE podcast' ' SET manager_blob = ?' ' WHERE podcast_id = ?', (blob, i_manager.id)) db.commit()
def get_podcast(id): podcast = get_db().execute( 'SELECT p.id, podcast_name, podcast_id, token, user_id' ' FROM podcast p JOIN user u ON p.user_id = u.id' ' WHERE p.id = ?', (id, )).fetchone() if podcast is None: abort(404, f"Podcast with ID {id} doesn't exist") if podcast['user_id'] != g.user['id']: abort(403) return podcast
def test_register(client, app): assert client.get('/auth/register').status_code == 200 response = client.post('/auth/register', data={ 'username': '******', 'password': '******' }) assert 'http://localhost/auth/login' == response.headers['Location'] with app.app_context(): assert get_db().execute( "select * from user where username = '******'", ).fetchone() is not None
def get_manager(id, token): """ Get a manager from id and token, as well as the bsm manager cache if it is saved in the database """ try: c = get_db().execute( 'SELECT manager_blob FROM podcast p' ' WHERE p.podcast_id = ?', (id, )).fetchone() m = pickle.loads(c['manager_blob']) return m except Exception as inst: print(type(inst), " - ", inst) return Manager(id, token)
def test_create(client, auth, app): auth.login() assert client.get('/create').status_code == 200 client.post('/create', data={ 'podcast_name': 'New Podcast', 'podcast_id': POD_TEST_ID_2, 'token': POD_TEST_TOKEN }) with app.app_context(): db = get_db() count = db.execute('SELECT COUNT(id) FROM podcast').fetchone()[0] assert count == 2
def test_update(client, app, auth): auth.login() response = client.post('/1/update', data={ 'podcast_name': "UPDATED", 'podcast_id': POD_TEST_ID_2, 'token': POD_TEST_TOKEN }) assert response.headers['Location'] == 'http://localhost/' with app.app_context(): db = get_db() index = db.execute('SELECT podcast_name, podcast_id, token' ' FROM podcast WHERE id = 1').fetchone() assert index['podcast_name'] == "UPDATED" assert str(index['podcast_id']) == POD_TEST_ID_2 assert index['token'] == POD_TEST_TOKEN
def login(): 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: session.clear() session['user_id'] = user['id'] session['podcasts'] = {} return redirect(url_for('manager')) flash(error) return render_template('auth/login.html')
def register(): 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 {} 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 manager(): db = get_db() podcasts = db.execute('SELECT * FROM podcast p' ' WHERE p.user_id = ?', (g.user['id'], )).fetchall() return render_template('manager/manager.html', podcasts=podcasts)
def batch_upload(): id = g.user['id'] # ****POST**** if request.method == 'POST': # TERRIBLE way of deleteing files after upload. # Doing a remove at the end of the function throws an exception. # Maybe changeing the scope of the file.save() and os.remove()?? # ********************* # uploads_to_rem = glob.glob(f"{upload_folder}/*") # for f in uploads_to_rem: # os.remove(f) # First find all podcast IDs in the request.form upload_folder = current_app.config['UPLOAD_FOLDER'] form_pods = [] for i in request.form: try: p = i.split('_')[0] if p not in form_pods: form_pods.append(p) except: pass # Get podcast, create manager for id_value in form_pods: p_title = request.form[f"{id_value}_title"] if f"{id_value}_post" not in request.form.keys(): continue pod = get_podcast(id_value) if pod['user_id'] != g.user['id']: abort(403) manager = get_manager(pod['podcast_id'], pod['token']) # Get File try: u_file = request.files[F"{id_value}_file"] if u_file and not u_file.filename.lower().endswith('.mp3'): flash("Filetype must be .mp3") return redirect(url_for('manager.batch_upload')) filename = f"{id}-{id_value}-{int(time())}.mp3" u_file.save(os.path.join(upload_folder, filename)) except Exception as e: print('Batch Upload Error - ', type(e)) # Upload Episode file_url = f"https://{current_app.config['HOST_NAME']}/media/{filename}" print("File URL - ", file_url) e_title = p_title if e_title == '': e_title = 'Untitled Episode' e = Episode( **{ 'title': e_title, 'description': request.form[f"{id_value}_description"], 'audio_url': file_url }) bsmr = manager.post_episode(episode=e) print(bsmr) # Make Public if checked if f"{id_value}_public" in request.form.keys(): manager.set_episode_public(bsmr.id) flash("Podcasts Uploaded!") return redirect(url_for('manager.manager')) # ****GET***** db = get_db() podcasts = db.execute('SELECT * FROM podcast p' ' WHERE p.user_id = ?', (g.user['id'], )).fetchall() return render_template('manager/batch_upload.html', podcasts=podcasts)
def delete(id): get_podcast(id) db = get_db() db.execute('DELETE FROM podcast WHERE id = ?', (id, )) db.commit() return redirect(url_for('manager.manager'))