Flask / JSON前导斜线

时间:2019-02-20 22:11:45

标签: javascript python json apache flask

以下Flask应用具有一个HTML路由和一个JSON路由。

app.py

from flask import Flask, render_template, request, jsonify

app = Flask(__name__)


@app.route('/bar)
def bar_index():
    return render_template('index.html')


@app.route('/path/to/json', methods=['POST'])
def path_to_json_fn():
    ret = {'ret_str': 'You sent *{}*'.format(request.json['my_str'])}
    return jsonify(ret)

该应用程序呈现以下HTML页面,其中包含一个字段,其中idstr_field

templates / index.html

<!DOCTYPE html>
<body>
    <h2>Ping</h2>
    <form action="javascript:handle_ping()" method="post">
        Enter a string:
        <input type="text" id="str_field">
    </form>
    <br />
    <p id="output_message"></p>

    <script src="https://d3js.org/d3.v5.min.js"></script>

    <script src="{{ url_for('static', filename='client.js')}}"></script>
</body>

以下JS代码检索str_field,在其周围构造一条消息,然后向path/to/json处的JSON端点发送请求。

static / client.js

function handle_ping() {
    var s = d3.select('#str_field').node().value;
    var json_msg = JSON.stringify({'my_str': s});

    var msg_sent = {
        method: "POST",
        headers: {"Content-type": "application/json; charset=UTF-8"},
        body: json_msg,
    };

    d3.json("path/to/json", msg_sent)
      .then(function(json_received) {
          var e = d3.select('#output_message');
          e.text(json_received.ret_str);
      })
      .catch(error => {console.log(error);});
}

该应用程序通过mod_wsgi托管在Apache上。通过Apache的conf/extra/httpd-vhosts.conf,该应用不是托管在server/上,而是托管在server/foo/WSGIScriptAlias /foo "/some/place/web.wsgi")上。

因此,在server/foo/上可以看到该应用程序,而在server/foo/bar上可以访问上面提供的页面。

尽管@app.route('/bar)中存在斜杠,但HTML页面仍可重定位。的确,如果省略该前导斜线,werkzeug将会抱怨:

File "....werkzeug/routing.py", line 603, in __init__
    raise ValueError('urls must start with a leading slash')
ValueError: urls must start with a leading slash

@app.route('/path/to/json', methods=['POST'])也是如此。前导斜杠是必需的。

d3.json("path/to/json", msg_sent)d3.json("/path/to/json", msg_sent)有什么区别?

我看到后者是有问题的,因为当服务器在server/path/to/json上提供JSON时,会在server/foo/path/to/json与服务器联系,从而导致404。

前者(不带斜杠)是发送JSON请求以保持应用程序可重定位的适当方法吗?似乎还有其他问题在起作用,即,寻找"path/to/json"并且在路径“ server / foo / bar”提供的HTML页面中加载的JS代码将寻找“ server / foo / bar / path / to / json',但我尚未能够在此MCVE中产生此问题。尽管JSON API不在任何蓝图之内,但它可能与在较大的应用程序中使用app工厂方法有关,或者与蓝图有关。

您能否阐明正在发生的事情?

相关:

0 个答案:

没有答案
相关问题