无法将表单中的数据提交到SQLAlchemy:sqlalchemy.orm.exc.UnmappedInstanceError?

时间:2018-05-30 02:24:14

标签: python sqlalchemy flask-sqlalchemy

我按照教程从本教程Building a CRUD application with Flask and SQLAlchemy学习了Python sqlAlchemy作为开始级别,一切都很顺利。

在此之前,我更进一步创建了另一个模型publisher  就像整个脚本如下的书模型一样:

import os

from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy

project_dir = os.path.dirname(os.path.abspath(__file__))
database_file = "sqlite:///{}".format(os.path.join(project_dir,"bookdatabase.db"))

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = database_file

db = SQLAlchemy(app)

class Book(db.Model):
    title = db.Column(db.String(80), unique=True, nullable=False, primary_key=True)

    def __init__(self, title):
        self.title = title
        super(Book,self).__init__()

    def __repr__(self):
        return "<Title: {}".format(self.title)

class Publisher(db.Model):
    name = db.Column(db.String(80), unique=True, nullable=False, primary_key=True)

    def __init__(self, name):
        self.name = name
        super(Publisher,self).__init__()

    def __repr__(self):
        return "<Name: {}".format(self.name)


@app.route("/", methods=["GET","POST"])
def home():
    if request.form:
        book = Book(title=request.form.get('title'))
        db.session.add(book)
        db.session.commit()

        pub = Publisher(name=request.form.get('pub_name'))
        db.session.add(Publisher)
        db.session.commit()

    return render_template('home.html')

if __name__=="__main__":
    app.run(debug=True)

home.html的

<html>
  <body>
    <form method="POST" action="/">
    <fieldset>
        <p>Book Title: <input type="text" name="title"></p>
    </fieldset>
    <fieldset>
        <p>Pub Name: <input type="text" name="pub_name"></p>
    </fieldset>
      <input type="submit" value="Add">
    </form>
  </body>
</html>

提交表单后,我收到错误:

  

sqlalchemy.orm.exc.UnmappedInstanceError   UnmappedInstanceError:未映射类'flask_sqlalchemy._BoundDeclarativeMeta';是一个需要实例的类( .Publisher)?

知道有一些用户遇到了类似的问题,例如thread,但我仍然无法解决这个问题。

请帮助我。谢谢!

0 个答案:

没有答案