Reputation: 122
I am trying to create an sqlite db on a volume within a docker container. When execution reaches c = conn.cursor()
a receive the following error:
sqlite3.ProgrammingError: Cannot operate on a closed database.
I wanted to re-use the connection process so built the following functions, which I think might be where the problem is:
def create_sqlite_conn(db):
try:
conn = sqlite3.connect(db, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
return conn
except sqlite3.Error as e:
logging.warning("WARNING: Error accessing DB: {}".format(db), e)
finally:
conn.close()
def create_db(db):
conn = create_sqlite_conn(db)
c = conn.cursor()
c.execute('''CREATE TABLE table1(id INTEGER PRIMARY KEY AUTOINCREMENT, ip_ver TEXT, date_time DATETIME)''')
conn.commit()
This is called with:
create_db('/home/web/data/new_db.sql')
This code runs outside of the docker container, which is why I wonder whether this is alpine or docker related. My docker file looks like this:
FROM alpine:3.7
RUN apk --no-cache add python3 build-base linux-headers python3-dev \
&& pip3 install virtualenv \
&& addgroup -g 500 web \
&& adduser -D -u 1000 -G web web
WORKDIR /home/web
ENV PYTHONPATH /home/web/myapp
USER web
RUN mkdir -p /home/web/env /home/web/myapp /home/web/data/
COPY myapp/__init__.py /home/web/myapp/
COPY myapp/myapp.py /home/web/myapp/
COPY setup.py /home/web/myapp/
COPY requirements.txt /home/web/myapp/
COPY README.txt /home/web/myapp/
RUN /usr/bin/virtualenv -p python3 /home/web/env \
&& source /home/web/env/bin/activate \
&& python -m pip install ./myapp/ \
&& python -m pip install -r ./myapp/requirements.txt
VOLUME ["./data"]
CMD ["/home/web/env/bin/myapp"]
Starting the docker container I have tried with and without the '--privileged' flag and still get the same error.
Thanks,
Upvotes: 1
Views: 2278
Reputation: 13175
This is unrelated to docker
. From the docs:
A finally clause is always executed before leaving the try statement, whether an exception has occurred or not.
This is easily testable, b
will exist regardless:
try:
a = int(2)
except:
pass
finally:
b = 3
print(b)
So it doesn't make sense to close()
a connection in a finally
block. I don't see any reason to close the connection at all in this function because it only tried to do one thing: open a connection. Either the connection is successful or it fails and therefore does not need closing (indeed, calling close()
in the exception handler is likely to throw an error because the name conn
will not exist).
Upvotes: 2