首页 > 解决方案 > 使用 cURL 将 CSV 文件读取到 Flask Restful API

问题描述

我正在尝试开发一种服务,有人可以将 csv 文件发送到我转储到数据库中的 REST API。我的cURL请求是读取数据但flask_restful无法处理。你能告诉我我做错了什么,我该如何解决?

[编辑如下]

我在阅读request.files可让您POST从表单请求中读取文件的文档后发现。我还找到了一种将 csv 文件cURL作为表单发送的方法。

class ForBetaAndUpload(Resource):
        def post(self, kind='quotes'):

#        parser = reqparse.RequestParser()
        file = request.files['file']
        print(file)
#        kind = parser.add_argument('kind').parse_args()['kind']

        if kind:
            if file and file[-3:]=='csv':
                if kind == 'quotes':
                    try:
                        df = pd.read_csv(file)
                        df.to_sql('QUOTES', helper.conx, index=False, if_exists='append')
                        return jsonify({'message':'%s rows inserted in the databasee table successfully' %(df.shape[0])})
                    except Exception as e:
                        return jsonify({'exception': e})

                if kind == 'trace':
                    try:
                        df = pd.read_csv(todos)
                        df.iloc[:10].to_sql('TRACE', helper.conx, index=False, if_exists='append')
                        return jsonify({'message':'%s rows inserted in the databasee table successfully' %(df.shape[0])})
                    except Exception as e:
                        return jsonify({'message': e})
            else:
                return jsonify({'message': 'Please provide a csv file'})
        else:
            return jsonify({'message':'Please provide the file for to update relevant table in the databse'})


    api.add_resource(ForBetaAndUpload, '/upload', endpoint='upload')

    if __name__ == "__main__":
        app.run(debug=True)

卷曲请求:

curl "https://localhost:5000/upload" -X POST -H 'Content-Type: txt/csv' -d trace.csv --insecure

我收到以下消息:

curl:(35)错误:140770FC:SSL例程:SSL23_GET_SERVER_HELLO:未知协议

API 错误信息

代码 400,消息错误 HTTP/0.9 请求类型('\x16\x03\x01\x02\x00\x01\x00\x01ü\x03\x03\x08Ú:ü^¢Ù~ö7W\x9fDyy\x16j\x7fõ>½\ x82\x90uÎ&3ÿZ\x08êE\x00\x00')

如何将 csv 文件发送到flask restful_api. 我正在做的事情是正确的还是有其他方法可以做到?

标签: pythonpython-3.xcurlflask

解决方案


我从中读取 csv 的解决方案Flask是:

在烧瓶中:

f = request.files['file']

f将是文件的处理程序,然后您可以使用csv_reader.

并发送文件:

curl -s "http://localhost:5000" \
    -F file=@./myfile.csv \
    -X POST \
    -H 'enctype:multipart/form-data ; Content-Type:multipart/form-data'

这应该有效。让我知道。


推荐阅读