- Copy the project seperately
- Go to 'Getting Started on Heroku with Python'
- Create an Heroku account
- install pipenv
- Install git ( check git --version)
- Install Heroku CLI
- Login heroku
- Create a virtual enviroment
- Run manage.py not gonna run - pip freeze nothing installing
- Check which version django,requests you have and install it
- Run manage.py and then stop it
- Go to django heroku
- Create a Procfile and
- Install django-heroku
- Add stuff to settings.py file
- Install guincorn
- pip freeze > requirements.txt
- heroku create attreyaweb (to create an app on heroku)
- git status git commands (git push heroku master)
- Open up the website
- Admin panel not working. heroku run bash. Migrations
install pipenv
的原因是想通过 pipenv
创建一个虚拟环境,这个虚拟环境也可以通过 anaconda
来创建;虚拟环境的作用主要是保护你本地 python 环境,虚拟环境可以在不影响你本地所有东西的情况下创建一个隔离的环境,在这里面你可以创建任意的 Python 运行环境,也可以随时将这个虚拟环境删除
pip install gunicorn
这个虽然在你本地的环境中用不到,你本地运行服务器也没有用,但是当你上传代码到 heroku,他会使用 gunicorn 来帮你部署,所以 gunicorn 必须要出现在你的环境中,这样才能随着下一步 freeze 操作生成的 requirements.txt 一起 push 到远端 heroku 仓库pip freeze > requirements.txt
的作用主要是将你所有的 python 环境输出到 requirements.txt 这个文件里面,这个文件记录了你所有运行代码需要的 library 的列表,部署的时候会从这里面读取然后在远程给你配置部署环境,所以非常重要。
这一步还有一点非常重要:如果你的 requirements.txt 中出现了这种问题,一定要注意,将后面的内容删掉,手动换成版本号,和其他的那些写法一样,你可以用
pip list
来检查当前环境下所有 library 的版本,唯一正确的写法就是package名称==版本号
Procfile
文件,这个文件 没有后缀!没有后缀!没有后缀!(mac 容易将无后缀的文件默认是 txt 格式,一定要注意这个问题,这个文件是真正的无后缀的)Procfile
文件中写的内容是 web: gunicorn myproject.wsgi
这里的 myproject
替换成你的文件的名称,比如我这个服务器中,就应该写成web: gunicorn djangoServer.wsgi
这个文件对于 heroku
的部署非常重要,否则部署一定会失败django-heroku
,安装命令 pip install django-heroku
- 根据官网推荐的这个文件去修改你 Django 中原本的
settings.py
文件,- 我把自己的
settings.py
也贴在这里,大家可以参考,尤其注意的是ALLOWED_HOSTS = ["*"]
这句话一定不要漏:
"""
Django settings for djangoServer project.
Generated by 'django-admin startproject' using Django 3.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
import datetime
from pathlib import Path
import dj_database_url
import os
from django.test.runner import DiscoverRunner
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
"""
Heroku
"""
IS_HEROKU = "DYNO" in os.environ
SECRET_KEY = "CHANGE_ME!!!! (P.S. the SECRET_KEY environment variable will be used, if set, instead)."
if 'SECRET_KEY' in os.environ:
SECRET_KEY = os.environ["SECRET_KEY"]
# Generally avoid wildcards(*). However since Heroku router provides hostname validation it is ok
if IS_HEROKU:
ALLOWED_HOSTS = ["*",
're-echidna-django.herokuapp.com']
else:
ALLOWED_HOSTS = ['*','re-echidna-django.herokuapp.com']
# SECURITY WARNING: don't run with debug turned on in production!
if not IS_HEROKU:
DEBUG = True
# Application definition
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-pm42jjw)=bp1*8m3+vd=#kfnbe99213px8yb9*_7^%r6d$wlii'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ["*"]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'RE_app.apps.AppConfig',
'corsheaders'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware'
]
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
ROOT_URLCONF = 'djangoServer.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'RE_app', 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'djangoServer.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'ENGINE': None,
# 'ENGINE': 'djongo',
# 'NAME': BASE_DIR / 'db.sqlite3',
# 'NAME': 'RE_ECHIDNA',
# 'ENFORCE_SCHEMA': False,
# 'CLIENT': {
# 'host': 'mongodb+srv://:@/?retryWrites=true&w=majority'}
# 'host': 'mongodb+srv://ZIYUQ:@cluster0.366apt7.mongodb.net/?retryWrites=true&w=majority'}
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
"""
Heroku
"""
# Test Runner Config
class HerokuDiscoverRunner(DiscoverRunner):
"""Test Runner for Heroku CI, which provides a database for you.
This requires you to set the TEST database (done for you by settings().)"""
def setup_databases(self, **kwargs):
self.keepdb = True
return super(HerokuDiscoverRunner, self).setup_databases(**kwargs)
# Use HerokuDiscoverRunner on Heroku CI
if "CI" in os.environ:
TEST_RUNNER = "djangoServer.settings.HerokuDiscoverRunner"
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# print(os.path.join(BASE_DIR, 'RE_app', 'templates'))
- 说明一下,这里我本地其实 python 是 3.9.0 但是我大胆判断,远端的 3.9.15 应该和 3.9.0 是兼容的,而且远端只支持那么几种 python 版本,我只能选择 3.9.15 因此我这里可以告诉你,本地 3.9 的系列的 python 应该都不影响部署。
heroku login
登录到你自己的 heroku 账号,他会弹出一个界面,登录即可。(如果你使用了 ,执行这一步的时候尽量断掉,否则有可能说你 ip 地址不一致)heroku create xxxxx
任意名字,比如我 heroku create re-echidna-dataportal
他就会在 heroku 你的账号下面创建一个库。git init
heroku git:remote -a xxxx
xxx 是刚才 create 的名称git add .
将本地所有的文件提交到本地仓库git commit -am "随便说一句话"
git push heroku master
这句话一执行,远端会根据你的 requirements 准备运行环境,并通过 runtime 选择 python 版本并检查是否支持,最后通过 procfile 来部署