首页 > 解决方案 > 如何在 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

请建议

标签: pythonpython-3.xweb-servicesweb-applicationsweb.py

解决方案


利用

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() 

这会将您的文件写入指定位置。


推荐阅读