Heroku:部署 Django Rest Framework + Vue

Heroku: Deploying Django Rest Framework + Vue

我有一个用 Django(只有 DRF API)和 Vue js 制作的项目。 我有这个项目结构:

root_directory/
├── project_name/
│   ├── settings.py
│   ├── ...
├── front_end/
│   ├── ... vue files generated with CLI 3 ...
└── api/
    └── ... api app files ...

我想使用 heroku 部署这个项目,我最大的问题是:我不知道如何提供静态文件(vue 应用程序文件)。

在 heroku 文档中指定我应该将 django staticfiles serving 与 whitenoise 包一起使用(除了在 S3 中托管它们)。

但另一个问题来了:vue-cli 为我提供了一个 index.html 文件,当我 运行 npm run build 时,所有内容都会被注入,所以我无法访问 {% static 'example.js' %} ] 直接在 index.html 中,因为它不是我应该使用的 index.html,它当然是 dist/ 文件夹中的那个。但是那里的一切都变得越来越小,而且太复杂了,我无法处理。我认为如果 npm run buildpublic/index.html.

中看到类似 {% %} 的内容,它会抛出错误

我不知道如何使用 heroku 部署这个项目。 在这种情况下部署它的最佳做法是什么?

提前致谢。

将此添加到 settings.py

中的中间件
'whitenoise.middleware.WhiteNoiseMiddleware',

确保在 settings.py STATIC_URL

之后添加此 STATICFILES_DIRSSTATICFILES_STORAGE
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

注意:确保安装此:pip install django-heroku

您应该能够使用 WhiteNoise 4.0 及更高版本和一些设置来处理此问题。例如:

# Enable this so that WhiteNoise will serve `index.html` files at the directory root
WHITENOISE_INDEX_FILE = True

# Set this to wherever npm puts your final files
WHITENOISE_ROOT = os.path.join(BASE_DIR, 'dist')

除了混合使用这两个应用程序之外,您还可以托管彼此分开的 Django 应用程序和 Vue 应用程序。

使用 Django 连接到数据库并通过 REST API(后端)提供数据(例如 JSON)。

使用您的 Vue 应用程序(前端)使用 来自 REST 端点的数据。

以下是一些起点(正如您提到的 Heroku):

Deploy Django:

https://devcenter.heroku.com/articles/deploying-python

Deploy Vue:

https://medium.com/netscape/deploying-a-vue-js-2-x-app-to-heroku-in-5-steps-tutorial-a69845ace489

Some nice library to consume the data from the REST API with Vue:

https://github.com/axios/axios

您检查过了吗 - Timestrap 应用程序 ( https://github.com/overshard/timestrap). They do have Heroku based demo instance: https://timestrap.herokuapp.com/

此应用程序基于 Vuejs 和 Django - 它将很好地说明如何去做。

尽情享受