gpt4 book ai didi

python - 带有python flask后端的Angular 4前端如何呈现简单的索引页面

转载 作者:太空狗 更新时间:2023-10-29 17:19:37 25 4
gpt4 key购买 nike

你好 Python 社区我是 angular 和 node.js 开发人员,我想尝试将 Python 作为我服务器的后端,因为我是 python 的新手我想问你如何定位包含所有 HTML、CSS 和 js 的 dist 文件夹来自 Flask Python 服务器中 Angular 4 应用程序的文件

因为我的应用程序是 SPA 应用程序,所以我在 Angular 路由组件中设置了路由

当我跑来跑去或任何其他路线时,我收到此字符串消息 './dist/index.html'而且我知道我返回了字符串消息,但我想告诉 flask 用户在 URL 上键入的任何路由让 Angular 呈现页面,因为在我的 Angular 应用程序中我已经设置了这个页面并且正在工作

关于如何从 flask 和 angular 开始构建简单的 REST API 的任何帮助

现在我有了这个文件结构

python-angular4-app
|___ dist
| |___ index.html
| |___ style.css
| |___ inline.js
| |___ polyfill.js
| |___ vendor.js
| |___ favicon.ico
| |___ assets
|
|___ server.py

我的server.py有这个内容

from flask import Flask

app = Flask(__name__, )

@app.route('/')
def main():
return './dist/index.html'


@app.route('/about')
def about():
return './dist/index.html'


@app.route('/contact')
def contact():
return './dist/index.html'

if __name__ == "__main__":
app.run(debug=True)

最好的问候 George35mk 感谢您的帮助

最佳答案

因为我遇到了同样的问题,我希望这个答案能帮助再次寻找它的人。

  1. 首先创建并构建 Angular 应用程序。 (您将在“dist”文件夹中获得所有必需的 js 文件和 index.html 文件。
  2. 创建具有所需端点的 python + flask 网络应用。

    from flask import Flask,render_template
    app = Flask(__name__)

    @app.route("/")
    def hello():
    return render_template('index.html')

    if __name__ == "__main__":
    app.run()
  3. 在您的 Python 应用程序根文件夹中创建一个文件夹“templates”。

  4. 将 index.html 文件从 angular dist 文件夹复制到新创建的“templates”文件夹。

  5. 在您的 python 应用程序根文件夹中创建另一个名为“static”的文件夹

  6. 然后将所有其他静态文件(JS 文件和 CSS 文件)复制到这个新文件夹。

  7. 像这样更新您的 index.html 文件静态文件 url。

      <script type="text/javascript" src="/static/inline.bundle.js"></script>

Flask look static files inside '/root_folder/static' folder and update url relative to this structure.

完成。现在您的应用程序将在 localhost:5000 上提供服务,并且将提供 Angular 应用程序。最终的文件夹结构将是这样的,

    /pythondApplication
|-server.py
|-templates
| -index.html
|-static
| -js files and css files

由于这是我在stackoverflow的第一个回答,如果有什么需要更正的地方,欢迎提出来。

关于python - 带有python flask后端的Angular 4前端如何呈现简单的索引页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45692749/

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