question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Support sqlite database urls relative to project path.

See original GitHub issue

When developing it makes sense to have the database file in the local repository directory, to have a dev.env which is valid for all developers it needs to be relative…

I have been doing hacks in settings.py to get around it for a few years now but I would like a discussion about how to maybe integrate such a feature into django-environ.

This basically just assumes that if the the file is at the root of the system it’s instead relative but I’m looking for a way to get rid of these in every project…

for db in DATABASES:
    if DATABASES[db]['ENGINE'] == 'django.db.backends.sqlite3':
        if os.path.split(DATABASES[db]['NAME'])[0] == "/":
            DATABASES[db]['NAME'] = root(DATABASES[db]['NAME'][1:])

I am thinking that this is kind of sane because no one proably stores the database in the root of the file system but making it optional by having a sqlite_root argument to the db-url function maybe works?

root = environ.Path(__file__) - 2
...
DATABASES = {
    'default': env.db(sqlite_root=root()),
}

I think that both relative AND absolute paths should work.

One option which I think might work safely for triggering a relative path instead of absolute is to do it when host is . or some other reserved name which isn’t really a hostname. It should error out if sqlite_root was not provided to the url parse function.

DATABASE_URL=sqlite://./db.sqlite3

Please share your opinions on this…

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:4
  • Comments:7 (2 by maintainers)

github_iconTop GitHub Comments

7reactions
joke2kcommented, Jun 27, 2018

Hi @tomasf The file url syntax for dbs allows your to put you db everywhere in your filesystem. Relative or absolute too. See the tips for sqlite in Readme. If I correctly understand what do you mean, you need to have dev.env with relative path for db… so you can use sqlite:///db.sqlite for a db in the same dir of .env file and sqlite://../db.sqlite for relative one and sqlite:////home/user/db.sqlite for absolute one. Is it right for you?

0reactions
sergeyklaycommented, Sep 1, 2021

I’d like django-environ remain simple as long as possible. I’d not complicate its codebase without an urgent and obvious need. To all those who want to work with relative paths, I would recommend some kind of approach like this:

# .env file contents
DATABASE_URL=sqlite:///db.sqlite3
# settings.py file contents
import environ
import os


env = environ.Env()

# Set the project base directory
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Take environment variables from .env file
env.read_env(os.path.join(BASE_DIR, '.env'))


def get_db_config(environ_var):
    """Get Database configuration."""
    options = env.db(var=environ_var, default='sqlite:///db.sqlite3')
    if options.get('ENGINE') != 'django.db.backends.sqlite3':
        return options

    # This will allow use a relative to the project root DB path
    # for SQLite like 'sqlite:///db.sqlite3'
    if not options['NAME'] == ':memory:' and not os.path.isabs(options['NAME']):
        options.update({'NAME': os.path.join(BASE_DIR, options['NAME'])})

    return options


DATABASES = {
    'default': get_db_config('DATABASE_URL'),
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

How to use SQLite database with path relative to project ...
I would like to make my application generate the SQLite database file that it will use in a path relative to the application's...
Read more >
Data Source properties: Relative path for database URL
E.g. I want to add a SQLite datasource where the database file is located inside my project folder ("C:\dev\MyProject\data\db.sqlite"). Can I create a ......
Read more >
SQLite Home Page
SQLite is a C-language library that implements a small, fast, self-contained, high-reliability, full-featured, SQL database engine.
Read more >
Connect To The SQLite Database Using SQLite JDBC Driver
The sqlite_data_file_path is the path to the SQLite database file, which is either relative or absolute path as follows: jdbc:sqlite:sample.db.
Read more >
SQLite database connector (Reference) - Prisma
url : Specifies the connection URL for the SQLite database. The connection URL always starts with the prefix file: and then contains a...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found