iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 26
0
Modern Web

用 Python 玩 PDF,結合Django 變成一個網頁系統系列 第 26

[Day 26] PostgreSQL

今天來用資料庫,有很多著名的關聯式資料庫,像Mysql、Oracle、MS SQL、PostgreSQL等等,我的習慣是使用PostrgreSQL,他是一套開源的資料庫。

要先安裝postgresql

$ sudo apt-get -y install postgresql postgresql-contrib

安裝好之後,來建立user和 Database
這裡建 pdfWeatherDB, 和pdfWeather,就直接拿專案名稱來使用。

$ sudo -i -u postgres
$ createdb pdfWeatherDB

建立使用者,並輸入兩次密碼

$ createuser -P pdfWeather

設定存取權限

$ psql
$ GRANT ALL PRIVILEGES ON DATABASE "pdfWeatherDB" to "pdfWeather";

會出現GRANT 就完成了。
退出

$ \q
$ exit

django 設定
先安裝psycopg2,記得要進到專案的虛擬環境

(venv)$ pip install psycopg2

main/settings.py
打上剛剛建立的database, user, password

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'pdfWeatherDB',
        'USER': 'pdfWeather',
        'PASSWORD': 'pdfWeatherPassword',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}

做migrate ,將django 一開始的表格建立到database裡

(venv) $ python manage.py migrate

輸出

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying sessions.0001_initial... OK

這樣就完成了

參考資料:

如果有任何寫得不好的地方,請跟我說,謝謝。


上一篇
[Day 25] 前端顯示圖表(Chart.js)
下一篇
[Day 27] 訂閱
系列文
用 Python 玩 PDF,結合Django 變成一個網頁系統30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言