SQLAlchemy NameError:未定义名称“ db”

时间:2020-08-23 17:38:24

标签: python sqlite flask sqlalchemy flask-sqlalchemy

这是我使用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:映射器映射类BlogPost-> blog_post无法为映射表'blog组装任何主键列 _post'

此后,当我运行db.create_all()在sqlite中创建数据库时,出现此错误:
NameError:名称“ db”未定义

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

1 个答案:

答案 0 :(得分:0)

嘿,可能是这里的错字:

a

primary_key 处不带s(因此命名)