【发布时间】: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