Requests not being sent with payload in Python - Moodle

Asked

Viewed 180 times

0

Good afternoon,

I’m having a problem that’s already giving me a headache. The blessed request payload is not being sent to the webservice, only the url.

My code is 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 in any way, IE, it is only sent the url and the parameters do not. Does anyone know why this is happening? My version of Python is 3.7

1 answer

0

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

If the server accepts JSON, instead of calling one json.dumps with your data, pass them directly in the parameter json= 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, but rather the data encoded as form-encoded, in this case, you pass the data in the direct dictionary form in the parameter data=, without serializing JSON before:

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

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

response = s.post(serverUrlDisc, data=params)
...
  • I have tried these two methods previously, but without success. I believe it is the Moodle server that is blocking the json payload. I need to find the location to change this setting.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.