Skip to content

Post Method

Iury O. G. Figueiredo edited this page Dec 5, 2020 · 2 revisions

It is quite simple to perform post requests with Websnake, the example below shows an example.

from websnake import Post, ResponseHandle, core, die, FormData, TokenAuth

def on_done(con, response):
    print('Headers:', response.headers)
    print('Code:', response.code)
    print('Version:', response.version)
    print('Reason:', response.reason) 
    print('Data:', response.fd.read())
    die()

if __name__ == '__main__':
    url = 'http://httpbin.org/post'
    data = {'somekey': 'somevalue'}

    request = Post(url, payload=FormData(data))

    request.add_map(ResponseHandle.DONE, on_done)
    core.gear.mainloop()

The class FormData is used to send the request payload encoded as multipart form data. It automatically sets the request header content-type accordingly.

    request = Post(url, payload=FormData(data))

The line below just binds on_done to ResponseHandle.DONE that will be fired when the request is finished and a response was sent back. The Post request also handles reddirects automatirely.

    request.add_map(ResponseHandle.DONE, on_done)

The Post class also accepts url parameters /queries.

request = Post(url, args={'key':'value}, ...)