简体   繁体   English

执行插入查询但未将数据添加到表中

[英]Insert query is executed but data is not added into table

I am trying to insert data in a table on heroku postgres db from a Flask App.我正在尝试从 Flask 应用程序在 heroku postgres db 上的表中插入数据。 The query is being executed but there is no result displayed on the table.查询正在执行,但表上没有显示结果。

Please let me know if I had made any mistakes.如果我犯了任何错误,请告诉我。 Thanks!谢谢!

route file(bookpage[post]):路线文件(书页[帖子]):

import os

from flask import Blueprint, render_template, request, flash, redirect, url_for
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from flask_login import login_required, current_user

main = Blueprint('main', __name__)

engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))


@main.route("/")
def index():
    return render_template('index.html')


@main.route("/home")
@login_required
def home():
    book = ""
    return render_template('home.html', name=current_user.name, book=book)


@main.route("/home", methods=['POST'])
@login_required
def home_post():
    isbn = '%' + request.form.get('isbn') + '%'
    title = '%' + request.form.get('title') + '%'
    author = '%' + request.form.get('author') + '%'
    if isbn is None and title is None and author is None:
        flash('Please enter atleast one info of book')
    books = []
    if isbn is not None:
        q1 = db.execute("SELECT title FROM bookinfo WHERE isbn LIKE (:isbn)", {"isbn": isbn}).fetchall()
        if len(q1) < 4999:
            books.append(q1)
    if title is not None:
        q2 = db.execute("SELECT title FROM bookinfo WHERE title LIKE (:title)", {"title": title}).fetchall()
        if len(q2) < 4999:
            books.append(q2)
    if author is not None:
        q3 = db.execute("SELECT title FROM bookinfo WHERE author LIKE (:author)", {"author": author}).fetchall()
        if len(q3) < 4999:
            books.append(q3)
    if not books:
        flash('No book found with given info')
    else:
        return render_template('home.html', book=books)
    return redirect(url_for('main.home', name=current_user.name))


@main.route("/bookpage")
def bookpage():
    data = []
    review_data = []
    return render_template('bookpage.html', data=data, review=review_data)


@main.route("/bookpage", methods=['POST'])
def bookpage_post():
    title = request.form.get('title')
    data = []
    review_data = []
    rating = request.form.get('rating')
    reviews = request.form.get('review')
    bk_title = request.form.get('bk_title')
    if request.method == 'POST':
        if request.form.get('submit') == 'Get Details':
            if title is not None:
                q1 = db.execute("SELECT isbn, title, author, year FROM bookinfo WHERE title = (:title)",
                                {"title": title}).fetchall()
                q2 = db.execute("SELECT rating, review FROM reviews WHERE title = (:title)",
                                {"title": title}).fetchall()
                data.append(q1)
                if q2 is not None:
                    review_data.append(q2)
                    if len(review_data[0]) == 0:
                        review_data.clear()
                        review_data.append([('No Rating', 'No Reviews')])
        if request.form.get('submit') == 'Submit Review':
            if rating is not None and reviews is not None:
                db.execute("INSERT INTO reviews (title, rating, review) VALUES (:title, :rating, :review)",
                           {"title": bk_title, "rating": rating, "review": reviews})
                flash('Review Submitted')
            else:
                flash('Error')
    return render_template('bookpage.html', data=data, review=review_data, rating=rating, reviews=reviews)

html page: html页面:

{% extends 'index.html' %}

{% block content %}
<div class="box">
    {% with messages = get_flashed_messages() %}
    {% if messages %}
    <div class="alert alert-primary" role="alert">
        {{ messages[0] }}
    </div>
    {% endif %}
    {% endwith %}
    <form action="/bookpage" method="POST">
        <input type="text" id="result" name="title" readonly>
        <input type="submit" value="Get Details" name="submit"><br><br>
        <br><br>
        {% for d in data[0] %}
        <h2>ISBN: </h2>
        <h3>{{ d[0] }}</h3><br>
        <h2>Title: </h2>
        <h3>{{ d[1] }}</h3><br>
        <h2>Author: </h2>
        <h3>{{ d[2] }}</h3><br>
        <h2>Year: </h2>
        <h3>{{ d[3] }}</h3><br>
        <h2>Rating: </h2>
        <h3>{{ review[0][0][0] }}</h3><br>
        <h2>Reviews: </h2>
        <h3>{{ review[0][0][1] }}</h3><br>
        {% endfor %}
    </form>
    <form action="/bookpage" method="POST" id="review">
        <h5 align="left">Review:</h5>
        <input type="range" min="1" max="5" value="3" name="rating" class="slider" id="myRange"><br>
        <h6 align="left">&nbsp;1&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;2&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;3&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;4&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;5</h6>
        <input id="result1" name="bk_title">
        <textarea rows="4" cols="50" name="review" form="review"></textarea>
        <input type="submit" value="Submit Review" name="submit">
    </form>
</div>
{% endblock %}

The output after submitting the query: html page Error: table view output提交后查询: html页面报错:表视图

You should be creating only one method for one route .您应该只one method for one route You are creating 2 methods for route /bookpage .您正在2 methods for route /bookpage

The standard to follow:遵循的标准:

If you want route /bookpage for different kind of requests ie GET, POST, etc , you define one single method for that route and handle with if-else conditions as to what logic to perform when it is GET request-type and what logic to perform when it is POST request-type如果您想为不同类型的请求(即GET, POST, etc )路由/bookpage ,您可以为该路由定义一个方法并使用if-else conditions处理当它是GET request-type时要执行什么逻辑以及要执行什么逻辑当它是POST request-type时执行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM