How to connect docker volume 'database/app.db' to SQLAlchemy?

a 夏天 提交于 2020-04-18 05:46:29

问题


I am using Python 3.8.1 Flask latest and app running fine but unable to connect the docker volume from SQLAlchemy and if the database does not exist it should create the database, but I am unable to connect my shared docker volume into my Python Flask app.

Config.py file:

import os
basedir = os.path.abspath(os.path.dirname(__file__))

DATA_PATH = "/database"

if os.path.exists(DATA_PATH) == False:
    os.mkdir(DATA_PATH)

class Config(object):

    # set a proper secret key here or is the .flaskenv file
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'
    SQLALCHEMY_DATABASE_URI = 'sqlite://database/app.db'
    SQLALCHEMY_TRACK_MODIFICATIONS = False

init.py file:

from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager

app = Flask(__name__, static_url_path='', static_folder='static')
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
login = LoginManager(app)
login.login_view = 'login'

from app import routes, models

Docker run :

docker run -p 8080:8080 -it --name abc -v localdb:/database  --rm abc:v1

Error 1:

xc.ArgumentError(
sqlalchemy.exc.ArgumentError: Invalid SQLite URL: 
sqlite://database//app/app/app.db
Valid SQLite URL forms are:
 sqlite:///:memory: (or, sqlite://)
 sqlite:///relative/path/to/file.db
 sqlite:////absolute/path/to/file.db

Error 2:

For SQLALCHEMY_DATABASE_URI = 'sqlite:///database/app.db'

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) unable to open database file
(Background on this error at: http://sqlalche.me/e/e3q8)

回答1:


This doesn't look like a Docker volume issue, it looks like you are trying to access the database using a path as the URI instead of: sqlite:////path/to/db.db

See: https://docs.sqlalchemy.org/en/13/core/engines.html#database-urls

Specifically for sqlite: https://docs.sqlalchemy.org/en/13/core/engines.html#sqlite



来源:https://stackoverflow.com/questions/61106345/how-to-connect-docker-volume-database-app-db-to-sqlalchemy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!