Django settings.py 中設置訪問 MySQL 數據庫【一種是直接在 settings.py 文件中直接寫數據庫信息,另一種是讀文件獲取數據庫信息】


settings.py 

1. 修改時區: 
   默認為:TIME_ZONE = 'America/Chicago' 
   修改為:TIME_ZONE = 'Asia/Shanghai' 

2. 默認的url: 
   ROOT_URLCONF = 'mysite.urls' 

3. 模板位置: 
   TEMPLATE_DIRS = (.....) 
  

Java代碼   收藏代碼
  1. import os.path  
  2. TEMPLATE_DIRS = (  
  3.     #'/home/tony/djcode/mysite/templates',  
  4.     os.path.join(os.path.dirname(__file__),'templates').replace('\\','/'),  
  5. )  



4. 數據庫配置:(MySQL) 
  

Java代碼   收藏代碼
  1. DATABASES = {  
  2.    'default': {  
  3.        'ENGINE': 'mysql',                 
  4.        'NAME': 'projectforge',                       
  5.        'USER': 'root',                           
  6.        'PASSWORD': 'root',                          
  7.        'HOST': 'localhost',                      
  8.        'PORT': '5432'  
  9.     }  
  10. }        

 

 

============================================================================================

文章來源:http://club.topsage.com/thread-2261820-1-1.html

Django訪問數據庫的設置是在settings.py中寫入數據庫的engine、用戶名和密碼,默認的寫法是:

DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 
DATABASE_NAME = 'xxx' # Or path to database file if using sqlite3. 
DATABASE_USER = 'root' # Not used with sqlite3. 
DATABASE_PASSWORD = 'xxx' # Not used with sqlite3. 
DATABASE_HOST = 'localhost' # Set to empty string for localhost. Not used with sqlite3. 
DATABASE_PORT = '3306' # Set to empty string for default. Not used with sqlite3.

數據庫的關鍵信息都寫在settings.py中,這樣做是非常不安全的。現在可以在settings.py里面使用DATABASE項代替以上的配置項,username和password可以寫在配置文件中。下面是把username和password放到MySQL數據庫的配置文件中,由 DATABASE項讀取的示例:

  1. DATABASES = {
  2.     'default': {
  3.         'ENGINE': 'django.db.backends.mysql',
  4.         'OPTIONS': {
  5.             'read_default_file': '/etc/mysql/my.cnf',
  6.         },
  7.     }
  8. }
  1. # my.cnf
  2. [client]
  3. database = xxx
  4. user = xxx
  5. password = xxxxxx
  6. default-character-set = utf8

也可以在DATABASES中加入NAME來指定數據庫名,client中去除database選項,HOST和PORT這些也都可以寫在my.cnf文件中。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM