how to send bson.M data in python

Viewed 41

i have an Api function in Golang that receive a json data and good working with postman but i want te call api with python3 but error in parse body this is my golang code:

var approve bson.M
err := c.BodyParser(&approve)

and this is my data in patch api :

{
    "result" : true
}

and this is my python script:

  jsondata = bson.BSON.encode({'result': True})
  options = CodecOptions(document_class=collections.OrderedDict)
  #decoded_doc = bson.BSON(jsondata).decode(codec_options=options)
  decoded_doc = bson.decode(jsondata, codec_options=options)
  r = requests.patch(approvurl,data=decoded_doc,headers={'Content-Type':'application/json','Authorization':API_KEY,'Imei':'1234567890','phone':'123456789','email':'test@gmail.com'} )

and my backend in my golang throw this exeption :

expected { character for map value

and i compare json object in wirshark : this is for postman: enter image description here and this is for my python script enter image description here

please help me to solve my problem in python script

2 Answers

I think what's happening is that you're passing a Python dict using requests.patch's data parameter, which expects a string. It looks like you want to send JSON, so you should use the json parameter (which adds the application/json Content-Type automatically).

Also, it looks like you're encoding a Python dict to BSON format, only to re-decode it back to a Python dict again. Unless I'm missing something, you shouldn't need to do that.

So your Python script can be changed to a single call to requests.patch:

r = requests.patch(
    approvurl,
    json={'result': True},
    headers={'Authorization': API_KEY, ...},
)

my problem solved by added a new function that check agent :

userAgent := string(c.Context().UserAgent())
        //print("userAgent=", userAgent)
        if strings.HasPrefix(userAgent, "python-requests") {
            eq := c.Body() //("result")
            if string(eq) == "result=True" {
                print("jsonBody is", string(eq))
                id, _ := primitive.ObjectIDFromHex(c.Params("id"))
                print("Approving started=", true)

tnx`

Related