示例#1
0
def update(id):
    """Update a post if the current user is the author."""
    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:
            conn = get_conn_db()
            cur = conn.cursor()
            cur.execute("UPDATE post SET title = %s, body = %s WHERE id = %s",
                        (title, body, id))
            cur.close()
            conn.commit()
            conn.close()

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

    return render_template("blog/update.html", post=post)
示例#2
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"]
        conn = get_conn_db()
        cur = conn.cursor()

        error = None
        user = None
        cur.execute("SELECT * FROM author WHERE username = %s", (username,))
        auth_cur = cur.fetchone()
        if auth_cur is not None:
            user = tp_to_dict(auth_cur, cur)
        cur.close()
        conn.commit()
        conn.close()

        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")
示例#3
0
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
    """
    conn = get_conn_db()
    cur = conn.cursor()
    cur.execute(
        "SELECT post.id, title, body, created, author_id, username"
        " FROM post  JOIN author ON post.author_id = author.id"
        " WHERE post.id = %s",
        (id, ),
    )
    cur_post = cur.fetchone()
    post = tp_to_dict(cur_post, cur)
    cur.close()
    conn.commit()
    conn.close()

    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
示例#4
0
def create():
    """Create a new post for the current user."""
    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:
            conn = get_conn_db()
            cur = conn.cursor()
            cur.execute(
                "INSERT INTO post (title, body, author_id)"
                " VALUES (%s, %s, %s)",
                (title, body, g.user["id"]),
            )
            cur.close()
            conn.commit()
            conn.close()

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

    return render_template("blog/create.html")
示例#5
0
def index():
    global log_new_game, search_number, time_game, lst_new_game
    log_new_game = []
    lst_new_game = []
    search_number = []
    time_game = []
    search_number = pick_number()

    conn = get_conn_db()
    cur = conn.cursor()

    cur.execute('''
            SELECT game.id, author_id, username, game_begin, 
            conceived_number, count_step, time_game, win_los
            FROM game JOIN author ON game.author_id = author.id
            ORDER BY game_begin DESC;
            ''')

    game_cur = cur.fetchall()
    lst_bd = list_tp_to_list_dict(game_cur, cur)

    cur.close()
    conn.commit()
    conn.close()

    return render_template("blog/index.html", games=lst_bd)
示例#6
0
def delete(id):
    """Delete a post.

    Ensures that the post exists and that the logged in user is the
    author of the post.
    """
    conn = get_conn_db()
    cur = conn.cursor()
    cur.execute("DELETE FROM post WHERE id = %s", (id, ))
    cur.close()
    conn.commit()
    conn.close()
    return redirect(url_for("blog.index"))
示例#7
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:
        conn = get_conn_db()
        cur = conn.cursor()

        cur.execute("SELECT * FROM author WHERE id = %s", (user_id,))
        auth_cur = cur.fetchone()
        g.user = tp_to_dict(auth_cur, cur)
        cur.close()
        conn.commit()
        conn.close()
示例#8
0
def index():
    conn = get_conn_db()
    cur = conn.cursor()

    cur.execute('''
            SELECT post.id, title, body, created, author_id, username
            FROM post JOIN author ON post.author_id = author.id
            ORDER BY created DESC;
            ''')

    post_cur = cur.fetchall()
    lst_bd = list_tp_to_list_dict(post_cur, cur)

    cur.close()
    conn.commit()
    conn.close()
    return render_template("blog/index.html", posts=lst_bd)
示例#9
0
def get_game_log(id_game):

    conn = get_conn_db()
    cur = conn.cursor()
    cur.execute(
        "SELECT log.id, game_id, log_game"
        " FROM log  JOIN game ON log.game_id = game.id"
        " WHERE game_id = %s",
        (id_game, ),
    )
    cur_game = cur.fetchall()
    game_log = list_tp_to_list_dict(cur_game, cur)
    cur.close()
    conn.commit()
    conn.close()

    if game_log is None:
        abort(404, "Game id {0} doesn't exist.".format(id_game))
    return game_log
示例#10
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"]

        conn = get_conn_db()
        cur = conn.cursor()

        error = None
        cur.execute("SELECT id FROM author WHERE username = %s", (username, ))
        auth_cur = cur.fetchone()

        if not username:
            error = "Username is required."
        elif not password:
            error = "Password is required."
        elif auth_cur 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
            cur.execute(
                "INSERT INTO author (username, password) VALUES (%s, %s)",
                (username, generate_password_hash(password)),
            )
            cur.close()
            conn.commit()
            conn.close()
            message = "You registered as {0}. You may login and create, " \
                      "edit and delete your post!".format(username)
            flash(message)
            return redirect(url_for("auth.login"))

        flash(error)

    return render_template("auth/register.html")
示例#11
0
def new_game():
    global log_new_game, search_number, time_game, lst_new_game

    time_session_game = datetime.datetime.now()
    time_game.append(time_session_game)

    if request.method == "POST":
        step_game = request.form["step_game"]
        valid_input = validator_input_number(input_str=step_game)

        if valid_input[0] != '':
            flash(valid_input[0])
        else:
            if not search_number:
                error = 'Слишком долгое ожидание! Игра завершена без сохраннеия!'
                flash(error)
                return redirect(url_for("game.index"))

            last_step = valid_input[1]
            bulls_cows = check_number(user_input_str=last_step,
                                      search_number_lst=search_number)
            step_dict = {'log_game': last_step + ' ' + bulls_cows}
            log_new_game.append(step_dict)
            lst_new_game.append(last_step + ' ' + bulls_cows)
            if bulls_cows == '40':
                count_record_time = len(time_game)
                sum_time_game = time_game[count_record_time - 1] - time_game[0]
                sum_time_game_sec = sum_time_game.total_seconds()
                # Запись сесии игры ====================================
                conn = get_conn_db()
                cur = conn.cursor()
                search_number_str = ''.join(search_number)
                count_step = len(log_new_game)
                cur.execute(
                    "INSERT INTO game (author_id, conceived_number, count_step, time_game, win_los)"
                    "VALUES (%s, %s, %s, %s,%s)",
                    (g.user["id"], search_number_str, count_step,
                     sum_time_game_sec, 1))
                cur.execute("SELECT * FROM game ORDER BY id DESC LIMIT 1")
                game_id = cur.fetchone()[0]

                for i in range(len(lst_new_game)):
                    cur.execute(
                        "INSERT INTO log (game_id, log_game)"
                        " VALUES (%s, %s)",
                        (game_id, lst_new_game[i]),
                    )

                cur.close()
                conn.commit()
                conn.close()

                message_win = 'Поздравляю с победой! Количество ходов в сесии ' + str(
                    count_step)
                flash(message_win)
                return redirect(url_for("game.index"))

            return render_template("blog/new_game.html",
                                   steps=log_new_game,
                                   last_step=last_step,
                                   search_num=search_number)

    return render_template("blog/new_game.html")