簡體   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