python - 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
有人可以帮我解决这个问题吗?
解决方案
嘿,这里可能只是一个错字:
id=db.Column(db.Integer,primary_key=True)
在primary_key处没有 s (因此得名)
推荐阅读
- css - 具有可滚动 div 的 CSS,占用 100% 可用高度,但不向正文添加滚动条
- visual-studio-code - 更漂亮的 vscode “r 不是函数”
- python - Python3:os.system 不重定向标准输出
- php - 为什么页面显示一个 php 脚本?
- ruby-on-rails - Rails 路线通配符
- html - 为什么 chrome 和 firefox 会忽略这个多重选择器 CSS 规则?
- bash - Bash:从 docker-compose.yml 获取容器名称列表
- android - Android Room defaultValue="CURRENT_TIMESTAMP" 不起作用
- android - 从 Cloud Firestore 和 Flutter 获取数据
- python - 有没有办法从类中的用户输入追加?