用烧瓶提供HTML + CSS + JS(角度)

时间:2015-10-28 09:48:26

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

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

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

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

例如

Directory Structure

  • redirect-server(app主文件夹)
    • 静态
    • 的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文件

2 个答案:

答案 0 :(得分:0)

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

app.send_static_file("index.html")

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

答案 1 :(得分:0)

我无法在不依赖模板的情况下找到它。

  

以下为我工作

按如下方式重构我的目录

  • 重定向服务器
    • 静态
      • 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>
相关问题