python 无法使用sqllight创建数据库SQLAlchemy

qyzbxkaa  于 2023-02-15  发布在  Python
关注(0)|答案(1)|浏览(144)

这是我第一次使用SQLAlchemy和sqllight。
我的代码如下所示:

#we are going to create the flask app
app = Flask(__name__)

global db
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqllite:///databse.db'
app.config['SECRET_KEY'] = 'ca8b6694c31960d1f7ee2d1ac73c669f'

db = SQLAlchemy(app)
    
app = create_app()

下一步是进入终端并输入Python。Python解释器将出现,我输入了"from main import db",因为我的文件名为main,所以我必须从main导入。
但这是实际的错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/alex/portal/main.py", line 15, in <module>
    db = SQLAlchemy(app)
  File "/home/alex/portal/venv/lib/python3.10/site-packages/flask_sqlalchemy/extension.py", line 219, in __init__
    self.init_app(app)
  File "/home/alex/portal/venv/lib/python3.10/site-packages/flask_sqlalchemy/extension.py", line 326, in init_app
    engines[key] = self._make_engine(key, options, app)
  File "/home/alex/portal/venv/lib/python3.10/site-packages/flask_sqlalchemy/extension.py", line 614, in _make_engine
    return sa.engine_from_config(options, prefix="")
  File "/home/alex/portal/venv/lib/python3.10/site-packages/sqlalchemy/engine/create.py", line 817, in engine_from_config
    return create_engine(url, **options)
  File "<string>", line 2, in create_engine
  File "/home/alex/portal/venv/lib/python3.10/site-packages/sqlalchemy/util/deprecations.py", line 277, in warned
    return fn(*args, **kwargs)  # type: ignore[no-any-return]
  File "/home/alex/portal/venv/lib/python3.10/site-packages/sqlalchemy/engine/create.py", line 556, in create_engine
    entrypoint = u._get_entrypoint()
  File "/home/alex/portal/venv/lib/python3.10/site-packages/sqlalchemy/engine/url.py", line 754, in _get_entrypoint
    cls = registry.load(name)
  File "/home/alex/portal/venv/lib/python3.10/site-packages/sqlalchemy/util/langhelpers.py", line 365, in load
    raise exc.NoSuchModuleError(
sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:sqllite

如果你有任何建议,请告诉我。
另外,我正尝试将此代码放在脚本中的"* init *. py"中,以获得更干净的代码。

bsxbgnwa

bsxbgnwa1#

您将sqlite错误拼写为sqllite

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///databse.db'

但是即使你修正了这个问题,你还是会遇到其他的问题,因为你在代码的末尾重新定义了app,这里有一个工作示例,是文档中这个示例的简化版本。

from flask import Flask, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///databse.db"
app.config["SECRET_KEY"] = "ca8b6694c31960d1f7ee2d1ac73c669f"

db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String, unique=True, nullable=False)
    email = db.Column(db.String)

    def as_dict(self):
        return {c.name: getattr(self, c.name) for c in self.__table__.columns}

with app.app_context():
    db.create_all()

@app.route("/users", methods=["GET"])
def user_list():
    res = db.session.execute(db.select(User).order_by(User.username)).scalars()
    users = res.fetchall()
    return [user.as_dict() for user in users]

@app.route("/users", methods=["POST"])
def user_create():
    user = User(**request.get_json())
    db.session.add(user)
    db.session.commit()
    return user.as_dict()

@app.route("/user/<int:id>")
def user_detail(id):
    user = db.get_or_404(User, id)
    return user.as_dict()

您可以创建用户条目:

$ curl http://localhost:5000/users -H content-type:application/json \
  -d '{"username": "alice", "email": "alice@example.com"}'
{
  "email": "alice@example.com",
  "id": 1,
  "username": "alice"
}

获取用户列表:

$ curl http://localhost:5000/users
[
  {
    "email": "alice@example.com",
    "id": 1,
    "username": "alice"
  }
]

获取单个用户的详细信息:

$ curl http://localhost:5000/user/1
{
  "email": "alice@example.com",
  "id": 1,
  "username": "alice"
}

等等。

相关问题