Requests not being sent with payload in Python - Moodle

0

Good afternoon,

I have a problem that is already giving a certain headache. The blessed payload of the request is not being sent to the webservice, only to the url.

My code looks like this:

class Curso:
'''Resgata todas as disciplinas modelo'''
def getDisModelo(self):

    config = Config()

    serverUrlDisc = config.dominio + "/webservice/rest/server.php" + "?wstoken=" + \
                    config.alocaGrupoToken + "&wsfunction=" + "core_course_get_courses_by_field" \
                    + "&moodlewsrestformat=" + config.formatoRest

    params = json.dumps({'field': 'id', 'value': '31198'})

    s = requests.session()
    s.verify=False

    response = s.post(serverUrlDisc, data=params)
    disciplinasAva = response.json()
    response.status_code

    return disciplinasAva

What happens, I can send the request but it does not recognize the content of params at all, that is, it is only sent to the url and the parameters are not. Does anyone know why this is happening? My Python version is 3.7

    
asked by anonymous 27.10.2018 / 22:18

1 answer

0

If you use data= to send its parameters, along with a string, in this case, the JSON encoded, the content is sent "raw" in the body of the HTTP request. If the server is not expecting a JSON response, which may in this case with the incorrect headers, it will not work at all.

If the server accepts JSON, instead of calling a json.dumps with its data, pass it directly to the json= parameter in the post method call. This will not only encode the data, but will put the correct headers:

...
params = {'field': 'id', 'value': '31198'}

s = requests.session()
s.verify=False

response = s.post(serverUrlDisc, json=params)
...

Now, if the application on the server is not expecting JSON, and yes, the data encoded as form-encoded, in this case, you pass the data in the form of a direct dictionary in the data= parameter, without serializing the JSON before:

...
params = {'field': 'id', 'value': '31198'}

s = requests.session()
s.verify=False

response = s.post(serverUrlDisc, data=params)
...
    
29.10.2018 / 14:29