防止 Django SQLite 数据库在推送到 Heroku 时被覆盖

2021-12-08 00:00:00 django heroku git sqlite

我有一个 Django 应用程序,它在它的模型中存储了大量数据.问题是,每当我部署到 Heroku 时,即使它是一个小的更改,具有正确数据的远程数据库都会被虚拟数据的本地数据库覆盖.

I've got a Django application that is storing a large amount of data in it's models. The problem is, whenever I deploy to Heroku even if it's a small change, the remote database with the correct data gets overwritten with the local database of dummy data.

场景:

我有一个远程的 db 文件 my_db.现在,当推送到 heroku 时,我只是 git add > git commit 仅包含更改的文件而不是整个项目.我的问题在于,它以某种方式仍然用本地数据覆盖远程数据库.

I have a db file my_db which is remote. Now, when pushing to heroku, I just git add > git commit only the files with the changes rather than the whole project. My problem lies in the fact that, it somehow still overwrites remote database with local data.

有没有办法防止这种情况发生?

Is there a way to prevent this?

推荐答案

Heroku 不提供一个持久的文件系统.

我使用过的大多数 Heroku 应用程序都将 PostgreSQL 用于他们的数据库,所以这不是问题.但是 SQLite 只是放在某个目录中的一个文件,因此每次部署数据库时都会丢失.

Most Heroku applications that I have worked on use PostgreSQL for their database, so this isn't a problem. But SQLite is just a file sitting in a directory somewhere, so every time you deploy your database will be lost.

最简单的解决方案可能是从 SQLite 迁移到 PostgreSQL,这在 Heroku(和 Django)上得到了很好的支持,并且每次部署时都不会丢失数据.

The easiest solution is probably to migrate from SQLite to PostgreSQL, which is very well supported on Heroku (and in Django) and will not lose data every time you deploy.

如果您坚定地致力于 SQLite,您可能还有其他一些选择:

If you're firmly committed to SQLite you may have some other options:

  • 在每次推送之前备份您的数据库文件,并在您推送之后恢复它.
  • 将您的生产数据库添加到您的 Git 存储库,以便它会与您的应用程序一起部署(请注意,我不建议这样做).
  • 许多用户使用 Amazon S3 存储其他类型的资产.您或许可以对您的数据库使用类似的过程,但我怀疑这样做会带来一些非常重大的安全风险.
  • Back your database file up before each push and restore it after your push.
  • Add your production database to your Git repository, so it will be deployed along with your application (note that I don't recommend this).
  • Many users use Amazon S3 to store other types of assets. You may be able to use a similar procedure with your database, though I suspect there will be some very significant security risks doing so.

相关文章