Python SQLAlchemy名称错误:名称';db';没有定义
这是我使用Flask和SQLAlchemy创建博客网站的代码Python SQLAlchemy名称错误:名称';db';没有定义,python,sqlite,flask,sqlalchemy,flask-sqlalchemy,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 Blo
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)
从烧瓶导入烧瓶,渲染\u模板
从flask_sqlalchemy导入sqlalchemy
从日期时间导入日期时间
app=烧瓶(名称)
app.config['SQLALCHEMY\u DATABASE\u URI']='sqlite:///posts.db'
db=SQLAlchemy(应用程序)
BlogPost类(db.Model):
id=db.Column(db.Integer,主键=True)
title=db.Column(db.String(100),null=False)
content=db.Column(db.Text,nullable=False)
author=db.Column(db.String(30),nullable=False,默认值='N/A')
date\u posted=db.Column(db.DateTime,nullable=False,default=DateTime.utcnow)
定义报告(自我):
返回“BlogPost”+str(self.id)
所有职位=[
{
“标题”:“帖子1”,
'内容':“这是帖子1的内容”,
“作者”:“阿南塔”
},
{
“标题”:“帖子2”,
“内容”:“这是第2篇文章的内容”
}
]
@应用程序路径(“/”)
def index():
返回渲染模板(“index.html”)
@app.route(“/posts”)
def posts():
返回render_模板(“posts.html”,posts=all_posts)
@app.route(“/home//images/”)
def home(姓名、id):
return“我的名字是”+name+,我的id是=“+str(id)
@app.route(“/onlyget”,methods=['GET']))
def get_req():
return“您只能获取此网页”
如果名称=“\uuuuu main\uuuuuuuu”:
app.run(debug=True)
当我打开python环境并尝试从app import db运行时,它会抛出一个错误:
sqlalchemy.exc.ArgumentError:映射器映射的类BlogPost->blog\u post无法为映射表“blog”组装任何主键列
_邮政’
在这之后,当我运行db.create_all()
在sqlite中创建数据库时,我得到以下错误:
NameError:未定义名称“db”
有人能帮我解决这个问题吗?嘿,这里可能有个打字错误:
id=db.Column(db.Integer,primary_key=True)
在主键处没有s(因此得名)