def index(): db, c = get_db() c.execute( 'select t.id, t.description, u.username, t.completed, t.created_at ' 'from todo t JOIN user u on t.created_by = u.id where t.created_by = %s order by created_at desc', (g.user['id'], )) todos = c.fetchall() #Crear todo: if request.method == 'POST': description = request.form['description'] error = None if not description: error = 'Descripción es requerida.' if error is not None: flash(error) else: db, c = get_db() c.execute( 'insert into todo (description, completed, created_by)' ' values (%s, %s, %s)', (description, False, g.user['id'])) db.commit() return redirect(url_for('todo.index')) return render_template('todo/index.html', todos=todos)
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 add_new_task(list_id): ''' Add a new task to the todo list ''' db = get_db() todo_list = db.execute('SELECT id FROM todo_list WHERE id=?', (list_id, )).fetchone() if not todo_list: abort(404) input_data = request.get_json() if set(input_data.keys()) < set(('name', 'completed')): abort(400) name, completed = map(lambda k: input_data[k], ('name', 'completed')) if not name or not isinstance(name, str) or not isinstance( completed, bool): abort(400) elif db.execute('SELECT id FROM task WHERE name=?', (name, )).fetchone(): abort(409) task_id = uuid4().hex db.execute( 'INSERT INTO task (id, list_id, name, completed) VALUES (?,?,?,?)', (task_id, list_id, name, completed)) db.commit() input_data['id'] = task_id input_data['list_id'] = list_id return jsonify(input_data), 201
def update(id): todo = get_todo(id) if request.method == 'POST': description = request.form['description'] completed = True if request.form.get('completed') == 'on' else False error = None if not description: error = "La descripcion es requerida." if error is not None: flash(error) else: db, c = get_db() c.execute( 'update todo set description = %s, completed = %s where id = %s and created_by = %s', (description, completed, id, g.user['id'])) db.commit() return redirect(url_for('todo.index')) return render_template('todo/update.html', todo={ "description": "Mi todo", "id": 2, "completed": 0 })
def get_all_done_tasks(): db = get_db() tasks = db.execute( 'SELECT task_id,task_content,done_flag,created_at FROM todo WHERE done_flag = 1' ).fetchall() return tasks
def register(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] db, c = get_db() error = None c.execute('SELECT id FROM user WHERE username = %s', (username, )) if not username: error = 'Username es requerido' if not password: error = 'Password es requerido' elif c.fetchone() is not None: error = 'Usuario {} se encuentra registrado'.format(username) if error is None: print(password) print(generate_password_hash(password)) c.execute('INSERT INTO user (username, password) VALUES (%s, %s)', (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, c = get_db() error = None c.execute( 'select id from user where username = %s', (username, ) ) if not username: error = 'Username es requerido' if not password: error = 'Password es requerido' elif c.fetchone() is not None: error = 'Usuario {} se encuentra registrado.'.format(username) if error is None: c.execute( 'insert into user (username, password) values (%s, %s)', (username, generate_password_hash(password)) ) db.commit() return redirect(url_for('auth.login')) flash(error) return render_template('auth/register.html')
def lists(): ''' Returns all of the available lists ''' searchString = request.args.get('searchString', None) skip = _int(request.args, 'skip') limit = _int(request.args, 'limit', default=-1) db = get_db() select = 'SELECT {columns} FROM todo_list' if searchString: select += f' WHERE name LIKE "{searchString}"' select += ' LIMIT :limit OFFSET :skip' #print(f'SQL: {select}') limit_skip = {'limit': limit, 'skip': skip} todo_list_rows = db.execute(select.format(columns='id, name, description'), limit_skip) select_tasks = f'SELECT * FROM task WHERE list_id IN ({select.format(columns="id")})' #print(f'select tasks: {select_tasks}') tasks = tuple( dict(task_row, completed=bool(task_row['completed'])) for task_row in db.execute(select_tasks, limit_skip)) return jsonify( tuple( dict(todo_list_row, tasks=tuple(task for task in tasks if task['list_id'] == todo_list_row['id'])) for todo_list_row in todo_list_rows))
def register(): # La funcion que llamamos para hacer el registro de usuarios if request.method == "POST": # If para asegurarnos el caso de exito (happy path) username = request.form["username"] password = request.form["password"] # Datos que vamos a agarrar del usuario db, c = get_db() # Abrimos el acceso a la Bdd error = None c.execute( "select id from user where username = %s", (username, ) ) # Query para buscar al usuario en la bdd if not username: # Si el user no escribe nada en username error = "Username es requerido" if not password: # Si el user no escribe nada en password error = "Password es requerido" elif c.fetchone() is not None: # Si lo que encontro en la Bdd no trajo ningun resultado error = f"Usuario {username} se encuentra registrado."#.format(username) if error is None: # Si error es invalido, osea la query dio OK, registramos al usuario... c.execute( "insert into user (username, password) values (%s, %s)", (username, generate_password_hash(password)) ) # Ejecuta el script para añadir el usuario a la tabla y le agrega la contraseña encriptada db.commit() # Compromete la tabla para asentar la query anterior return redirect(url_for("auth.login")) # Ruta donde vamos a redireccionar al usuario, una vez dio exitoso el register, necesitamos la ruta y funcion login() flash(error, "error") # Si error no es None, lo va a representar return render_template("auth/register.html") # Para realizar si el usuario hace la peticion al metodo GET, a prueba de errores
def index(): db, c = get_db() c.execute( 'select t.id, t.description, u.username, t.completed, t.created_at from todo t JOIN user u on t.created_by = u.id where t.created_by = %s order by created_at desc', (g.user['id'], )) todos = c.fetchall() return render_template('todo/index.html', todos=todos)
def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] db, c = get_db() error = None c.execute( 'select * from user where username = %s', (username, ) ) user = c.fetchone() if user is None: error = 'Usuario o contraseña invalida' elif not check_password_hash(user['password'], password): error = 'Usuario o contraseña incorrecta' if error is None: session.clear() session['user_id'] = user['id'] return redirect(url_for('todo.index')) flash(error) return render_template('auth/login.html')
def update(id): todo = get_todo(id) if request.method == 'POST': description = request.form['description'] completed = True if request.form.get('completed') == 'on' else False error = None if not description: error = "Description is required" if error is not None: flash(error) else: db, cursor = get_db() cursor.execute( 'update todo set description = %s, completed=%s' ' where id = %s' ' and created_by = %s', (description, completed, id, g.user['id'])) db.commit() return redirect(url_for('todo.index')) return render_template('todo/update.html', todo=todo)
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 register(): # validamos en el servidor si el metodo que estamos recibiendo es post if request.method == 'POST': # sacamos de nuestro formulario el nombre de usuario y la contrasenia username = request.form['username'] password = request.form['password'] # validamos estos datos contra la db db, c = get_db() error = None c.execute( 'select id from user where username = %s', (username,) ) if not username: error = 'Username es requerido!' if not password: error = 'Password es requerido!' elif c.fetchone() is not None: error = 'Usuario {} se encuentra registrado.'.format(username) if error is None: c.execute( 'insert into user (username, password) values (%s, %s)', (username, generate_password_hash(password)) ) db.commit() return redirect(url_for('auth.login')) Flash(error) return render_template('auth/register.html')
def delete(id): db, c = get_db() c.execute( 'delete from todo where id= %s and created_by =%s',(id,g.user['id']) ) db.commit() return redirect(url_for('todo.index'))
def load_loggin_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, c = get_db() c.execute( 'SELECT t.id, t.description, u.username, t.completed, t.created_at from todo t JOIN user u on t.created_by = u.id ORDER BY created_at desc' ) todos = c.fetchall() return render_template('auth/index.html', todos=todos)
def delete(id): db, c = get_db() c.execute( 'DELETE FROM todo WHERE id = %s and created_by = %s', (id, g.user['id']) ) db.commit() return redirect(url_for('todo.index'))
def index(): db, c = get_db() c.execute( 'SELECT t.id,t.description,u.username,t.completed,t.created_at FROM todo AS t JOIN user AS u ON t.created_by=u.id ORDER BY created_at DESC' ) todos = c.fetchall() return render_template('todo/index.html', todos=todos)
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 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 load_logger_in_user(): user_id = session.get('user_id') if user_id is None: g.user = None else: db, c = get_db() c.execute('select * from user where id = %s', (user_id, )) g.user = c.fetchone()
def get_todo(id): db, c = get_db() c.execute( "select t.id, t.description, t.completed, t.created_by, t.created_at, u.username from todo t JOIN user u on t.created_by=u.id where t.id = %s", (id, )) todo = c.fetchone() if todo is None: abort(404, "El todo de id {0} no existe".format(id)) return todo
def load_logged_in_user(): user_id = session.get('user_id') if user_id is None: g.user = None else: db, c = get_db() c.execute('SELECT * FROM user WHERE id = %s', (user_id, )) g.user = c.fetchone()
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 index(): db, c = get_db() c.execute( "select t.id, t.description, u.username, t.completed, t.created_at from todo t JOIN user u " "on t.created_by = u.id where t.created_by = %s order by created_at desc", (g.user["id"], )) todos = c.fetchall() # Obtenemos el response return render_template("todo/index.html", todos=todos) # Creamos ruta y pasamos listado
def load_logged_in_user(): # Funcion que carga el usuario a g (Variable global que contiene al usuario) user_id = session.get("user_id") if user_id is None: g.user = None else: db, c = get_db() c.execute( "select * from user where id = %s", (user_id,) ) g.user = c.fetchone() # Agregamos el usuario a g
def app(): ''' yields a Flask() object initialized with a temporary database and some test data coming from 'data.sql' ''' 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 index(): db, c = get_db() c.execute( 'SELECT t.id, t.description, u.username, t.completed, t.created_at' ' FROM todo t JOIN user u on t.created_by = u.id WHERE t.created_by = %s ORDER BY created_at DESC', (g.user['id'],) ) todos = c.fetchall() resultado = todos if todos is not None else [] return render_template('todo/index.html', todos=resultado)
def check(id, completed): print(id, completed) db, c = get_db() if completed == 1: completed = False else: completed = True c.execute( 'update todo set completed = %s where id = %s and created_by = %s', (completed, id, g.user['id'])) db.commit() return redirect(url_for('todo.index'))