我可以使Django数据库路径(对于sqlite3)“跨平台”吗? [英] Can I make the Django database path (for sqlite3) "cross-platform"?

查看:154
本文介绍了我可以使Django数据库路径(对于sqlite3)“跨平台”吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Django和Python(以及一般的编程)。为了简单起见,我正在使用sqlite3作为我的数据库,而我正在通过Django等教程。



我是一个多平台用户(Mac OS ,Windows,Linux)取决于我当时的位置。所以,我做的是把我的编程项目放在我的Dropbox中,以便我可以在任何地方使用相同的代码。



问题是在设置中。 py文件为特定项目,我指定数据库路径如下所示:

  DATABASES = {
'default': {
'ENGINE':'django.db.backends.sqlite3',#添加'postgresql_psycopg2','mysql','sqlite3'或'oracle'。
'NAME':'C:/ Users / David / Dropbox / programming / mysite / database',#或使用sqlite3的数据库文件路径。

...但是当我使用MacOS或Linux时,显然是C:/ chokes。我想知道有人是否有一个简单的补救措施的建议。当然,我可以做的一种方法是通过MySQL或其他东西在我的网络服务器上远程设置我的数据库,但是我认为可能会有一个简单的方法,例如使用'if'语句。

解决方案

使用 settings.py 中的相对路径是很常见的,被许多人认为是最佳实践。

  from os.path import dirname,join 

PROJECT_DIR = dirname( __file__)

DATABASES = {
#...
'NAME':join(PROJECT_DIR,'your_db_name.db'),
#...
}


I'm in the process of learning Django and Python (as well as programming in general). For the sake of simplicity, I am using sqlite3 as my database while I'm going through tutorials for Django and such.

I am a multi-platform user (Mac OS, Windows, Linux) depending on where I am at the time. So, what I have done is put my programming projects in my Dropbox so that I can work on the same code from anywhere.

The problem is that, in the settings.py file for a particular project, I specify the database path like so:

DATABASES = {
    'default': {
    'ENGINE': 'django.db.backends.sqlite3',                             # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
    'NAME': 'C:/Users/David/Dropbox/programming/mysite/database',       # Or path to database file if using sqlite3.

... but when I'm using MacOS or Linux, obviously the C:/ chokes. I was wondering if someone had a suggestion of a simple remedy to this. Of course, one way I could do it would be to set up my database remotely on my webserver via MySQL or something, but I thought there might be a simple way to do it such as with an 'if' statement.

解决方案

Using relative paths in settings.py is a common enough to be considered a best practice by many. Something like this may help.

from os.path import dirname, join

PROJECT_DIR = dirname(__file__)

DATABASES = {
    # ...
    'NAME': join(PROJECT_DIR, 'your_db_name.db'),
    # ...
}

这篇关于我可以使Django数据库路径(对于sqlite3)“跨平台”吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆