简体   繁体   English

发送带有数据和 JSON 参数的 post 请求

[英]Sending post request with both data and JSON parameters

I am trying to send a post request with both data and JSON fields, such as:我正在尝试发送包含数据和 JSON 字段的发布请求,例如:

my_df = pd.read_csv('test.csv')
pickled = pickle.dumps(my_df)
pickled_b64 = base64.b64encode(pickled)

my_name = "my_csv_name.csv"

r = requests.post('http://localhost:5003/rcvdf', data = pickled_b64, json= {"name": my_name})

Notice that pickled_b64 is of type 'bytes'.请注意,pickled_b64 的类型为“字节”。

But on the other end, I get only the data and no JSON at all:但在另一端,我只得到数据,根本没有 JSON:

@api.route('/rcvdf', methods=['POST'])
def test_1():
    data_pickeled_b64_string = request.data
    json_data = request.json #This is None

Is it even possible to pass two variables in such a way?甚至可以以这种方式传递两个变量吗?

--edit - 编辑

Solution解决方案

thanks to the comments I tried different approach - and passed the variable by headers:感谢评论我尝试了不同的方法 - 并通过标题传递变量:

Sending Side:发送方:

my_name = "my_csv.csv"

r = requests.post('http://localhost:5003/rcvdf', data=pickled_b64, headers={"name": my_name})

Receiving Side:接收方:

@app.route('/rcvdf', methods=['POST'])
def rcvdf():
    data_pickeled_b64_string = request.data
    name = request.headers['name']

requests.post(url, json=payload) is just a shortcut for requests.post(url, data=json.dumps(payload)) requests.post(url, json=payload)只是requests.post(url, data=json.dumps(payload))的快捷方式

Note, the json parameter is ignored if either data or files is passed.请注意,如果传递数据或文件,则忽略 json 参数。

docs 文档

So, no, it is not possible to pass both data and json parameters.所以,不,不可能同时传递datajson参数。

An Alternative method:另一种方法:

Since base64 encoding has ASCI format you can convert it to simple string object.由于 base64 编码具有 ASCI 格式,您可以将其转换为简单的字符串 object。

Then you can do it by embedding your pickled_b64 in your json data:然后你可以通过将你的 pickled_b64 嵌入到你的 json 数据中来做到这一点:

import base64, request


pickled_b64 = str(base64.b64encode("hello world".encode()), encoding="utf-8")
json_data = {"Pickled_B64": pickled_b64, "Name": "my_csv_name.csv"}
send_request = requests.post('http://localhost:5003/rcvdf', json=json_data)
print(send_request.json())

and on your backend side:在你的后端:

from flask import make_response, jsonify

@api.route('/rcvdf', methods=['POST'])
def test_1():
    pickled_b64 = request.json.get('Pickled_B64', None)
    name = request.json.get('Name', None)
    reserve_dict = {"Status": "Got it", "name": name, "pickled_b64": pickled_b64}
    reserve_response = make_response(jsonify(reserve_dict), 200)
    return reserve_response

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM