如何将Flask应用的单个页面改造为Angular单页应用
实现Flask路由返回Angular单页应用的方案
需求概述
现有基于Jinja模板的Flask后台管理应用(运行在http://localhost:5000/),需将其中/mailing-list/路由改为返回Angular单页应用(Angular开发环境运行在http://localhost:4200/),无需将整个Flask应用迁移到Angular。
现有目录结构
. ├── angular.json ├── app.py ├── dist │ └── mailing-list │ └── browser ├── src │ ├── app │ │ ├── app-routing.module.ts │ │ ├── app.component.html │ │ ├── app.component.scss │ │ ├── app.component.spec.ts │ │ ├── app.component.ts │ │ ├── app.module.ts │ │ └── mailinglist │ │ ├── mailinglist.component.html │ │ ├── mailinglist.component.scss │ │ └── mailinglist.component.ts │ ├── assets │ ├── index.html │ ├── main.ts │ └── styles.scss ├── static └── templates
现有代码片段
Flask的app.py
from flask import ( Flask, render_template, ) app = Flask(__name__) @app.route('/') def index(): context = {} return render_template('index.html', context=context) @app.route('/mailing-list/') # 需改为返回Angular页面的路由 def mailing_list(): context = {} return render_template('mailing-list.html', context=context) if __name__ == '__main__': app.run(host='localhost', port=5000) # 修正原代码端口笔误,Flask应运行在5000
Angular的index.html
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>MailingList</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <div class="pure-g outer"> <h1>Mailing List Manager</h1> <app-mailinglist></app-mailinglist> </div> </body> </html>
具体实现步骤
1. 构建Angular应用并指定基础路径
由于Angular单页将在Flask的/mailing-list/路径下运行,构建时需设置base-href参数确保静态资源路径正确:
ng build --base-href /mailing-list/
构建完成后,产物会生成在dist/mailing-list/browser目录下。
2. 修改Flask配置与路由
更新app.py,使其指向Angular构建后的静态资源,并返回Angular的index.html:
from flask import Flask, render_template, send_from_directory import os app = Flask(__name__) # 设置Flask静态文件夹指向Angular构建后的目录 app.static_folder = 'dist/mailing-list/browser' @app.route('/') def index(): context = {} return render_template('index.html', context=context) # 返回Angular的index.html @app.route('/mailing-list/') def mailing_list(): return send_from_directory(app.static_folder, 'index.html') # 处理Angular静态资源(如JS、CSS、图片等) @app.route('/mailing-list/<path:path>') def serve_angular_assets(path): file_path = os.path.join(app.static_folder, path) if os.path.exists(file_path): return send_from_directory(app.static_folder, path) # 若路径不存在,返回index.html(适配Angular路由,即使无路由也可保留) return send_from_directory(app.static_folder, 'index.html') if __name__ == '__main__': app.run(host='localhost', port=5000, debug=True)
3. 验证Angular基础路径(可选)
若构建时未使用--base-href参数,需手动修改Angular的index.html中的<base href="/">为:
<base href="/mailing-list/">
(推荐使用构建参数自动替换,避免手动修改)
4. 测试运行
- 确保Angular已完成构建
- 启动Flask应用:
python app.py - 访问
http://localhost:5000/mailing-list/,即可看到Angular单页应用正常加载
内容的提问来源于stack exchange,提问作者commadelimited
相关产品推荐
相关产品推荐

