简体   繁体   中英

Python 3.6.3 unable to import _sqlite3 to run a SQlite db with sqlalchemy

I'm running my Fast API project with pipenv and I use Python 3.6.3 as the interpreter. For production I use a postgres db which works fine. Now I want to test my api with pytest and sqlite.

Therefore I changed the db connection setup:

engine = create_engine("sqlite:///./test.db")
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()
db = SessionLocal()

I also tried the connection string from the official docs from sqlalchemy:

engine = create_engine('sqlite://')

when I run my test , I get the following error:

   engine = create_engine("sqlite:///./test.db")
../../../../.local/share/virtualenvs/test-hhG2yARU/lib/python3.6/site-packages/sqlalchemy/util/deprecations.py:298: in warned
    return fn(*args, **kwargs)
../../../../.local/share/virtualenvs/test-hhG2yARU/lib/python3.6/site-packages/sqlalchemy/engine/create.py:560: in create_engine
    dbapi = dialect_cls.dbapi(**dbapi_args)
../../../../.local/share/virtualenvs/test-hhG2yARU/lib/python3.6/site-packages/sqlalchemy/dialects/sqlite/pysqlite.py:473: in dbapi
    from sqlite3 import dbapi2 as sqlite
../../../../.pyenv/versions/3.6.3/lib/python3.6/sqlite3/__init__.py:23: in <module>
    from sqlite3.dbapi2 import *
../../../../.pyenv/versions/3.6.3/lib/python3.6/sqlite3/dbapi2.py:27: in <module>
    from _sqlite3 import *
E   ModuleNotFoundError: No module named '_sqlite3'

I have seen in the source code that the error causing module has the following note:

 pysqlite2/dbapi2.py: the DB-API 2.0 interface
#
# Copyright (C) 2004-2005 Gerhard Häring <gh@ghaering.de>
#
# This file is part of pysqlite.

Here the error is cause by

from _sqlite3 import *

where _sqlite is not found. I had a look at the

dbapi2.py file from pysqlite3. Here sqlite is imported without the "_". So I thought since python3 the pysqlite3 file should be inbuilt in python.

Is there a way to change the pysqlite2 to 3? I've read about installing pysqlite3, but this did not change anything in my case.

I also tried to update from python 3.6.13 to 3.6.3 as 3.6 is mandatory. This also did not change the behaviour.

I was able to solve it by the information provided by @MatsLindh Here is the original comment with the solution. I have installed

sudo apt-get install libsqlite3-dev

and then reinstalled my python version with pyenv

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM