15

BottlePy で html テンプレートを返そうとしています。そして、これはうまくいきます。しかし、tpl ファイルに次のような JavaScript ファイルを挿入すると、次のようになります。

<script type="text/javascript" src="js/main.js" charset="utf-8"></script>

404 エラーが発生します。 (リソースの読み込みに失敗しました: サーバーは 404 (見つかりません) のステータスで応答しました)

この問題を解決する方法を知っている人はいますか?

これが私のスクリプトファイルです:

from bottle import route, run, view

@route('/')
@view('index')
def index():
    return dict()
run(host='localhost', port=8080)

これが「./views」サブフォルダーにあるテンプレート ファイルです。

<!DOCTYPE html>
<html lang="de">
    <head>
        <meta charset="utf-8" />
        <script type="text/javascript" src="js/main.js" charset="utf-8"></script>
    </head>
    <body>
    </body>
</html>

私のjsファイルを探す開発サーバーからの「rootPath/js/main.js」でしょうか?

ファイルの構造は次のとおりです。

app.py
-js
 main.js
-views
 index.tpl

ありがとう。

4

3 に答える 3

30

まず、開発サーバーが実際にサービスを提供する必要がありますmain.js。そうしないと、ブラウザーで使用できません。

.js小さな Web アプリでは、ディレクトリの下にすべての.cssファイルを配置するのが通例staticであるため、レイアウトは次のようになります。

  app.py
- static/
    main.js
- views/
    index.tpl

この正確な名前付けとレイアウトは必須ではなく、頻繁に使用されるだけです。

次に、静的ファイルのハンドラーを提供する必要があります。

from bottle import static_file

# ...

@route('/static/:path#.+#', name='static')
def static(path):
    return static_file(path, root='static')

これにより、実際にファイルstatic/がブラウザに提供されます。

では、最後に。JavaScript を次のように指定しました。

<script type="text/javascript" src="js/main.js" charset="utf-8"></script>

これは、へのパスが.js現在のページに相対的であることを意味します。開発サーバーでは、インデックス ページ ( /) が を検索し.js/js/main.js別のページ (たとえば/post/12) が を検索しますが/post/12/js/main.js、確実に失敗します。

get_url代わりに、関数を使用して静的ファイルを適切に参照する必要があります。ハンドラーは次のようになります。

from Bottle import get_url

# ...

@route('/')
@view('index')
def index():
    return { 'get_url': get_url } 

ではindex.tpl、次の.jsように参照する必要があります。

<script type="text/javascript" src="{{ get_url('static', path='main.js') }}" charset="utf-8"></script>

get_urlでハンドラを見つけ、name='static'それへの適切なパスを計算します。開発サーバーの場合、これは常に/static/. おそらくテンプレートにハードコードすることもできますが、次の 2 つの理由からお勧めしません。

  • アプリを本番環境のルート以外の場所にマウントすることはできません。つまり、製品サーバーにアップロードすると、http://example.com/ (ルート) の下に配置できますが、 http://example.com/myapp/の下には配置できません。
  • ディレクトリの場所を変更した場合は/static/、テンプレート全体で検索し、すべてのテンプレートで変更する必要があります。
于 2011-08-08T10:15:03.023 に答える
2

これは、 Bottle Web プロジェクトに CSS/JS のような静的ファイルを追加する作業アプローチです。Bootstrap と Python 3.6 を使用しています。

プロジェクトの構造

project
│   app.py
│   bottle.py
│
├───static
│   └───asset
│       ├───css
│       │       bootstrap-theme.css
│       │       bootstrap-theme.css.map
│       │       bootstrap-theme.min.css
│       │       bootstrap-theme.min.css.map
│       │       bootstrap.css
│       │       bootstrap.css.map
│       │       bootstrap.min.css
│       │       bootstrap.min.css.map
│       │       custom.css
│       │
│       ├───fonts
│       │       glyphicons-halflings-regular.eot
│       │       glyphicons-halflings-regular.svg
│       │       glyphicons-halflings-regular.ttf
│       │       glyphicons-halflings-regular.woff
│       │       glyphicons-halflings-regular.woff2
│       │
│       └───js
│               bootstrap.js
│               bootstrap.min.js
│               jquery.min.js
│               npm.js
│
└───views
        index.tpl

app.py

from bottle import Bottle, run, \
     template, debug, static_file

import os, sys

dirname = os.path.dirname(sys.argv[0])

app = Bottle()
debug(True)

@app.route('/static/<filename:re:.*\.css>')
def send_css(filename):
    return static_file(filename, root=dirname+'/static/asset/css')

@app.route('/static/<filename:re:.*\.js>')
def send_js(filename):
    return static_file(filename, root=dirname+'/static/asset/js')

@app.route('/')
def index():
    data = {"developer_name":"Ahmedur Rahman Shovon",
            "developer_organization":"Datamate Web Solutions"}
    return template('index', data = data)

run(app, host='localhost', port = 8080)

index.tpl

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Bottle web project template">
    <meta name="author" content="datamate">
    <link rel="icon" href="/static/favicon.ico">        
    <title>Project</title>
    <link rel="stylesheet" type="text/css" href="/static/bootstrap.min.css">
    <script type="text/javascript" src="/static/jquery.min.js"></script>
    <script type="text/javascript" src="/static/bootstrap.min.js"></script> 
</head>
<body>
    <!-- Static navbar -->
    <nav class="navbar navbar-default navbar-static-top">
        <div class="container">
            <div class="row">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                        <span class="sr-only">Toggle navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a class="navbar-brand" href="#">Project</a>
                </div>
                <div id="navbar" class="navbar-collapse collapse">
                    <ul class="nav navbar-nav navbar-right">
                        <li><a href="../navbar/">Home</a></li>
                        <li><a href="./">Github</a></li>
                        <li><a href="../navbar-fixed-top/">Stackoverflow</a></li>
                    </ul>
                </div><!--/.nav-collapse -->
            </div>
        </div>
    </nav>
    <div class="container">
        <div class="row">
            <div class="jumbotron">
            <h2>Welcome from {{data["developer_name"]}}</h2>
                <p>This is a template showcasing the optional theme stylesheet included in Bootstrap. Use it as a starting point to create something more unique by building on or modifying it.</p>
            </div>
        </div>
        <!--./row-->
        <div class="row">
            <hr>
            <footer>
                <p>&copy; 2017 {{data["developer_organization"]}}.</p>
            </footer>           
        </div>
    </div> 
    <!-- /container -->
</body>
</html>

出力

ボトルのブートストラップのデモ

于 2017-08-18T16:44:02.837 に答える
0

main.jsファイルを間違った場所に置いていると思います。

このファイル パスは、テンプレートへのパスに対してではなく、要求された URL に対して相対的である必要があることに注意してください。したがって、次のようなフォルダーに入れると機能しtemplate/js/main.jsません。

于 2011-08-08T06:47:19.400 に答える