【问题标题】:How to integrate python api request and response with javascript如何将python api请求和响应与javascript集成
【发布时间】:2019-04-29 10:57:30
【问题描述】:

我在 server.py 中有一组 api,即用于文件上传、预处理数据以进行分析等。我想通过 UI 集成和进行 api 调用。即使文件上传我也无法开始,因为我无法通过我的 UI 与 API 交互。请帮助我了解如何将 UI 与 API 集成。

API 正在 JSON 文件中返回输出:

代码sn-p server.py:

from flask import Flask, render_template, request
from flask_restplus import Resource, Api, fields, reqparse
import os
import pandas
import json
from werkzeug.contrib.fixers import ProxyFix
from waitress import serve
from werkzeug.datastructures import FileStorage
import parser
import uuid
import importlib
@app.route('/dashboard')
def dashboard():
return render_template('dashboard.html')
@api.route('/api/v1/fileupload')
class upload_file(Resource):
@api.expect(file_upload_model)
def post(self):
    try:
        requestid = uuid.uuid4().hex
        parser = reqparse.RequestParser()
        parser.add_argument('file', type=FileStorage, location='files', 
        required=True)
        args = parser.parse_args()
        # checking if the file is present or not.
        #if 'file' not in request.files:
        #    return "No file found"
        file = args.get('file')

        #file = request.files['file']

        path = os.path.join(os.path.join(server_path, requestid + "\\" + 
        "rawdata"))
        if os.path.exists(path):
            pass
        else:
            os.makedirs(path)

        abs_path = path + "\\" + file.filename
        file.save(abs_path)
        return {"requestid": requestid, "upload_status": "success", 
        "location": abs_path}, 200
        except Exception as e:
        requestid = None
        return {"requestid": requestid, "upload_status": "failed::" + str(e) 
        , "location": ""}

dashboard.html 的代码 sn-p

<form class="navbar-brand" method="POST">
    <script type="text/javascript" language="javascript">
        function checkfile(sender) {
            var validExts = new Array(".csv");
            var fileExt = sender.value;
            fileExt = fileExt.substring(fileExt.lastIndexOf('.'));
            if (validExts.indexOf(fileExt) < 0) {
                alert("Invalid file selected, please select only" +
                    validExts.toString() +"file");
                return false;
            }
            else return true;
        }
    </script>
    <div>Select a file to Upload: <br>
        <input type="file" name="fileupload"
               value="fileupload" id="fileupload" onchange=checkfile(this) /> <br>
        <small>please select .csv file only</small>
    </div>
</form>

【问题讨论】:

    标签: javascript python html api file-upload


    【解决方案1】:

    您似乎缺少上传文件的整个部分。这段代码应该能让你到达那里。

    • 删除了您的 checkfile 函数,并使用了 accept 属性
    • 为表单提交和上传添加了事件监听器
    • 防止页面重定向,你可以决定显示什么
    • output div 将显示上传状态。

    解决方案

    var form = document.forms.namedItem("upload-form");
    
    form.addEventListener('submit', function(e) {
      var output = document.getElementById("output");
      var data = new FormData(this);
      var request = new XMLHttpRequest();
    
      request.open("POST", "/api/v1/fileupload", true);
      request.onload = function(e) {
        if (request.status == 200) {
          output.innerHTML = "Uploaded!";
        } else {
          output.innerHTML = "Error " + request.status + " occurred when trying to upload your file.<br \/>";
        }
      };
    
      request.send(data);
      e.preventDefault();
    }, false);
    <form class="navbar-brand" name="upload-form" enctype="multipart/form-data">
      <div>Select a file to Upload: <br>
          <input
            type="file"
            name="fileupload"
            id="fileupload"
            accept=".csv"
          /> <br>
          <small>please select .csv file only</small>
      </div>
      <button type="submit">Upload</button>
    </form>
    <div id="output"></div>

    【讨论】:

    • 非常感谢。我尝试了上述方法,现在选择文件并单击上传。页面只是刷新而不给出成功或错误状态代码。请你也帮忙。谢谢,莫妮卡 C
    • 你能把你最近的代码放在 jsFiddle 上并分享链接吗?
    • 下面是curl命令 curl -X POST \localhost:5510/api/v1/fileupload \ -H 'cache-control: no-cache' \ -H 'content-type: multipart/form-data;边界=----WebKitFormBoundary7MA4YWxkTrZu0gW' \ -F 'file=@C:\Users\sample data.csv'。如何在那里获取上述文件对象或如何在上述代码中调用文件对象
    • 导致刷新的不是请求,而是您的代码中的错误,这就是我需要查看它的原因。
    • 这是因为你的 JavaScript 在你的 HTML 之前,所以它找不到要附加监听器的 HTML 元素。你要么必须把你的 JS 放在最底层,要么用window.addEventListener('DOMContentLoaded', function(){ \\ your code here })
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 2016-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-07
    相关资源
    最近更新 更多