-1

私がやりたいことは、次のようないくつかのルートで HTML+css+js ファイルを静的ページとして送信することです。

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

特に、テンプレートから離れて、フラスコ アプリの他のルートに接続する ajax/websocket に依存して、JSON オブジェクトを取得し、Web ページを更新したいと考えています。また、css と js ファイルを html でリンクするのに苦労しました。このurl_for方法は完全にテンプレート システムに依存しているようで、私の場合は適切に機能していないようです。

例えば。

Directory Structure

  • リダイレクト サーバー (アプリのホーム フォルダー)
    • 静的
    • index.html
    • main.js
    • venv(python3 仮想環境)
    • 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 -

jsHTML は正常に返されますが、ファイルが見つかりません

4

2 に答える 2

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>
于 2015-10-29T08:05:35.933 に答える