我正在尝试运行我的create_db.py文件来创建posts.db数据库,但它不会在我的项目目录中创建。当我运行博客的主文件并尝试登录时,我收到以下错误。
我查了一下这个错误并看到其他人也已经得到它并在Stackoverflow上询问它,但它们似乎都没有帮助我。我读过这可能是因为我的blog.py文件中的某些内容在创建数据库之前运行 main 。但是,我认为它与配置有关。主要是数据库的PATH可能与app.config['SQLAlCHEMY_DATABASE_URI'] = 'sqlite:///'
行混淆。
有什么想法吗?
这是错误
sqlalchemy.exc.OperationalError
OperationalError:(OperationalError)没有这样的表:posts u'SELECT posts.id AS posts_id,posts.title AS posts_title,posts.post AS posts_post \ nFROM posts'()
OperationalError:(OperationalError)没有这样的表:posts u'SELECT posts.id AS posts_id,posts.title AS posts_title,posts.post AS posts_post \ nFROM posts'()
这是我的代码。这里有三个文件:blog.py,models.py,create_db.py
blog.py #blog app的控制器
from flask import Flask, render_template, request, session,\
flash, redirect, url_for, g
from flask.ext.sqlalchemy import SQLAlchemy
import sqlite3
from functools import wraps
# create the application object
app = Flask(__name__)
# configuration
app.secret_key = 'x13xa8xf5}[xfexd4Zxb8+x07=7xc9xe1Bxcfxbdt.ox87oxc9'
app.config['SQLAlCHEMY_DATABASE_URI'] = 'sqlite:///'
# create sqlalchemy object
db = SQLAlchemy(app)
from models import *
# login required decorator
def login_required(test):
@wraps(test)
def wrap(*args, **kwargs):
if 'logged_in' in session:
return test(*args, **kwargs)
else:
flash('You need to login first.')
return redirect(url_for('login'))
return wrap
@app.route('/', methods = ['GET','POST'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] != 'admin' or request.form['password'] != 'admin':
error = 'Invalid Credentils. Please try again.'
else:
session['logged_in'] = True
return redirect(url_for('main'))
return render_template('login.html', error=error)
@app.route('/main')
@login_required
def main():
posts = db.session.query(BlogPost).all()
return render_template('main.html', posts=posts)
@app.route('/add', methods=['POST'])
@login_required
def add():
title = request.form['title']
post = request.form['post']
if not title or not post:
flash("All fields are required. Please try again.")
return redirect(url_for('main'))
else:
db.session.add(title)
db.session.add(post)
db.session.commit()
db.session.close()
flash('New entry was successfully posted!')
return redirect(url_for('main'))
@app.route('/logout')
def logout():
session.pop('logged_in', None)
flash('You were logged out')
return redirect(url_for('login'))
def connect_db():
return sqlite.connect('posts.db')
if __name__ == '__main__':
app.run(debug = True)
models.py:
from blog import db
class BlogPost(db.Model):
__tablename__ = "posts"
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String, nullable=False)
post = db.Column(db.String, nullable=False)
def __init__(self, title, post):
self.title = title
self.post = post
def __repr__(self):
return '<title {}'.format(self.title)
create_db.py
from blog import db
from models import BlogPost
# create the database and the db tables
db.create_all()
# insert
db.session.add(BlogPost("Good","I\'m good."))
db.session.add(BlogPost("Well","I\'m well."))
db.session.add(BlogPost("Post","I\'m a post."))
# commit the changes
db.session.commit()
答案 0 :(得分:1)
SQLAlCHEMY_DATABASE_URI
中有一个拼写错误,应为SQLALCHEMY_DATABASE_URI
,第二个l
。
在from blog import db
中运行blog.py
时,sqlite:///
中的某些语句会被执行,包括app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///posts.db'
的语句,这是设置路径的位置。修改此行
create_db.py
然后在运行ImportError: cannot import name [name]
之后应该在app的根目录中创建一个数据库。代码中似乎没有其他位置设置数据库路径。
看起来您可能会遇到一些循环导入问题(将抛出db = SQLAlchemy..
)。有些解决方案是将app {init}之类的东西放到一个单独的文件中,或者在文件的末尾导入。