【问题标题】:SQLAlchemy NameError: Name 'db' is not definedSQLAlchemy NameError:未定义名称'db'
【发布时间】:2020-12-12 10:47:51
【问题描述】:

这是我使用 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' 未定义

谁能帮我解决这个问题?

【问题讨论】:

    标签: python sqlite flask sqlalchemy flask-sqlalchemy


    【解决方案1】:

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

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

    primary_key 处没有 s(因此得名)

    【讨论】:

      猜你喜欢
      • 2017-12-26
      • 2022-01-27
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      • 2018-01-24
      • 1970-01-01
      • 2021-04-15
      相关资源
      最近更新 更多