복붙노트

[PYTHON] BottlePy 템플릿에 자바 스크립트 또는 CSS 파일을로드하는 방법은 무엇입니까?

PYTHON

BottlePy 템플릿에 자바 스크립트 또는 CSS 파일을로드하는 방법은 무엇입니까?

BottlePy를 사용하여 html 템플릿을 반환하려고합니다. 그리고 이것은 잘 작동합니다. 하지만 내 tpl 파일에 이런 자바 스크립트 파일을 삽입하는 경우 :

<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

감사.

해결법

  1. ==============================

    1.먼저, main.js를 실제로 제공하기 위해서는 dev 서버가 필요합니다. 그렇지 않으면 브라우저에서 사용할 수 없습니다.

    먼저, main.js를 실제로 제공하기 위해서는 dev 서버가 필요합니다. 그렇지 않으면 브라우저에서 사용할 수 없습니다.

    모든 .js 및 .css 파일을 작은 웹 응용 프로그램의 고정 디렉토리 아래에 두는 것이 일반적입니다. 따라서 레이아웃은 다음과 같아야합니다.

      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')
    

    그러면 정적 / 브라우저 아래에 파일이 실제로 제공됩니다.

    이제 마지막으로. JavaScript를 다음과 같이 지정했습니다 :

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

    이는 .js에 대한 경로가 현재 페이지와 관련이 있음을 의미합니다. 개발 서버에서 인덱스 페이지 (/)는 /js/main.js에서 .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'인 핸들러를 찾아서 그것에 대한 적절한 경로를 계산합니다. dev 서버의 경우, 이것은 항상 / static /입니다. 템플릿에서 하드 코딩 할 수도 있지만 두 가지 이유로 권장하지 않습니다.

  2. ==============================

    2.난 당신이 잘못된 위치에 main.js 파일을 넣는 것 같아요.

    난 당신이 잘못된 위치에 main.js 파일을 넣는 것 같아요.

    이 파일 경로는 템플릿에 대한 경로가 아니라 요청 된 URL에 상대적이어야합니다. 따라서 template / js / main.js와 같은 폴더에 넣으면 작동하지 않습니다.

  3. ==============================

    3.다음은 Bottle 웹 프로젝트에서 CSS / JS와 같은 정적 파일을 추가하는 작업 방식입니다. 부트 스트랩과 파이썬 3.6을 사용하고 있습니다.

    다음은 Bottle 웹 프로젝트에서 CSS / JS와 같은 정적 파일을 추가하는 작업 방식입니다. 부트 스트랩과 파이썬 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>
    

    산출

  4. from https://stackoverflow.com/questions/6978603/how-to-load-a-javascript-or-css-file-into-a-bottlepy-template by cc-by-sa and MIT license