【发布时间】: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