如何通过Flask请求文件属性获取Python字典

时间:2018-11-14 21:32:38

标签: python flask request python-requests

运行server.py

from flask import Flask, request, Response

app = Flask(__name__)

@app.route('/test', methods=['GET','POST'])
def route():   
    print('got files: %s' % request.files)
    return Response()

if __name__ == '__main__':
    app.run('0.0.0.0', 5000)

使用client.py发送请求:

import json, requests  

dictionary_1 = {"file": {"url": "https://bootstrap.pypa.io/get-pip.py"}}  

files = [('dictionary_1', ('get-pip.py', json.dumps(dictionary_1), 'application/json'))]

response = requests.post('http://127.0.0.1:5000/test', files=files)

服务器记录它收到请求:

got files: ImmutableMultiDict([('dictionary_1', <FileStorage: u'get-pip.py' ('application/json')>)]) 

显然,dictionary_1被作为FileStorage对象接收。 如何将收到的FileStorage转换成Python字典?

稍后编辑

可能重复的帖子并未阐明如何发送和解压缩通过requests(files=list())发送的Python字典对象

2 个答案:

答案 0 :(得分:0)

之所以发生这种情况,是因为您要发布文件而不是数据。这应该起作用:

import flask

app = flask.Flask(__name__)

@app.route('/test', methods=['GET','POST'])
def route():   
    print('got data: {}'.format(flask.request.json))
    return Response()

if __name__ == '__main__':
    app.run('0.0.0.0', 5000)

然后通过以下方式将数据发送到您的应用程序

import requests  

dictionary_1 = {"file": {"url": "https://bootstrap.pypa.io/get-pip.py"}}  

response = requests.post('http://127.0.0.1:5000/test', json=dictionary_1)

在您的示例中,除非我有误解,否则无需发布文件

答案 1 :(得分:0)

解决方案1:

from flask import Flask, request, Response
import StringIO, json 

app = Flask(__name__)

@app.route('/test', methods=['GET','POST'])
def route():  
    print('got files: %s' % request.files)
    for key, file_storage in request.files.items():
        string_io = StringIO.StringIO()
        file_storage.save(string_io)
        data = json.loads(string_io.getvalue())
        print('data: %s type: %s' % (data, type(data)) ) 

    return Response()

if __name__ == '__main__':
    app.run('0.0.0.0', 5000)

解决方案2:

from flask import Flask, request, Response
import tempfile, json, os, time   

app = Flask(__name__)

@app.route('/test', methods=['GET','POST'])
def route():   
    print('got files: %s' % request.files)

    for key, _file in request.files.items():
        tmp_filepath = os.path.join(tempfile.mktemp(), str(time.time()))
        if not os.path.exists(os.path.dirname(tmp_filepath)):
            os.makedirs(os.path.dirname(tmp_filepath))

        _file.save(tmp_filepath)

        with open(tmp_filepath) as f:
            json_data = json.loads(f.read())

        print type(json_data), json_data 

    return Response(json_data)

if __name__ == '__main__':
    app.run('0.0.0.0', 5000)