如何通过使用Python web.py处理上传CSV文件

问题描述 投票:1回答:1

我试图让我的模型API。

我想上传csv文件,然后读取CSV数据,然后在API使用模型进行预测。

我能上传文件并保存路径,但无法读取CSV数据进行预测通过使用Python中web.py

我已保存的预测模型,并在此代码,然后预测数据加载。

upload.朋友

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

请建议

python python-3.x web-services web-applications web.py
1个回答
0
投票

采用

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

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

© www.soinside.com 2019 - 2024. All rights reserved.