当我运行python udemy课程的启动文件时,我遇到了一个奇怪的错误,首先,下面是代码:
from flask import Flask, jsonify, render_template, request
from flask_sqlalchemy import SQLAlchemy
import random
app = Flask(__name__)
##Connect to Database
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///cafes.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
##Cafe TABLE Configuration
class Cafe(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(250), unique=True, nullable=False)
map_url = db.Column(db.String(500), nullable=False)
img_url = db.Column(db.String(500), nullable=False)
location = db.Column(db.String(250), nullable=False)
seats = db.Column(db.String(250), nullable=False)
has_toilet = db.Column(db.Boolean, nullable=False)
has_wifi = db.Column(db.Boolean, nullable=False)
has_sockets = db.Column(db.Boolean, nullable=False)
can_take_calls = db.Column(db.Boolean, nullable=False)
coffee_price = db.Column(db.String(250), nullable=True)
@app.route("/")
def home():
return render_template("index.html")
## HTTP GET - Read Record
@app.route("/random")
def get_random_cafe():
cafes = db.session.query(Cafe).all()
random_cafe = random.choice(cafes)
return jsonify(cafe={
#Omit the id from the response
# "id": random_cafe.id,
"name": random_cafe.name,
"map_url": random_cafe.map_url,
"img_url": random_cafe.img_url,
"location": random_cafe.location,
#Put some properties in a sub-category
"amenities": {
"seats": random_cafe.seats,
"has_toilet": random_cafe.has_toilet,
"has_wifi": random_cafe.has_wifi,
"has_sockets": random_cafe.has_sockets,
"can_take_calls": random_cafe.can_take_calls,
"coffee_price": random_cafe.coffee_price,
}
})
## HTTP POST - Create Record
## HTTP PUT/PATCH - Update Record
## HTTP DELETE - Delete Record
if __name__ == '__main__':
app.run(debug=True)
当我指向"/random"我得到这个错误:sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: cafe
但是这个表存在,它就在我的目录中充满了数据,或者我错过了什么,我真的不知道该怎么做。提前感谢!
*在进一步阅读文档后编辑
这是一个猜测,但是关于SQLite配置的部分说数据库URI路径必须是绝对路径。
#Unix/Mac (note the four leading slashes)
sqlite:////absolute/path/to/foo.db
#Windows (note 3 leading forward slashes and backslash escapes)
sqlite:///C:\absolute\path\to\foo.db
#Windows (alternative using raw string)
r'sqlite:///C:absolutepathtofoo.db'
可能需要检查您是否正在连接到您认为正在连接的数据库文件。我想知道您是否有两个,一个位于文件系统的根目录,另一个位于创建表的目录。
https://flask-sqlalchemy.palletsprojects.com/en/2.x/config/connection-uri-format