Flask API无法正常运行,也无法通过request.files.get

时间:2019-08-13 04:34:32

标签: python api csv flask

我是创建用于模型部署的其余api的新手。我正在尝试编写代码来托管系统中的api。我已经阅读了所有相关问题,并尝试了不同的方法,但是没有一个可以回答我所面临的问题。

我写了下面的代码。但是该API无法正常工作。

app = Flask(__name__)
swagger = Swagger(app)

#def main():
@app.route('/',methods=['GET','POST'])
def predict_inv():
    """Example file endpoint
    ---
    parameters:
      - name: input_file
        in: formData
        type: file
        required: true
    """
    print("entry in to the job")
    #dfinput = pd.read_csv(request.files.get("input_file"),encoding='cp1252')
    #dfinput = pd.read_csv(request.files.get('uploaded_file'),encoding="utf8")
    dfinput = pd.read_csv(request.files.get('file'))
    print("entry")
    PicklePath = "C:/Users/koyeli/data/gbsemail_adaV0.1.pkl"
    model1 = joblib.load(PicklePath)
    print("model loaded")
    #FilePath1 = "C:/Users/z001133/Desktop/work files/customer quality/SAFETY/data/jan1st.csv"
    dfclean = clean_data(dfinput['Body'])
    filenm1 = "email_classification_ml_result"
    predict(model1,filenm1,dfclean)
    print("before return")
    return 'OK'


if __name__ == '__main__':
    app.run(debug=True, use_reloader=False)

出现以下错误。

 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [13/Aug/2019 09:43:44] "GET / HTTP/1.1" 500 -
Traceback (most recent call last):
  File "C:\Users\z026355\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 2309, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Users\z026355\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 2295, in wsgi_app
    response = self.handle_exception(e)
  File "C:\Users\z026355\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 1741, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\z026355\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\_compat.py", line 35, in reraise
    raise value
  File "C:\Users\z026355\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\z026355\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\z026355\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\z026355\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\_compat.py", line 35, in reraise
    raise value
  File "C:\Users\z026355\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\z026355\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "<ipython-input-77-0c3a1ef05475>", line 18, in predict_invoice

  File "C:\Users\z026355\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\parsers.py", line 678, in parser_f
    return _read(filepath_or_buffer, kwds)
  File "C:\Users\z026355\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\parsers.py", line 424, in _read
    filepath_or_buffer, encoding, compression)
  File "C:\Users\z026355\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\common.py", line 218, in get_filepath_or_buffer
    raise ValueError(msg.format(_type=type(filepath_or_buffer)))
ValueError: Invalid file path or buffer object type: <class 'NoneType'>
127.0.0.1 - - [13/Aug/2019 09:43:44] "GET /?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
127.0.0.1 - - [13/Aug/2019 09:43:44] "GET /?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
127.0.0.1 - - [13/Aug/2019 09:43:44] "GET /?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
127.0.0.1 - - [13/Aug/2019 09:43:45] "GET /?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
127.0.0.1 - - [13/Aug/2019 09:43:45] "GET /?__debugger__=yes&cmd=resource&f=ubuntu.ttf HTTP/1.1" 200 -
entry in to the job
127.0.0.1 - - [13/Aug/2019 09:43:45] "GET /?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -

它正在打印“ Entry to job”,但api无法正常工作。 以下是即时通讯进入API的错误。

builtins.ValueError
ValueError: Invalid file path or buffer object type: <class 'NoneType'>

读取csv文件是否存在问题,或者我的代码处理方式有问题吗?请提出建议。

1 个答案:

答案 0 :(得分:0)

您需要使用csv阅读器来读取csv文件 尝试这样

from flask import Flask, make_response, request
import io
import csv

app = Flask(__name__)

def transform(text_file_contents):
    return text_file_contents.replace("=", ",")


@app.route('/')
def form():
    return """
        <html>
            <body>
                <h1>Transform a file demo</h1>

                <form action="/transform" method="post" enctype="multipart/form-data">
                    <input type="file" name="data_file" />
                    <input type="submit" />
                </form>
            </body>
        </html>
    """

@app.route('/transform', methods=["POST"])
def transform_view():
    f = request.files['data_file']
    if not f:
        return "No file"

    stream = io.StringIO(f.stream.read().decode("UTF8"), newline=None)
    csv_input = csv.reader(stream)
    #print("file contents: ", file_contents)
    #print(type(file_contents))
    print(csv_input)
    for row in csv_input:
        print(row)
    return 'OK'

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5001, debug=True)

现在检查