繁体   English   中英

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

[英]Python (Flask) serving Angular project's index.html file

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

我在服务默认路由“/”时遇到问题,它应该加载 index.html 和相关组件。 这是我的烧瓶功能:

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

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

带有 Angular/Flask 的空 Chrome 窗口

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

在此处输入图片说明

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

在此处输入图片说明

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

<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以确保提供支持文件。

主文件

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

这是一个老问题,但接受的答案对我不起作用。 所以这是我的解决方案,适用于角度路由:


我的文件夹结构:

/angular
    /src
    angular.json
    ... angular project files
/public
    index.html
    ... angular build files
/venv
server.py

在我的angular.json 中,我更改了outputPath以实现上述结构:

"outputPath": "../public"

server.py 中

import os.path

@app.route("/custom-endpoint")
def custom_endpoint_handler():
    return jsonify(myKey="myValue")


# Serving static files
@app.route('/', defaults={'path': ''})
@app.route('/<string:path>')
@app.route('/<path:path>')
def static_proxy(path):
    if os.path.isfile('public/' + path):
        # If request is made for a file by angular for example main.js
        # condition will be true, file will be served from the public directory
        return send_from_directory('public', path)
    else:
        # Otherwise index.html will be served,
        # angular router will handle the rest
        return app.send_static_file("index.html")

脚注:我是烧瓶新手。 因此,如果有任何错误,欢迎进行任何改进或修复。

正如 Flask 文档中提到的:

只需在您的包中或模块旁边创建一个名为 static 的文件夹,它将在应用程序的 /static 中可用。

因此,如果您在以下位置使用模板:

templates/dist/templates/index.html
static/ # set static folder there

或者,取决于您对应用程序的排序方式:

templates/dist/static/ # set static folder there

看看他们如何在文档中对应用程序进行排序:

/application.py
/templates
    /hello.html

或者如果您使用模块文件夹:

/application
    /__init__.py
    /templates
        /hello.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM