首页 > 解决方案 > SQLAlchemy NameError:未定义名称'db'

问题描述

这是我使用 Flask 和 SQLAlchemy 制作博客网站的代码。

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

app=Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///posts.db'
db=SQLAlchemy(app)

class BlogPost(db.Model):
    id=db.Column(db.Integer,primary_keys=True)
    title=db.Column(db.String(100),nullable=False)
    content=db.Column(db.Text,nullable=False)
    author=db.Column(db.String(30),nullable=False,default='N/A')
    date_posted=db.Column(db.DateTime,nullable=False,default=datetime.utcnow)

    def __repr__(self):
        return "BlogPost "+ str(self.id)

all_posts=[
             {
                'title':'Post 1',
                'content':"This is the content of post 1 ",
                'author':"Anantya"
             },
             {
                'title':'Post 2',
                'content':"This is the content of post 2 "
             }
          ]

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

@app.route('/posts')
def posts():
    return render_template("posts.html",posts=all_posts)

@app.route("/home/<int:id>/images/<string:name>")
def home(name,id):
    return "My name is "+name +" and my id is=" +str(id)

@app.route("/onlyget",methods=['GET'])
def get_req():
    return "you can only get this webpage"

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

当我打开一个 python 环境并尝试运行from app import db它时会抛出一个错误: sqlalchemy.exc.ArgumentError: Mapper mapped class BlogPost->blog_post could notassemble any primary key columns for mapped table 'blog _post'

在此之后,当我运行db.create_all()在 sqlite 中创建数据库时,出现此错误:
NameError: name 'db' is not defined

有人可以帮我解决这个问题吗?

标签: pythonsqliteflasksqlalchemyflask-sqlalchemy

解决方案


嘿,这里可能只是一个错字:

id=db.Column(db.Integer,primary_key=True)

在primary_key处没有 s (因此得名)


推荐阅读