我是Flask的新手,正在尝试创建一个博客。我想从我想插入帖子的位置创建一个页面。从理论上讲,页面应重定向到索引,但是每次我尝试在页面“添加”中插入内容时,都会出现错误。这是我的代码:
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////Users/admin/Desktop/Blog_Project/blog2.db'
db = SQLAlchemy(app)
class Blogpost(db.Model):
id = db.Column(db.Integer, primary_key = True)
title = db.Column(db.String(50))
subtitle = db.Column(db.String(50))
author = db.Column(db.String(20))
date_posted = db.Column(db.DateTime)
content = db.Column(db.Text)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/about')
def about():
return render_template('about.html')
@app.route('/post')
def post():
return render_template('post.html')
@app.route('/contact')
def contact():
return render_template('contact.html')
@app.route('/prova')
def prova():
return render_template('prova.html')
@app.route('/add')
def add():
return render_template('add.html')
@app.route('/addpost', methods=['POST'])
def addpost():
title = request.form['title']
subtitle = request.form['subtitle']
author = request.form["author"]
content = request.form['content']
post = Blogpost(title=title, subtitle=subtitle, author=author, content=content, date_posted = datetime.now())
db.session.add(post)
db.session.commit()
return redirect(url_for('index'))
if __name__ == "__main__":
app.run(debug = True)
这是我得到的错误:
sqlalchemy.exc.OperationalError
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: blogpost
[SQL: INSERT INTO blogpost (title, subtitle, author, date_posted, content) VALUES (?, ?, ?, ?, ?)]
[parameters: ('ds', 'ds', 'sd', '2020-09-08 12:55:25.333277', 'ds')]
(Background on this error at: http://sqlalche.me/e/13/e3q8)
据我了解,问题在于Flask无法在数据库blog2中创建表blogpost并用我在代码中插入的值填充它。我已经阅读了Internet和Stackoverflow上的一些文档,显然有些人使用db.create_all()
方法解决了相同的问题,但是我不确定应该在哪里插入它,或者是否应该以其他方式重新组织代码。你有什么建议吗?提前非常感谢您!