gpt4 book ai didi

javascript - Python (Flask) 为 Angular 项目的 index.html 文件提供服务

转载 作者:太空狗 更新时间:2023-10-29 18:22:18 24 4
gpt4 key购买 nike

有人知道如何使用 Flask 为 Angular 单页应用程序提供服务吗?

我在提供默认路由“/”时遇到问题,它应该加载 index.html 和相关组件。这是我的 Flask 函数:

@app.route('/')
def hello_world():
return send_file('templates/dist/templates/index.html')

当我访问 localhost:5000 时,我得到一个空的 Chrome 浏览器窗口:

Empty Chrome window with Angular / Flask

以及 Chrome 开发控制台中的以下错误:

enter image description here

这是应该出现在 Chrome 中的内容:

enter image description here

我预计这些错误是因为 Flask 不知道在哪里可以找到支持文件来呈现 Angular 组件。按照 Angular 快速入门教程中的说明,我的 index.html 大部分是空的,app-root 作为 HTML 正文元素的占位符:

<body>
<app-root></app-root>
<script type="text/javascript" src="runtime.js"></script><script type="text/javascript" src="polyfills.js"></script><script type="text/javascript" src="styles.js"></script><script type="text/javascript" src="vendor.js"></script><script type="text/javascript" src="main.js"></script></body>

有谁知道如何告诉 Flask 让 Angular 渲染页面?

最佳答案

为简化设置,请考虑使用 Angular CLI在构建过程中将所有文件放在分发目录中,即通过在 angular.json 中指定 outputPath。您可以使用 angular.json assets 部分在构建期间移动您的 Python 文件。

Angular .json

"your-project": {
"root": "your-project-directory",
"sourceRoot": "your-project-directory/src",
"projectType": "application",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist",
"index": "your-project-directory/src/index.html",
"main": "your-project-directory/src/main.ts",
...

"assets": [
{
"glob": "**/*",
"input": "your-project-directory/src/assets/",
"output": "assets"
},
{
"glob": "**/*",
"input": "your-project-directory/src/python/",
"output": "."
}



dist 目录的顶层,将具有基本 Flask 设置的 main.pyindex.html 一起放置。请注意 static_proxy 以确保提供支持文件。

主.py

from flask import Flask, send_from_directory

app = Flask(__name__)


@app.route('/<path:path>', methods=['GET'])
def static_proxy(path):
return send_from_directory('./', path)


@app.route('/')
def root():
return send_from_directory('./', 'index.html')


if __name__ == '__main__':
# This is used when running locally only. When deploying use a webserver process
# such as Gunicorn to serve the app.
app.run(host='127.0.0.1', port=8080, debug=True)


@app.errorhandler(500)
def server_error(e):
return 'An internal error occurred [main.py] %s' % e, 500

关于javascript - Python (Flask) 为 Angular 项目的 index.html 文件提供服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53824239/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com