强制 encode/databases 使用 asyncpg 而不是 psycopg2

Force encode/databases to use asyncpg instead of psycopg2

最近,我正在尝试将 encode/databases 包与我的 postgres 数据库一起使用。我做对了。但是当我用 uvicorn 访问 运行 它时,我看到它显示没有安装 psycopg2。我不想使用 psycopg2。因此,我重述了所有 运行 databases[postgresql] 而不是仅 databases。我还安装了 asyncpg。但我仍然看到同样的错误。 我也是在虚拟环境中做的。我的代码附在下面:

import databases, sqlalchemy, asyncpg
from fastapi import FastAPI

#POSTGRES DATABASE
DATABASE_URL = "postgresql://xxxxxxxxxxx" # hidden
database = databases.Database(DATABASE_URL)
metadata = sqlalchemy.MetaData()

users = sqlalchemy.Table(
    "py_users",
    metadata,
    sqlalchemy.Column("id"        , sqlalchemy.String, primary_key=True),
    sqlalchemy.Column("username"  , sqlalchemy.String),
    sqlalchemy.Column("password"  , sqlalchemy.String),
    sqlalchemy.Column("first_name", sqlalchemy.String),
    sqlalchemy.Column("last_name" , sqlalchemy.String),
    sqlalchemy.Column("gender"    , sqlalchemy.CHAR  ),
    sqlalchemy.Column("created_at", sqlalchemy.String),
    sqlalchemy.Column("status"    , sqlalchemy.CHAR  ),
)

engine = sqlalchemy.create_engine(
    DATABASE_URL
)
metadata.create_all(engine)

app = FastAPI()

@app.get('/users')
def find_all_users():
    return "List All Users"

回溯是:

INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [110] using statreload
Process SpawnProcess-1:
Traceback (most recent call last):
  File "/usr/lib/python3.8/multiprocessing/process.py", line 315, in _bootstrap
    self.run()
  File "/usr/lib/python3.8/multiprocessing/process.py", line 108, in run
    self._target(*self._args, **self._kwargs)
  File "/home/runner/HelloCoderFastAPITuto/env/lib/python3.8/site-packages/uvicorn/subprocess.py", line 61, in subprocess_started
    target(sockets=sockets)
  File "/home/runner/HelloCoderFastAPITuto/env/lib/python3.8/site-packages/uvicorn/_impl/asyncio.py", line 47, in run
    loop.run_until_complete(self.serve(sockets=sockets))
  File "/usr/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
    return future.result()
  File "/home/runner/HelloCoderFastAPITuto/env/lib/python3.8/site-packages/uvicorn/_impl/asyncio.py", line 54, in serve
    config.load()
  File "/home/runner/HelloCoderFastAPITuto/env/lib/python3.8/site-packages/uvicorn/config.py", line 306, in load
    self.loaded_app = import_from_string(self.app)
  File "/home/runner/HelloCoderFastAPITuto/env/lib/python3.8/site-packages/uvicorn/importer.py", line 23, in import_from_string
    raise exc from None
  File "/home/runner/HelloCoderFastAPITuto/env/lib/python3.8/site-packages/uvicorn/importer.py", line 20, in import_from_string
    module = importlib.import_module(module_str)
  File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "./main.py", line 22, in <module>
    engine = sqlalchemy.create_engine(
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/sqlalchemy/engine/__init__.py", line 500, in create_engine
    return strategy.create(*args, **kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/sqlalchemy/engine/strategies.py", line 87, in create
    dbapi = dialect_cls.dbapi(**dbapi_args)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/sqlalchemy/dialects/postgresql/psycopg2.py", line 778, in dbapi
    import psycopg2
ModuleNotFoundError: No module named 'psycopg2'

根据以上错误,我认为包数据库正在尝试使用 psycopg2 而不是 asyncpg。在这种情况下,我如何强制数据库包使用 asyncpg 而不是 psycopg2。如果不是这种情况,我该如何使用 asyncpg 而不是使用 psycopg2?

提前致谢。

我的问题可能有一些错误。请忽略那些愚蠢的错误,如果您在我的问题中发现任何错误,请直接编辑问题

documentation for databases说的很清楚,我引用:

Note that if you are using any synchronous SQLAlchemy functions such as engine.create_all() or alembic migrations then you still have to install a synchronous DB driver: psycopg2 for PostgreSQL and pymysql for MySQL.

你的程序中有这段代码:

engine = sqlalchemy.create_engine(
    DATABASE_URL
)
metadata.create_all(engine)

不,在你的情况下 SQLAlchemy 试图使用 psycopg2.

看到错误:

opt/virtualenvs/python3/lib/python3.8/site-packages/sqlalchemy/dialects/postgresql/psycopg2.py

声明表时,由 SQLAlchemy 完成。但是它们之间的联系,是由 asyncpg.

完成的

文档中明确指出

Driver support is providing using one of asyncpg.

所以你不用担心这个。编码将使用 asyncpg.

您需要一个不同的 SQLAlchemy 连接字符串。

DATABASE_URL = "postgresql://xxxxxxxxxxx" # database url for databases library
DATABASE_URL_SQLALCHEMY = "postgresql+asyncpg://xxxxxxxxxxx" # database url for SQLAlchemy

另外 metadata.create_all(engine) 将不起作用,因为该函数不包含可等待的挂钩。

查看 https://docs.sqlalchemy.org/en/14/orm/extensions/asyncio.html 了解更多信息。