Python(Flask)服务Angular项目的index.html文件
问题内容:
有谁知道如何使用Flask服务Angular单页应用程序?
我在提供默认路由“ /”时遇到了麻烦,该默认路由应加载index.html和相关组件。这是我的Flask函数:
@app.route('/')
def hello_world():
return send_file('templates/dist/templates/index.html')
当我访问localhost:5000时,我得到一个空的Chrome浏览器窗口:
以及Chrome开发者控制台中的以下错误:
这是在Chrome中显示的内容:
我希望这些错误是因为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
将所有文件放置在分发目录中,即通过outputPath
在angular.json中指定。您可以assets
在构建期间使用angular.json部分移动您的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
目录的顶层,将您main.py
的基本Flask设置与一起放置index.html
。注意 static_proxy
以确保提供支持文件。
main.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