【问题标题】:referencing data folder within a flask application在烧瓶应用程序中引用数据文件夹
【发布时间】:2017-11-07 16:33:11
【问题描述】:

对于 Flask 并具有以下目录结构,我如何在我使用 $.getJSON('data/data.json') 语句的 static/js/main.js 文件中引用 data/data.json 文件。我总是收到 404 file not found 回复。

. ├── data │   └── data.json ├── server.py ├── static │   ├── css │   │   └── main.css │   └── js │   └── main.js └── templates ├── form.html

【问题讨论】:

    标签: jquery json flask


    【解决方案1】:

    您可以从 Flask 路由提供 JSON 文件,并在模板中使用 AJAX 操作路由。

    在这里,我使用相同的目录结构重新创建了您的场景,并使用上述方法获得了积极的结果。

    server.py:

    from flask import Flask, render_template, request, url_for
    import os, json   
    
    app = Flask(__name__)
    SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
    
    json_url = os.path.join(SITE_ROOT, "data", "data.json")
    data = json.load(open(json_url))
    
    @app.route('/')
    def show_index():
        return render_template("form.html")
    
    @app.route('/data')
    def get_data():
        global data    
        return json.dumps(data)
    
    if __name__ == '__main__':
        app.run(debug=True)
    

    form.html 包含 jQuery CDN 和主 js 文件:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <meta name="author" content="Ahmedur Rahman Shovon">
        <title>JSON Example</title>
    </head>
    <body>
        <div id="result"></div>
    <!-- jQuery -->
    <script
      src="https://code.jquery.com/jquery-1.12.4.min.js"
      integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
      crossorigin="anonymous"></script>
    <script type="text/javascript" src="{{ url_for('static', filename='js/main.js') }}"></script>
    </body>
    </html>
    

    main.js 文件包含:

    $(document).ready(function () {
        $.getJSON('/data',function(data, status, xhr){
            $("#result").html(data["name"]);        
        })  
    })
    

    data.json 包含以下虚拟 JSON 数据:

    {
        "name": "pumpkin pie",
        "ingredients": [" large eggs plus 1 yolk", "1 tsp ground cinnamon"],
        "methods": {
            "1": "Pre-heat the oven to 200C/400F/Gas 6",
            "2": "If using a shop bought sweet crust pastry case, use one that is 23cm/9in diameter and 4cm/1.5in deep. If using your own pastry, roll it out and use it to line a 23cm/9in pie plate (not loose bottomed). Bake the pastry case blind for 20 minutes."
        } 
    }
    

    输出:

    【讨论】:

    • 太棒了。我试图直接在js 文件中访问data.json。您提倡的方式是通过路由/data 提供数据,然后让$.getJSON 访问该路由
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-17
    相关资源
    最近更新 更多