python - 如何在 python 中使用 web.py 处理上传的 csv 文件
问题描述
我正在尝试为我的模型制作 API。
我正在尝试上传 csv 文件,然后在 csv 中读取数据,然后在 API 中使用模型进行预测。
我可以上传文件并保存在路径中,但无法通过在 python 中使用 web.py 读取 csv 数据进行预测
我保存了预测模型并加载到此代码中,然后预测数据。
上传.py
import web
from sklearn.externals import joblib
import requests
urls = ('/upload', 'Upload')
class Upload:
def GET(self):
web.header("Content-Type","text/html; charset=utf-8")
return """<html><head></head><body>
<form method="POST" enctype="multipart/form-data" action="">
<input type="file" name="myfile" />
<br/>
<br/>
<input type="submit" />
</form>
</body></html>"""
def POST(self):
x = web.input(myfile=[])
filedir = 'D:/API_CITY_PRED/Upload' # change this to the directory you want to store the file in.
svmModel = open('D:/Model/model_city_id_predictor.pkl', 'rb')
svmModel = joblib.load(svmModel)
class_prediced = svmModel.predict(x)
output = "Predicted City ID: " + str(class_prediced)
print (output)
if 'myfile' in x: # to check if the file-object is created
filepath=x.myfile.filename.replace('\\','/') # replaces the windows-style slashes with linux ones.
filename=filepath.split('/')[-1] # splits the and chooses the last part (the filename with extension)
fout = open(filedir +'/'+ filename,'wb') # creates the file where the uploaded file should be stored
fout.write(x.myfile.file.read()) # writes the uploaded file to the newly created file.
fout.close() # closes the file, upload complete.
return output
raise web.seeother('/upload')
if __name__ == "__main__":
app = web.application(urls, globals())
app.run()
编辑-1
# x is the input data
svmModel = open('D:/Model/model_city_id_predictor.pkl', 'rb') # SVM Model Imported
svmModel = joblib.load(svmModel) # Model Loaded
class_prediced = svmModel.predict(x) # here we are using to predict
请建议
解决方案
利用
x = web.input(file={})
fout = open('path/to/location/', 'wb') # creates the file where the uploaded file should be stored
fout.write(x.file.file.read()) # writes the uploaded file to the newly created file.
fout.close()
这会将您的文件写入指定位置。
推荐阅读
- c++ - std::any 的支撑初始化
- php - 显示图片和上传图片问题
- arrays - bash:从数组中获取一个键值对,或设置为“”
- c# - Visual Studio 2019 导航到上一个编辑
- sql-server - T-SQL 将 XML 值作为包含行的数据集返回
- php - 仅将产品标签从 WooCommerce 单一产品元标签移动到产品描述
- julia - Julia 管道运算符适用于涉及乘法但不适用于幂运算的函数
- javascript - 如何使用 Node.js 上传文件夹并保持文件夹结构?
- database-normalization - 最小覆盖FD
- c# - 是否可以通过我创建的 Revit API 按钮打开我的 winForm?