使用Heroku遇到的问题

使用Mezzanine做了一个博客,部署到heroku时遇到了一些问题,此篇以作记录。

1. 无法完成github项目的部署-H12错误

项目根目录必须包含app.jsonrequirements.txtProcfile,可选Procfile.windowsruntime.txt

app.json
{ "name": "name", "description": "description", "image": "heroku/python", "repository": "https://github.com/YOURNAME/repository", "keywords": ["python", "django", "Mezzanine" ], "addons": [ "heroku-postgresql" ], "env": { "SECRET_KEY": { "description": "The secret key for the Django application.", "generator": "secret" } }, "environments": { "test": { "scripts": { "test-setup": "python manage.py collectstatic --noinput", "test": "python manage.py test" } } } }
requirements.txt
Mezzanine==4.3.1
Procfile
web: python manage.py runserver 0.0.0.0:8000
Procfile.windows
web: python manage.py runserver 0.0.0.0:8000
requirements.txt
python-3.7.5

2. Application error

Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch

也许是数据库的问题?

heroku create [APP_NAME] # 创建APP

git push heroku master # 创建分支

heroku run python manage.py migrate # 远端生成数据库
heroku ps:scale web=1
heroku open

requirement.txt文件中加入gunicorn,使用这个库开启Web服务,修改项目目录下的Procfile文件(mblog是我的项目里应用的名称,在该应用下应该存在wsgi.py文件)

Procfile
web: gunicorn mblog.wsgi --log-file -

3. no such table: django_site

尝试生成远端数据库

heroku run python manage.py migrate
heroku run python manage.py makemigrations
heroku run python manage.py createdb --noinput
heroku run python manage.py syncdb #(在Django 1.9中已删除)

setting.py
# heroku 只支持postgrespool数据库 来自:https://www.jianshu.com/p/610c670eabed import dj_database_url DATABASES['default'] = dj_database_url.config() ··· import django_heroku django_heroku.settings(locals())

4. 如果看到发现变量不对可以使用如下命令打印变量

heroku run echo \$JDBC_DATABASE_URL

5. 删除默认数据库,添加MySQL数据库

heroku addons:destroy heroku-postgresql
heroku addons:create cleardb:ignite
heroku config # 过程中可以使用 config 命令查看数据库 URL 是否修改成功

6. postgresql 无法连接

错误类似于

could not connect to postgres error: no pg_hba.conf entry for host "1.198.47.212", user "ijhjecdqztyvfo", database "d66rrjcr414em1", SSL off

解决方法取自于Connecting in Node.js

const { Client } = require('pg');

const client = new Client({
  connectionString: process.env.DATABASE_URL,
  ssl: {
    rejectUnauthorized: false
  }
});

client.connect();

client.query('SELECT table_schema,table_name FROM information_schema.tables;', (err, res) => {
  if (err) throw err;
  for (let row of res.rows) {
    console.log(JSON.stringify(row));
  }
  client.end();
});

如果指定PGSSLMODE配置变量,则可以省略ssl 配置对象: heroku config:set PGSSLMODE=no-verify

X. 可能会用到的命令

python manage.py createsuperuser # 创建超级管理员,帐号登录 admin 后台

# 将本地分支 master 提交到 heroku 
git add -u
git commit -m  "commit"
git push heroku master

heroku run python manage.py collectstatic --noinput