使用python将json和文件发送到flask [英] using python to send json and files to flask

查看:592
本文介绍了使用python将json和文件发送到flask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到这个问题,我试图在一个函数中向烧瓶API发送/接收一些文件和JSON.

I have this issue where I am trying to send/receive to a flask API some file and JSON in a single function.

在我的客户(发送者)上,我有:

On my client ( sender ) I have :

#my json to be sent 
datas = {'var1' : 'var1','var2'  : 'var2',}
#my file to be sent 
local_file_to_send = 'user_picture.jpg'
url = "http://10.100.2.6:80/customerupdate"
headers = {'Content-type': 'multipart/form-data'}
files = {'document': open(local_file_to_send, 'rb')}
r = requests.post(url, files=files, data=datas, headers=headers)

在我的Flask服务器上,我有:

On my Flask server I have :

class OPERATIONS(Resource):
        @app.route('/',methods=['GET'])
        def hello_world():
            return 'Hello World!'

        @app.route('/customerupdate',methods=['GET','POST'])
        def customerupdate():
            event_data_2 = json.loads(request.get_data().decode('utf-8'))
            print event_data_2

我有此错误消息,告诉我数据实际上不是json格式也不是utf8格式.如果我在不尝试解码的情况下打印"get_data"的内容,则会显示一些二进制字符.

I have this error message telling me that the data is actually not a json format nor a utf8 format. If I print the content of the "get_data" without trying to decode it shows some binary characters..

在我的客户端上读取json并在本地写入文件的语法是什么?

What would be the syntax on my client to read the json and write the file locally ?

推荐答案

我建议同时发送JSON和文件作为多部分表单的一部分.在这种情况下,您可以从服务器上的request.files中读取它们. (一个警告:我使用Python 3,请求2.18.4和Flask 0.12.2测试了所有示例,您可能需要更改代码以匹配您的环境.)

I would recommend sending both the JSON and the file as parts of the multipart form. In that case you would read them from request.files on the server. (One caveat: I tested all my examples with Python 3, requests 2.18.4, and Flask 0.12.2 -- you might need to change the code around to match your environment).

来自 https://stackoverflow.com/a/35940980/2415176 (以及 http://docs.python-requests.org /en/latest/user/advanced/#post-multiple-multipart-encoded-files ),则无需指定标头或其他任何内容.您可以让requests为您处理它:

From https://stackoverflow.com/a/35940980/2415176 (and the Flask docs at http://docs.python-requests.org/en/latest/user/advanced/#post-multiple-multipart-encoded-files), you don't need to specify headers or anything. You can just let requests handle it for you:

import json
import requests

# Ton to be sent
datas = {'var1' : 'var1','var2'  : 'var2',}

#my file to be sent
local_file_to_send = 'tmpfile.txt'
with open(local_file_to_send, 'w') as f:
    f.write('I am a file\n')

url = "http://127.0.0.1:3000/customerupdate"

files = [
    ('document', (local_file_to_send, open(local_file_to_send, 'rb'), 'application/octet')),
    ('datas', ('datas', json.dumps(datas), 'application/json')),
]

r = requests.post(url, files=files)
print(str(r.content, 'utf-8'))

然后在服务器上可以从request.files读取(请参阅 http://flask.pocoo.org/docs/0.12/api/#flask.Request.files ,但请注意,request.file的工作方式有所不同,请参见

Then on the server you can read from request.files (see http://flask.pocoo.org/docs/0.12/api/#flask.Request.files but note that request.files used to work a little differently, see https://stackoverflow.com/a/11817318/2415176):

import json                                                     

from flask import Flask, request                                

app = Flask(__name__)                                           

@app.route('/',methods=['GET'])                                 
def hello_world():                                              
    return 'Hello World!'                                       

@app.route('/customerupdate',methods=['GET','POST'])            
def customerupdate():                                           
    posted_file = str(request.files['document'].read(), 'utf-8')
    posted_data = json.load(request.files['datas'])             
    print(posted_file)                                          
    print(posted_data)                                          
    return '{}\n{}\n'.format(posted_file, posted_data)          

这篇关于使用python将json和文件发送到flask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆