将 Flask / Angular 应用程序_从同一存储库_部署到 Heroku

问题描述 投票:0回答:1

我有一个用 Flask 编写的现有应用程序,部署到 Heroku,它运行得很好,但我决定将其转换为 Angular 前端,仅使用 Flask 作为 API。这在本地也很有效,但我快完成了,我想将其部署到 Heroku 从同一个存储库。该网站是一套内部工具,流量极低...认为每天最多 20-40 次点击。

这是当前的文件系统结构:

├── Procfile
├── README.md
├── backend
│   ├── app.py
│   ├── requirements.txt
│   ├── static **(will not be used by Flask)**
│   └── templates **(will not be used by Flask)**
├── frontend
│   ├── angular.json
│   ├── dist
│   │   ├── mmscripts
│   │   │   ├── 3rdpartylicenses.txt
│   │   │   └── browser
│   │   │   │   ├── favicon.ico
│   │   │   │   ├── index.html
│   │   │   │   ├── main-HX6HQ3LL.js
│   │   │   │   ├── polyfills-S3BTP7ME.js
│   │   │   │   └── styles-HCXVZOOP.css
│   ├── package-lock.json
│   ├── package.json
│   ├── src
│   │   ├── app
│   │   │   ├── env.ts
│   │   ├── assets
│   │   ├── favicon.ico
│   │   ├── index.html
│   │   ├── main.ts
│   │   └── styles.scss
│   ├── tsconfig.app.json
│   ├── tsconfig.json
│   └── tsconfig.spec.json
└── runtime.txt

目前我进入后端并运行 Flask 应用程序:

FLASK_ENV=development flask run

然后在一个单独的 shell 中,我 cd 进入前端并运行

ng serve
。我在 Flask 应用程序中安装了 Flask-Cors,以便 Angular 可以访问 API,然后在
frontend/src/app/env.ts
中我得到了这个常量:

export const API_URL = 'http://localhost:5000/api';

这是一些版本控制:

Angular 17
Flask 3
Flask-Cors 4
Heroku stack is 22

过程文件:

web: gunicorn app:app

运行时.txt

python-3.9.19

如果需要的话,我不介意重新排列文件系统。我只是使用了这个特定的设置,因为从组织的角度来看,它似乎让事情变得更容易。

angular flask heroku
1个回答
0
投票

我能够让这个工作几乎完全像我希望的那样。

对于任何关注我的人,这就是我完成它的方法。

  1. 创建
    backend
    frontend
    目录。
    1. Flask 代码进入后端目录,如上所示。
    2. Angular 代码位于前端目录中,如上所示。
  2. 在项目的根目录中,创建一个包含以下代码的
    Procfile
    1. web: gunicorn --chdir ./backend app:app
    2. 就我而言,我使用的是gunicorn,如果您使用的是其他服务器,方法可能会有所不同。
  3. frontend
    目录中,在部署到 Heroku 之前,运行以下命令:
    1. ng build --configuration production
    2. 应使用最小化的 Angular 代码创建或更新
      dist
      文件夹。

为了让 Flask 提供正确的文件,我还必须对我的

app.py
文件进行如下更改:

from flask import (
    Flask,
    send_from_directory,
)

app = Flask(__name__, static_folder='../frontend/dist/<my Angular app name>/browser/', static_url_path='')

@app.errorhandler(404)
@app.route('/',defaults={"e": ""})
def index(e):
    return send_from_directory(app.static_folder, 'index.html')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=81)
© www.soinside.com 2019 - 2024. All rights reserved.