【问题标题】:Flask app: Post json to server for use in a different REST APIFlask 应用程序:将 json 发布到服务器以在不同的 REST API 中使用
【发布时间】:2021-12-05 18:56:25
【问题描述】:

我有一个带有一些普通 Javascript 的 Flask 应用程序(我不知道 JQuery)。它执行以下操作: (1) 用户在 HTML 表格中输入一些数据。 (2) 然后将数据解析为 JSON。 (3) 我想将 JSON 文件发布到服务器。 (4) 从服务器,JSON 对象被发布到不同的 REST API 以供进一步使用。

步骤 1、2 和 4 工作(我可以 console.log JSON 对象),但我不知道如何将 JSON 对象从客户端发布到服务器。我一直看到的选项是在标签之间移动表格,然后通过request.form 发布表格。我很高兴这样做,但与在客户端解析 JSON 并将干净的对象发布到第三方 REST API 可以立即使用的服务器相比,这似乎很笨拙。我在这里错过了什么?

<!DOCTYPE html>
    <html>
    <body>
    <body>
      <button id="click">Click</button>
      <table id="myTable">
<thead>
  <tr>
    <th>ID</th>
    <th>Name</th>
    <th>Price</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td>001</td>
    <td>Trousers</td>
    <td>9.99</td>
  </tr>
  <tr>
    <td>002</td>
    <td>Shirt</td>
    <td>19.99</td>
  </tr>
  <tr>
    <td>003</td>
    <td>Shoes</td>
    <td>49.99</td>
  </tr>
</tbody>
</table>


    </body>

    <script>
      const btn = document.getElementById("click");
      btn.addEventListener("click", function () {
        tableToJson(table);
      })
      
    let table = document.getElementById("myTable");
    function tableToJson(table) {
    var data = [];

    // first row needs to be headers
    var headers = [];
    for (var i=0; i<table.rows[0].cells.length; i++) {
        headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
    }

    // go through cells
    for (var i=1; i<table.rows.length; i++) {

        var tableRow = table.rows[i];
        var rowData = {};

        for (var j=0; j<tableRow.cells.length; j++) {

            rowData[ headers[j] ] = tableRow.cells[j].innerHTML;

        }

        data.push(rowData);
    }       
    console.log(data);
    
    return data;
}
    </script>
    </html>
app = Flask(__name__) # Create an Instance

@app.route('/', methods=['GET', 'POST']) # Route the Function and allow Requests
def main(): # Run the function
    if request.method == 'POST': # Identify Request Method
        value = request.form['input'] # Gather the Post Request
        return value
    if request.method == 'GET': # Identify Request Method
        return render_template('index.html')

app.run(host='0.0.0.0', port=5000, debug=True) # Run the Application (in debug mode)```

【问题讨论】:

    标签: javascript python html json flask


    【解决方案1】:

    使用Fetch API 发送数据。
    在下面的示例中,数据被转换为符合 JSON 标准的字符串,并通过 POST 发送到服务器。

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title></title>
      </head>
      <body>
        <button id="click">Click</button>
        <table id="my-table">
          <thead>
            <tr>
              <th>ID</th>
              <th>Name</th>
              <th>Price</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>001</td>
              <td>Trousers</td>
              <td>9.99</td>
            </tr>
            <tr>
              <td>002</td>
              <td>Shirt</td>
              <td>19.99</td>
            </tr>
            <tr>
              <td>003</td>
              <td>Shoes</td>
              <td>49.99</td>
            </tr>
          </tbody>
        </table>
    
        <script type="text/javascript">
          (() => {
            const tableToJSON = (tableElem) => {
              const tableRows = Array.from(tableElem.rows);
              const tableHead = Array.from(tableRows[0].cells).map(cell => {
                return cell.innerHTML.toLowerCase().replace(/ /g,'_')
              });
              return tableRows.slice(1).map(row => {
                const rowData = {}
                Array.from(row.cells).forEach((cell, i) => {
                  return rowData[tableHead[i]] = cell.innerHTML;
                });
                return rowData;
              });
            };
    
            const btnElem = document.getElementById('click');
            btnElem.addEventListener('click', (evt) => {
              const tableElem = document.getElementById('my-table');
              const tableData = tableToJSON(tableElem);
    
              // Post JSON data to the server.
              const url = '/data';
              fetch(url, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(tableData)
              }).then(resp => resp.json())
                .then(data => console.log(data));
            });
          })();
        </script>
      </body>
    </html>
    

    然后您可以使用request.get_json() 请求和处理服务器上的数据。来自服务器的响应是一个简单的 JSON 对象,用jsonify 转换。

    from flask import Flask
    from flask import render_template, request, jsonify
    
    app = Flask(__name__)
    app.secret_key = 'your secret here'
    
    @app.route('/', methods=['GET'])
    def index():
        return render_template('index.html')
    
    @app.route('/data', methods=['POST']) 
    def data(): 
        data = request.get_json()
        print(data)
        return jsonify(success=True)
    

    【讨论】:

    • 恐怕这在我的设置中不起作用(我使用 replit)。为了运行它,我在 main.py 中添加了 app.run(host='0.0.0.0', port=8080)。 index.html 被加载了,但是 console.log 和 print 语句都没有执行,所以我猜没有数据发布到服务器?
    • @vauss 对不起,我稍微改变了我的答案。如果您的服务器在端口 8080 上运行,您将不得不调整它发送到的 url。我现在已经减少了路径的 url。这就是它在您的设置中的工作方式。
    猜你喜欢
    • 2018-12-12
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    • 1970-01-01
    • 2020-03-21
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    相关资源
    最近更新 更多