【问题标题】:Serving HTML+CSS+JS(angular) with flask使用烧瓶提供 HTML+CSS+JS(angular)
【发布时间】:2015-10-28 09:48:25
【问题描述】:

我想要做的是,只需将 HTML+css+js 文件作为静态页面发送到某些路由上,例如:

@app.route('/', methods=[GET])
def index():
  return <html+css+js>

我特别想远离模板,并依靠连接到烧瓶应用程序的其他路由的 ajax/websocket 来获取 JSON 对象并更新网页。我也很难在 html 中链接 css 和 js 文件。 url_for 方法似乎完全依赖模板系统,在我的情况下似乎无法正常工作。

例如。

Directory Structure

  • 重定向服务器(应用主文件夹)
    • 静态
    • index.html
    • main.js
    • venv(python3 virtualenv)
    • main.py(烧瓶应用)

main.py

from flask import Flask, redirect
from flask import render_template

app = Flask(__name__)

@app.route('/')
def index():
    return redirect("/abc/xyz")

@app.route('/abc/xyz')
def abc():
    return app.send_static_file("index.html")

app.run(debug=True)

index.html

<!DOCTYPE html>

<html>
    <head>
        <title>Hello</title>
        <script type="text/javascript" src="{{ url_for('static', filename='main.js') }}"></script>
    </head>
    <body>
        <h1>Welcome!</h1>
    </body>
</html>

我得到的错误如下

127.0.0.1 - - [28/Oct/2015 14:07:02] "GET /abc/%7B%7B%20url_for('static',%20filename='main.js')%20%7D%7D HTTP/1.1" 404 -

HTML 正常返回,但找不到 js 文件

【问题讨论】:

    标签: angularjs python-3.x flask static-pages


    【解决方案1】:

    您将模板作为静态文件发送。

    app.send_static_file("index.html")
    

    更好render it, as shown in the docs :)

    【讨论】:

    • 上面已经提到过用js链接不行
    • @IshanKhare:在服务器上替换这样的模板表达式正是flask、Django、Mason、Catalyst等人的做法。工作,并且反对该范式机制成功的机会几乎为零,更不用说交付可维护的代码了。您能否通过“将其 [?] 与 js' 链接不起作用”来详细说明您试图表达的具体症状是什么?
    • @IshanKhare 做到了。看来您也做了,因为从您自己的回答看来,您发现“127.0.0.1 - - [28/Oct/2015 14:07:02]”GET /abc/%7B%7B%20url_for('static ',%20filename='main.js')%20%7D%7D HTTP/1.1" 404 -" 只是服务器日志告诉你我在散文中告诉你的方式。
    • render_template 不起作用,因为我在任何地方使用 {{ }} 作为 angular,jinja 模板在尝试将其解析为模板表达式时会引发错误
    【解决方案2】:

    如果不依赖模板,我无法找到它的工作方式。

    以下对我有用

    如下重组我的目录

    • 重定向服务器
      • 静态
        • main.js
      • 模板
        • index.html
      • main.py

    main.py

    from flask import Flask, redirect
    from flask import render_template
    
    app = Flask(__name__)
    
    @app.route('/')
    def index():
        return redirect("/abc/xyz")
    
    @app.route('/abc/xyz')
    def abc():
        return render_template("index.html")
    
    app.run(debug=True)
    

    index.html

    <!DOCTYPE html>
    
    <html>
        <head>
            <title>Hello</title>
            <script type="text/javascript" src="{{ url_for('static', filename='main.js') }}"></script>
        </head>
        <body>
            <h1>Welcome!</h1>
        </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-20
      • 1970-01-01
      • 2017-05-10
      • 1970-01-01
      • 1970-01-01
      • 2022-12-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多