0

I got stuck when I try to send a post request with a large body dictionary. Here is the code.

body = {"session":{"user":{"user_id":"user1"}, \
"equipment":{"equipment_id_alternate":{"alternate_equipment_id_type":"sms_address", \
"alternate_equipment_id":"equipmentid1"}, \
"extensions":[{"extension_type":"string","name":"device_type","value":"PC_Apple"}, \
{"extension_type":"string","name":"device_id", \
"value":"equipmentid1"}]}, \
"content":{"content_type":"http_broadcast_channel", \
"uri":"http://xyz/abc.m3u8", \
"extensions":[{"extension_type":"integer","name":"bandwidth","value":0}, \
{"extension_type":"string","name":"stream_quality","value":"HD"}, \
{"extension_type":"string","name":"session_type","value":"Live_Linear_Companion"}]}}, \
"sa_version":"sa_http_v_1_0_1","request_type":"setup_request", \
"authentication":{"auth_algorithm":"sa_hmac_token_v_1_0_1","auth_message_algorithm":"sa_http_auth_message_v_1_0_1", \
"auth_token_start":"2016-11-23T19:49:56Z","auth_token_expiry":"2016-11-30T19:49:56Z", \
"auth_token":"abdcwgegegegege"}}

header19 = {some keys and values}
api19 = requests.post(url19, json=body, headers=header19)

I want to pass the request body the same order as it is declared, how can i achieve it?

I see a lot of similar questions and replies saying that you can use collections.orderDict(); However I do not know how I can use it properly without declaring each key and value pair using collections.orderDict().

Thanks.

Feng
  • 41
  • 7

2 Answers2

0

A regular dict does not track the insertion order, and iterating over it produces the values in an arbitrary order. In an OrderedDict, by contrast, the order the items are inserted is remembered and used when creating an iterator.

import collections


print 'Regular dictionary:'
d = {}
d['a'] = 'A'
d['b'] = 'B'
d['c'] = 'C'
d['d'] = 'D'
d['e'] = 'E'

for k, v in d.items():
   print k, v

print '\nOrderedDict:'
d = collections.OrderedDict()
d['a'] = 'A'
d['b'] = 'B'
d['c'] = 'C'
d['d'] = 'D'
d['e'] = 'E'


for k, v in d.items():

 print k, v

The output will be :

Regular dictionary:
a A
c C
b B
e E
d D

OrderedDict:

a A
b B
c C
d D
e E
Amin Etesamian
  • 3,363
  • 5
  • 27
  • 50
-1

You may just try:

from collections import OrderedDict

ordered_body = OrderedDict(body)

The order of keys in ordered_body should remain the same as specified. I think this post explains OrderedDict very clearly.

Community
  • 1
  • 1
mikeqfu
  • 329
  • 2
  • 10
  • @AminEtesamian, did you try it? if i try to print ordered_body, i still got the result in a random order. – Feng Nov 28 '16 at 20:35
  • check the accepted answer here: http://stackoverflow.com/questions/15711755/converting-dict-to-ordereddict – Amin Etesamian Nov 28 '16 at 21:05