Ejemplo n.º 1
0
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)
Ejemplo n.º 2
0
def test_get_close_db(app):
    """
    Within an application context, get_db should return the same connection
    each time it’s called.
    After the context, the connection should be closed.
    """
    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)
Ejemplo n.º 3
0
Archivo: blog.py Proyecto: AEliu/flask
def get_post(id, check_author=True):
    """Get a post and its author by id.

    Checks that the id exists and optionally that the current user is
    the author.

    :param id: id of post to get
    :param check_author: require the current user to be the author
    :return: the post with author information
    :raise 404: if a post with the given id doesn't exist
    :raise 403: if the current user isn't the author
    """
    post = get_db().execute(
        'SELECT p.id, title, body, created, author_id, username'
        ' FROM post p JOIN user u ON p.author_id = u.id'
        ' WHERE p.id = ?',
        (id,)
    ).fetchone()

    if post is None:
        abort(404, "Post id {0} doesn't exist.".format(id))

    if check_author and post['author_id'] != g.user['id']:
        abort(403)

    return post
Ejemplo n.º 4
0
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)
Ejemplo n.º 5
0
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")
Ejemplo n.º 6
0
def update(id):
    post = get_post(id)

    if request.method == 'POST':
        title = request.form['title']
        body = request.form['body']
        error = None

        if not title:
            error = 'Title is required.'

        if error is not None:
            flash(error)
        else:
            db = get_db()
            db.execute(
                'UPDATE post SET title = ?, body = ?'
                ' WHERE id = ?',
                (title, body, id)
            )
            db.commit()

            return redirect(url_for('blog.index'))

    return render_template('blog/update.html', post=post)
Ejemplo n.º 7
0
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()
            # goto login page
            return redirect(url_for('auth.login'))

        flash(error)

    return render_template('auth/register.html')
Ejemplo n.º 8
0
def last_id():
    c = get_db().execute(
        "SELECT max(id) from post"
    )
    if c == None:
        abort(404, "No Posts exist")
    return str(c.fetchone()[0])
Ejemplo n.º 9
0
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")
Ejemplo n.º 10
0
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')
Ejemplo n.º 11
0
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)
Ejemplo n.º 12
0
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/idex.html', posts=posts)
Ejemplo n.º 13
0
def load_logined_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()
Ejemplo n.º 14
0
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
Ejemplo n.º 15
0
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
Ejemplo n.º 16
0
Archivo: blog.py Proyecto: AEliu/flask
def index():
    """Show all the posts, most recent first."""
    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)
Ejemplo n.º 17
0
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 * FRO post WHERE id = 1').fetchone()
        assert post['title'] == 'updated'
Ejemplo n.º 18
0
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()
Ejemplo n.º 19
0
def app():
    """Create and configure a new app instance for each test."""
    # create a temporary file to isolate the database for each test
    db_fd, db_path = tempfile.mkstemp()
    # create the app with common test config
    app = create_app({
        'TESTING': True,
        'DATABASE': db_path,
    })

    # create the database and load test data
    with app.app_context():
        init_db()
        get_db().executescript(_data_sql)

    yield app

    # close and remove the temporary database
    os.close(db_fd)
    os.unlink(db_path)
Ejemplo n.º 20
0
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
Ejemplo n.º 21
0
Archivo: blog.py Proyecto: AEliu/flask
def delete(id):
    """Delete a post.

    Ensures that the post exists and that the logged in user is the
    author of the post.
    """
    get_post(id)
    db = get_db()
    db.execute('DELETE FROM post WHERE id = ?', (id,))
    db.commit()
    return redirect(url_for('blog.index'))
Ejemplo n.º 22
0
def load_logged_in_user():
    """If a user id is stored in the session, load the user object from
    the database into ``g.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()
        )
Ejemplo n.º 23
0
def get_post(id, check_author=True):
    post = get_db().execute(
        'SELECT p.id, title, body, created, author_id, username'
        ' FROM post p JOIN user u ON p.author_id = u.id'
        ' WHERE p.id = ?',
        (id,)
    ).fetchone()
    if post is None:
        abort(404, "Post id {0} doesn't exist.".format(id))
    if check_author and post['author_id'] != g.user['id']:
        abort(403)
    return post
Ejemplo n.º 24
0
def test_author_required(app, client, auth):
    # change the post author to another user
    with app.app_context():
        db = get_db()
        db.execute('UPDATE post SET author_id = 2 WHERE id = 1')
        db.commit()

    auth.login()
    # current user can't modify other user's post
    assert client.post('/1/update').status_code == 403
    assert client.post('/1/delete').status_code == 403
    # current user doesn't see edit link
    assert b'href="/1/update"' not in client.get('/').data
Ejemplo n.º 25
0
def test_author_required(app, client, auth):
    # swap blog post author out with another user
    with app.app_context():
        db = get_db()
        db.execute('UPDATE post SET author_id = 2 WHERE id = 1')
        db.commit()

    auth.login()
    # don't let one user modify another user's post
    assert client.post('/1/update').status_code == 403
    assert client.post('/1/delete').status_code == 403
    # don't display edit link for unauthorized user
    assert b'href="/1/update"' not in client.get('/').data
Ejemplo n.º 26
0
def test_delete(client, auth, app):
    """
    The delete view should redirect to the index URL and the post should no
    longer exist in the database.
    """
    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
Ejemplo n.º 27
0
def test_register(client, app):
    # test that viewing the page renders without template errors
    assert client.get("/auth/register").status_code == 200

    # test that successful registration redirects to the login page
    response = client.post("/auth/register", data={"username": "******", "password": "******"})
    assert "http://localhost/auth/login" == response.headers["Location"]

    # test that the user was inserted into the database
    with app.app_context():
        assert (
            get_db().execute("select * from user where username = '******'").fetchone()
            is not None
        )
Ejemplo n.º 28
0
def get_post(id, check_author=True):
    post = get_db().execute(
        'select p.id, title, body, created, author_id, username'
        ' from post p join user u on p.author_id = u.id'
        ' where p.id = ?', (id,)
    ).fetchone()

    if post is None:
        abort(404, "Post id {} doesn't exists.".format(id))
    
    if check_author and post['author_id'] != g.user['id']:
        abort(403)

    return post
Ejemplo n.º 29
0
def create():
    if request.method == 'POST':
        title = request.form['title']
        body = request.form['body']
        error = None
        if not title:
            error = 'Title is required.'
        if error is not None:
            flash(error)
        else:
            db = get_db()
            db.execute(
                'INSERT INTO post (title, body, author_id)'
                ' VALUES (?, ?, ?)',
                (title, body, g.user['id'])
            )
            db.commit()
            return redirect(url_for('blog.index'))
    return render_template('blog/create.html')
Ejemplo n.º 30
0
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']
            return redirect(url_for('index'))
        flash(error)
    return render_template('auth/login.html')
Ejemplo n.º 31
0
def delete(id):
    get_post(id)
    db = get_db()
    db.execute(querries.deletePost, (id, ))
    db.commit()
    return redirect(url_for('blog.index'))
Ejemplo n.º 32
0
def index():
    "Get All Metric"
    if request.method == "GET":
        try:
            db = get_db()
            results = db.execute("SELECT * from Metric").fetchall()
            data=[]
            for row in results:
                data.append([x for x in row])
    
            return json.dumps(data),200
        except Exception as identifier:
            return identifier.args ,500
        
    """Create a new product."""
    if request.method == "POST":
        try:
            data = request.get_json(force=True)
            if not data:
               return {'message': 'No input data provided'}, 400                
            title=data['Title']                     
            description=data['Description']             
            db = get_db()
            posts = db.execute(
             "INSERT INTO Metric (Title, Description) VALUES (?,?)",(title,description)
                )  
            db.commit()               
            return { "status": 'success', 'data': 'Data added successfully'}, 201      
            
        except Exception as identifier:
            return json.dumps(identifier.args),500

    if request.method == "PUT":
        try:
            
            data=request.get_json()
            if not data:
               return {'message': 'No input data provided'}, 400 
            id=data['MetricId']              
            title=data['Title']                     
            description=data['Description']             
            db = get_db()
            posts = db.execute(
             "UPDATE Metric SET title = ?, description = ? WHERE MetricId = ?", (title, description, id)
                )             
            db.commit()               
            return { "status": 'success', 'data': 'Data updated successfully'}, 202     
            
        except Exception as identifier:
            return json.dumps(identifier.args),500

    if request.method=="DELETE":
        try:
            json_data = request.get_json(force=True)
            if not json_data:
               return {'message': 'No input data provided'}, 400        
            
            db = get_db()           
            results = db.execute("DELETE FROM Metric WHERE MetricID = ?", (json_data['MetricID'],) )             
            db.commit()   
            
            return { "status": 'success', 'data': ' Data deleted successfully'}, 204       
            
        except Exception as identifier:
            print(identifier.args  )
            return json.dumps(identifier.args ),500       
Ejemplo n.º 33
0
def renderEvents():
    db = get_db()
    events = db.execute('select * from Events order by EventDate').fetchall()
    return render_template('events/events.html', events=events)
Ejemplo n.º 34
0
def renderMyEvents():
    db = get_db()
    events = db.execute(
        'select * from Events join UsersRegistered on Events.ID = UsersRegistered.EventID and UsersRegistered.UserID = (?) order by EventDate',
        (g.user['id'], )).fetchall()
    return render_template('events/myevents.html', events=events)
Ejemplo n.º 35
0
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)
Ejemplo n.º 36
0
def delete(id):
    get_post(id)
    db = get_db()
    db.execute('delete from post where id = ?', (id, ))
    db.commit()
    return redirect(url_for('blog.index'))
Ejemplo n.º 37
0
 def viewUsers():
     with get_db() as conn:
         rows = viewUsersHelper(conn)
     return render_template("table.html", name="Users", rows=rows)
Ejemplo n.º 38
0
def user_page(id):
    db = get_db()
    info = db.execute('SELECT * FROM user' ' WHERE id = ?', (id, )).fetchone()
    return render_template('auth/user_page.html', id=id, info=info)
Ejemplo n.º 39
0
def log_user_in(username):
    db = get_db()
    user = db.execute('SELECT * FROM user WHERE username = ?',
                      (username, )).fetchone()

    return user
Ejemplo n.º 40
0
def account(ID):
    accountPosts = get_db().execute(
        'SELECT * FROM pages JOIN posts ON pages.prog_id=posts.id JOIN users ON users.id=posts.author_id WHERE author_id = ?',
        (g.user['id'], )).fetchall()

    return render_template('Profile/profile.html', posts=accountPosts)
Ejemplo n.º 41
0
def delete(id):
    get_post(id)
    db = get_db()
    db.execute('DELETE FROM category WHERE id = ?', (id,))
    db.commit()
    return 'Delete ok'
Ejemplo n.º 42
0
def index():
    """Show all the posts, most recent first."""
    db = get_db()
    posts = post_list(db)
    return render_template("blog/index.html", posts=posts)
Ejemplo n.º 43
0
def upvote(id):
    post = get_post(id, check_author=False)
    get_db().execute('UPDATE post SET votes = ? WHERE id = ?',
                     ((post['votes'] + 1), id))
    get_db().commit()
    return redirect(url_for('blog.look', id=id))
Ejemplo n.º 44
0
def submit(id):
    challenge = get_post(id)

    if request.method == 'POST':
        sourcecode = request.form['body']
        username = request.form['username']
        error = None

        if not sourcecode:
            error = 'Sourcecode is required.'

        if error is not None:
            flash(error)
        else:
            filepath = "./flaskr/files/"
            filename = str(id) + "_" + username
            srcf = open(filepath + "src/" + filename + ".c", 'w')
            srcf.write(sourcecode)
            srcf.close()

            subprocess.call(filepath + "compile.sh " + filename + " " +
                            str(id),
                            shell=True)
            resf = open(filepath + "results/result_" + filename + ".txt", 'r')
            result = resf.readline().strip()
            if (result == "correct"):
                print(str(id) + " has been solved by " + g.user['username'])
                db = get_db()
                alreadySolved = db.execute(
                    'SELECT s.id'
                    ' FROM solved s'
                    ' WHERE s.chall_id = ? AND s.solver_id = ?',
                    (id, g.user['id'])).fetchone()
                # print (alreadySolved)
                if (alreadySolved is None):
                    # First solved!
                    flash("정답입니다!")
                    db.execute(
                        'INSERT INTO solved (solver_id, chall_id)'
                        ' VALUES (?, ?)', (
                            g.user['id'],
                            id,
                        ))
                    chall = db.execute(
                        'SELECT score'
                        ' FROM challenge c'
                        ' WHERE c.id = ?', (id, )).fetchone()
                    newScore = chall['score'] + g.user['score']

                    db.execute('UPDATE user SET score = ?'
                               ' WHERE id = ?', (newScore, g.user['id']))
                    print("Gained " + str(chall['score']) + " points. (" +
                          str(newScore) + " points now)")
                    db.commit()
                else:
                    # Already Solved!
                    # do nothing...?
                    flash("이미 푼 문제입니다.")
                    print("Already solved")
            else:
                flash("틀렸습니다. 다시 시도 해 보세요.", 'fail')
            resf.close()
            return redirect(url_for('blog.index'))

    return render_template('blog/submit.html', challenge=challenge)
Ejemplo n.º 45
0
def index():
    db = get_db()
    posts = db.execute(querries.joinUserInfo).fetchall()
    return render_template('blog/index.html', posts=posts)
Ejemplo n.º 46
0
def index():
    db = get_db()
    challenges = db.execute('SELECT c.id, title, body, score'
                            ' FROM challenge c'
                            ' ORDER BY id ASC').fetchall()
    return render_template('blog/index.html', challenges=challenges)
Ejemplo n.º 47
0
def gallery():
    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/gallery.html", posts=posts)
Ejemplo n.º 48
0
def create(poster_name=None):
    if poster_name is not None:
        poster_name = poster_name.replace("/", "")

    if request.method == 'POST':
        poster_name = request.form.get("poster-name")
        email = request.form.get("email")

        error = None

        if error is not None:
            flash(error)
        else:
            db = get_db()

            if not db_utils.check_if_value_in_table("users", {"email": email}):
                db.execute(db_utils.insert_query_str('users', ['email']),
                           (email, ))

            if not db_utils.check_if_value_in_table("posters",
                                                    {"name": poster_name}):
                db.execute(
                    db_utils.insert_query_str('posters',
                                              ['name', 'qr_id', 'qr_value']),
                    (poster_name, 'qr122', ''))

            user_id = db_utils.get_table_id("users", {"email": email})
            poster_id = db_utils.get_table_id("posters", {"name": poster_name})
            if not db_utils.check_if_value_in_table("users_posters", {
                    "users_id": user_id,
                    "posters_id": poster_id
            }):
                db.execute(
                    db_utils.insert_query_str("users_posters",
                                              ['users_id', 'posters_id']),
                    [user_id, poster_id])
            else:
                flash('%s and %s entry exist. Please update values now' %
                      (poster_name, email))
                return redirect(
                    url_for('survey.update',
                            poster_name=poster_name,
                            email=email))

            users_posters_id = db_utils.get_table_id("users_posters", {
                "users_id": user_id,
                "posters_id": poster_id
            })

            if not db_utils.check_if_value_in_table(
                    "surveys", {"users_posters_id": users_posters_id}):
                db.execute(
                    db_utils.insert_query_str("surveys",
                                              ['comment', 'users_posters_id']),
                    ["", users_posters_id])

            survey_id = db_utils.get_table_id(
                "surveys", {"users_posters_id": users_posters_id})

            question_answer_dict = map_question_answer(request.form.items())
            db_utils.run_insert_answers_query(question_answer_dict.items(),
                                              survey_id)

            db.commit()
            return redirect(url_for('survey.index'))

    db = get_db()
    questions = db.execute('SELECT id, question'
                           ' FROM questions'
                           ' ORDER BY id').fetchall()
    return render_template('survey/create.html',
                           poster_name=poster_name,
                           questions=questions)
Ejemplo n.º 49
0
def test_get_close_db(app):
    # The db object should not change within a request
    with app.app_context():
        db = get_db()
        assert db is get_db()
Ejemplo n.º 50
0
def received():
    error = None
    db = get_db()
    # Get transactions that have request_type = 30, 31, 40, 41
    if request.method == 'POST':
        print('Request form: ', request.form)
        key = list(request.form)[0]
        value = request.form[key]
        tokens = key.split('_')
        print('Key: ', key)
        print('Value: ', value)
        print('Tokens:', tokens)
        transaction_method = tokens[0]
        transaction_type = int(tokens[1])
        transaction_friend_id = int(tokens[2])
        transaction_amount = int(tokens[3])
        print('Transaction variables: ', transaction_method, transaction_type,
              transaction_friend_id, transaction_amount)

        # Need to check if the user accepted or rejected the request
        if value == 'Reject':
            print('User clicked on reject')
            # If the user rejected the request:

            ## get only the first instance of the transaction type
            first_match = select_first_matched_transaction(
                db, g.user['id'], transaction_friend_id, transaction_type,
                transaction_amount)
            print('Current transaction: ', first_match)
            print(first_match['id'], first_match['user_id'],
                  first_match['friend_id'], first_match['request_type'],
                  first_match['amount'])

            ## remove the transaction from the current user's database
            delete_transaction(db, first_match['id'])

            # remove only the first instance of the transaction from the other user's database
            if transaction_type == 30:
                remove_transaction_type = 20
            elif transaction_type == 40:
                remove_transaction_type = 10

            ## get only the first instance of the transaction
            return_match = select_first_matched_transaction(
                db, transaction_friend_id, g.user['id'],
                remove_transaction_type, transaction_amount)
            ## remove the transaction from the current user's database
            delete_transaction(db, return_match['id'])

            ## Add the transaction for the current user to completed rejected transaction depending
            ## on whether it was a send/receive request to the database
            #    AND
            # Add the transaction for the other user to complete rejected depending on whether
            # it was a receive/send request to the database

            if first_match['request_type'] == 30:
                insert_transaction(db, g.user['id'], transaction_friend_id, 71,
                                   first_match['amount'])
                insert_transaction(db, transaction_friend_id, g.user['id'], 80,
                                   first_match['amount'])
            elif first_match['request_type'] == 40:
                insert_transaction(db, g.user['id'], transaction_friend_id, 81,
                                   first_match['amount'])
                insert_transaction(db, transaction_friend_id, g.user['id'], 70,
                                   first_match['amount'])

            error = 'Transaction request has been rejected!'
            flash(error)

        # else if the user accepted the request:
        elif value == 'Accept':
            print('User clicked on accept')
            ## Get the name of the person sending the request
            friend_username = get_current_user_username(
                db, transaction_friend_id)
            print('Friend username: '******'Credit/Debit: {{friend_username}} exists' for the current user
            if transaction_type == 30:
                category_user = '******' + friend_username + ')'
                kind_user = '******'

                category_friend = 'CREDIT (' + get_current_user_username(
                    db, g.user['id']) + ')'
                kind_friend = 'credit'

            elif transaction_type == 40:
                category_user = '******' + friend_username + ')'
                kind_user = '******'

                category_friend = 'DEBIT (' + get_current_user_username(
                    db, g.user['id']) + ')'
                kind_friend = 'debit'

            ## Checks and adds categories
            check_category_exists_and_create(db, category_user, g.user['id'],
                                             transaction_amount, kind_user)
            check_category_exists_and_create(db, category_friend,
                                             transaction_friend_id,
                                             transaction_amount, kind_friend)

            # Remove the transaction from the current user as well as friend and push it as a completed
            # transaction to both the current user and the friend

            ## get only the first instance of the transaction type for the current user
            first_match = select_first_matched_transaction(
                db, g.user['id'], transaction_friend_id, transaction_type,
                transaction_amount)
            print('Current transaction: ', first_match)
            print(first_match['id'], first_match['user_id'],
                  first_match['friend_id'], first_match['request_type'],
                  first_match['amount'])

            ## remove the transaction from the current user's database
            delete_transaction(db, first_match['id'])

            # remove only the first instance of the transaction from the other user's database
            if transaction_type == 30:
                remove_transaction_type = 20
            elif transaction_type == 40:
                remove_transaction_type = 10

            ## get only the first instance of the transaction for the friend
            return_match = select_first_matched_transaction(
                db, transaction_friend_id, g.user['id'],
                remove_transaction_type, transaction_amount)
            ## remove the transaction from the current user's database
            delete_transaction(db, return_match['id'])

            ## Add the transaction for the current user to completed rejected transaction depending
            ## on whether it was a send/receive request to the database
            #    AND
            # Add the transaction for the other user to complete rejected depending on whether
            # it was a receive/send request to the database

            if first_match['request_type'] == 30:
                insert_transaction(db, g.user['id'], transaction_friend_id, 51,
                                   first_match['amount'])
                insert_transaction(db, transaction_friend_id, g.user['id'], 60,
                                   first_match['amount'])
            elif first_match['request_type'] == 40:
                insert_transaction(db, g.user['id'], transaction_friend_id, 61,
                                   first_match['amount'])
                insert_transaction(db, transaction_friend_id, g.user['id'], 50,
                                   first_match['amount'])

            error = 'Transaction request has been accepted!'
            flash(error)

        return redirect(url_for('user.received'))

    else:
        received_transactions = db.execute(
            'SELECT t.user_id, t.friend_id, t.request_type, t.amount, u.username'
            ' FROM transactionrequest t JOIN user u'
            ' ON t.friend_id = u.id'
            ' WHERE t.user_id = ?'
            ' AND (t.request_type = ? OR t.request_type = ?)',
            (g.user['id'], 30, 40)).fetchall()

        print('Received transactions: ', received_transactions)
        current_username = get_current_user_username(db, g.user['id'])
        print('Current user username: '******'user/received.html',
                               type='received',
                               received_transactions=received_transactions,
                               current_username=current_username)
Ejemplo n.º 51
0
def delete(id):
    post = get_post(id)
    db = get_db()
    db.execute("DELETE FROM post WHERE id = ?", (id, ))
    db.commit()
    return redirect(url_for("blog.index"))
Ejemplo n.º 52
0
def delete(id):
    get_three(id)
    db = get_db()
    db.execute('DELETE FROM three WHERE id = ?', (id, ))
    db.commit()
    return redirect(url_for('three.index'))
Ejemplo n.º 53
0
def delete(id):
    get_post(id)
    db = get_db()
    db.execute("DELETE FROM groupe WHERE id = ?", (id,))
    db.commit()
    return redirect(url_for("groupe.index"))
Ejemplo n.º 54
0
def delete_comment(id):
    comment = get_comment(id)
    db = get_db()
    db.execute('DELETE FROM comments WHERE id = ?', (id,))
    db.commit()
    return redirect(url_for('blog.get_single_post', id=comment['post_id']))
Ejemplo n.º 55
0
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)
Ejemplo n.º 56
0
def ranking():
    db = get_db()
    users = db.execute('SELECT u.id, username, score'
                       ' FROM user u'
                       ' ORDER BY score DESC').fetchall()
    return render_template('blog/ranking.html', users=users)
Ejemplo n.º 57
0
def delete(post_id):
    get_post(post_id)
    db = get_db()
    db.execute('DELETE FROM post WHERE id = ?', (post_id, ))
    db.commit()
    return redirect(url_for('blog.index'))
def update(id):
    location = get_location(id)  #gets the location information
    #checks if we are updating a location or just viewing the update html page, if true then start updating the location
    if request.method == 'POST':
        # getting the user input from the update.html page
        name = request.form['name']
        error = None

        #Checks if the name is empty and if true, flashes the error message and redirects to update.html page
        if not name:
            error = 'name is required.'
            flash(error)

        else:
            #checks if the user attached a picture for the updated location, if true it calls the save_image method to save the image
            if request.files['file'].filename != '':
                file = request.files['file']
                filename = save_image(file)

                if filename == "":
                    filename = "location_default.jpg"

                if filename is None:
                    filename = "location_default.jpg"
            #if the user didnt attach a new picture the location will have the old image
            else:
                filename = location['image']

            exists = check_location_exists(name)
            #check if another location with the same name is already exists in the database, and if true, it flashes an error message
            if exists is not None and exists[0] != location['name']:
                flash(
                    "*Error: Similar location with the same name Has been already added"
                )
            else:
                db = get_db()  #create a connection with the database
                #updating the location in the productMovement table in database
                db.execute(
                    'UPDATE productMovement SET from_location = ?'
                    ' WHERE from_location = ?', (name, location['name']))
                db.commit()

                #updating the location in the productMovement table in database
                db.execute(
                    'UPDATE productMovement SET to_location = ?'
                    ' WHERE to_location = ?', (name, location['name']))
                db.commit()
                #updating the location in the productLocation table in database
                db.execute(
                    'UPDATE productLocation SET name = ?'
                    ' WHERE name = ?', (name, location['name']))
                db.commit()

                #updating the location in the location table in database
                db.execute(
                    'UPDATE location SET name = ?, image = ?'
                    ' WHERE location_id = ?', (name, filename, id))
                db.commit()

                #redirects the user to the home page of the product view
                return redirect(url_for('location.index'))
    #redirects the user to the product update.html page
    return render_template('location/update_location.html', location=location)
Ejemplo n.º 59
0
def test_login_required(client, path, app):
    with app.app_context():
        get_db().executescript(_data_sql)
    response = client.post(path)
    assert response.headers['Location'] == 'http://localhost/auth/login'
Ejemplo n.º 60
0
 def delete_user(self, userID):
     cursor = get_db().cursor()
     cursor.execute("UPDATE user SET activeFlag = 'N' WHERE user_id=%s",
                    (userID, ))
     row = cursor.fetchone()
     return