gpt4 book ai didi

python - Flask SQL 没有这样的表

转载 作者:行者123 更新时间:2023-12-01 06:40:10 25 4
gpt4 key购买 nike

我以前尝试过这个方法并且有效,现在我又这样做了,但还是不行。我使用虚拟环境。

db 文件与 initmodels 位于同一目录中。导入 db 后,我还在 python shell 中执行了 db.create_all() 。当我执行 Students.query.all() 时发生错误。我现在真的很困惑。我将我的代码与我现有的项目进行了比较,结果是相同的。我不明白为什么它不起作用。

Traceback (most recent call last):
File "C:\Users\Martin\Desktop\regtry\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1246, in _execute_context
cursor, statement, parameters, context
File "C:\Users\Martin\Desktop\regtry\venv\lib\site-packages\sqlalchemy\engine\default.py", line 581, in do_execute
cursor.execute(statement, parameters)
sqlite3.OperationalError: no such table: students

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Martin\Desktop\regtry\venv\lib\site-packages\sqlalchemy\orm\query.py", line 3211, in all
return list(self)
File "C:\Users\Martin\Desktop\regtry\venv\lib\site-packages\sqlalchemy\orm\query.py", line 3367, in __iter__
return self._execute_and_instances(context)
File "C:\Users\Martin\Desktop\regtry\venv\lib\site-packages\sqlalchemy\orm\query.py", line 3392, in _execute_and_instances
result = conn.execute(querycontext.statement, self._params)
File "C:\Users\Martin\Desktop\regtry\venv\lib\site-packages\sqlalchemy\engine\base.py", line 982, in execute
return meth(self, multiparams, params)
File "C:\Users\Martin\Desktop\regtry\venv\lib\site-packages\sqlalchemy\sql\elements.py", line 287, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "C:\Users\Martin\Desktop\regtry\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1101, in _execute_clauseelement
distilled_params,
File "C:\Users\Martin\Desktop\regtry\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1250, in _execute_context
e, statement, parameters, cursor, context
File "C:\Users\Martin\Desktop\regtry\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1476, in _handle_dbapi_exception
util.raise_from_cause(sqlalchemy_exception, exc_info)
File "C:\Users\Martin\Desktop\regtry\venv\lib\site-packages\sqlalchemy\util\compat.py", line 398, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "C:\Users\Martin\Desktop\regtry\venv\lib\site-packages\sqlalchemy\util\compat.py", line 152, in reraise
raise value.with_traceback(tb)
File "C:\Users\Martin\Desktop\regtry\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1246, in _execute_context
cursor, statement, parameters, context
File "C:\Users\Martin\Desktop\regtry\venv\lib\site-packages\sqlalchemy\engine\default.py", line 581, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: students
[SQL: SELECT students.id AS students_id, students.last_name AS students_last_name, students.college AS students_college, students.email AS students_email
FROM students]
(Background on this error at: http://sqlalche.me/e/e3q8)

_ _ 初始化 _ _.py:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

main = Flask(__name__)
main.config['SECRET_KEY'] = '3bce79429ad6b79670e4e800fb4a57b9'
main.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'

db = SQLAlchemy(main)

from reg import routes

模型.py:

from reg import db

class Students(db.Model):
id = db.Column(db.Integer, primary_key=True)
last_name = db.Column(db.String(60), nullable=False)
college = db.Column(db.String(60), nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)

def __repr__(self):
return f"Student('{self.last_name}','{self.college}','{self.email}')"

最佳答案

这可能与您调用 db.create_all() 的位置有关。您必须在定义所有模型后调用它。以下是一个模块中的一个工作示例:

import flask
from flask_sqlalchemy import SQLAlchemy

app = flask.Flask(__name__)
app.config['SECRET_KEY'] = '3bce79429ad6b79670e4e800fb4a57b9'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'

db = SQLAlchemy(app)


class Students(db.Model):
id = db.Column(db.Integer, primary_key=True)
last_name = db.Column(db.String(60), nullable=False)
college = db.Column(db.String(60), nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)

def __repr__(self):
return f"Student('{self.last_name}','{self.college}','{self.email}')"

db.create_all()


@app.route("/students", methods=["GET"])
def all_students():
students = Students.query.all()
resp = []
for student in students:
resp.append(dict(
id=student.id,
last_name=student.last_name,
college=student.college,
email=student.email
))
return flask.jsonify(resp), 200


@app.route("/students/<_id>", methods=["GET"])
def student_by_id(_id):
student = Students.query.get(_id)
if student:
resp = dict(
id=student.id,
last_name=student.last_name,
college=student.college,
email=student.email
)
return flask.jsonify(resp), 200
else:
return "", 404


@app.route("/students", methods=["POST"])
def add_student():
req = flask.request.get_json()
student = Students(**req)
db.session.add(student)
db.session.commit()
resp = flask.make_response()
resp.headers["Location"] = flask.url_for("student_by_id", _id=student.id)
return resp, 201

在您的示例中,我没有看到对 db.create_all() 的调用,但我怀疑它位于错误的位置。使用您的示例,我相信如果您将调用从您所在的位置移动到 __init__.py 的末尾,它会起作用:

__init__.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

main = Flask(__name__)
main.config['SECRET_KEY'] = '3bce79429ad6b79670e4e800fb4a57b9'
main.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'

db = SQLAlchemy(main)

from reg import routes
db.create_all()

关于python - Flask SQL 没有这样的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59491313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com