部屬Django 到 Heroku


Create Heroku Application

Register Your Heroku


in your dashbroad create new app


and give your app

  1. app name(can not use Big alphabet)
  2. region

Install Heroku CLI

Install PostgreSQL

Why we should install PostgreSQL
why we cannot use sqlite3

1
heroku ps:scale web=1

Because Heroku not supported sqlite

add-ons


Create python virtual env

1
2
3
4
5
pip install virtualenv
D:
virtualenv linebot
cd linebot
Scripts\activate

install pip module
1
2
3
4
5
6
pip install django
pip install dj-database-url //heroku處理DB
pip insyall dj-static //heroku處理靜態檔案
pip install gunicorn //heroku伺服器輔助模組
pip install psycopg2
pip install requests

show virtualenv module
1
pip list

create requirements.txt

create it in mysite folder

1
2
cd mysite
pip freeze >requirements.txt

create Procfile

create a “Procfile” in project folder and type the followings command in “Procfile”

1
web: gunicorn --pythonpath mysite mysite.wsgi

web is meaning to open webapp
gunicorn –pythonpath mysite mysite.wsgi will according mysite folder urls.py setting to setup default page


Create runtime.txt

this file is tell heroku which version of python we use(! that version must heroku supported)

1
python-3.9.7

Create prod_settings.py
1
2
3
4
5
from .settings import *#import my setting
STATIC_ROOT = 'staticfiles' #setup static file directory
ALLOWED_HOSTS=["*"]#allow all host
DEBUG=False#close debug mode
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')#setting HTTPS connect function

Create .gitignore

create it in mysite folder

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
*.pyc
__pycache__
staticfiles
````

----

##### edit wsgi.py

```python=
import os
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
application = get_wsgi_application()


end up virtualenv mode

and login heroku

1
heroku login

Git


Initailize project
1
2
git init
heroku git:remote -a <herokuapp_name>

set upo heroku use mysite folder prod_settings.py as website setting
1
heroku config:set DJANGO_SETTINGS_MODULE=mysite.prod_settings

add project to repository
1
2
3
git add .
git commit -am "init commit
git push heroku master