Contents

Post Request in Python

Thanks to Nicolas Patrois who pointed out that Python may bewilder with its http libraries!

Since about 50% of CodeAbbey people use Python, here are short snippets of code to help with solving interactive problems.

Python has at least 2 versions of http library. The second seems to make things simpler. Let us consider the Say-100 problem:

import httplib2

data = "token: abcdefghijklmnopqrstuvwx\n"

http = httplib2.Http()
response, content = http.request("http://codeabbey-games.atwebpages.com/say-100.php", "POST", data)

#print 'Status: ' + response['status']
print content

You see, we only need to create an object of class Http and then call simple request method on it, passing three parameters - url, the type of method (post) and the data themselves. Variable content in this case will hold the data sent to you by server as an answer. Additionally information from variable response could be used to debug if something goes wrong. For example the commented line prints HTTP status given by the server - it should be 200 if all is OK, but it may be 404 if the url is wrong and no script is found here or 400 if something is bad with request it all. Another well-known error 500 is the worst of all - it means there was some server failure. Hope you will not see them ofthen.

Older library

There is another standard library httplib. It seems to use HTTP protocol of version 1.0 and so it splits the url accordingly. Here is the code sample:

import httplib

data = "token: abcdefghijklmnopqrstuvwx"

conn = httplib.HTTPConnection("http://codeabbey-games.atwebpages.com")
conn.request("POST", "/say-100.php", data)

response = conn.getresponse()
#print str(response.status) + " " + response.reason
print response.read()

It does just the same as the code above, but is longer and more awkward. For example, as Nicolas Patrois have found, it returns status 400 if you miss the leading slash before say-100.php.


Url-encoded data

You also can send your request data not as plain text, but as url-encoded form data, if it is more convenient to you. Please take care of specifying appropriate content type. Here is an example:

import httplib2
import urllib

data = {'token': 'abcdefghijklmnopqrstuvwx'}

http = httplib2.Http()
response, content = http.request("http://codeabbey-games.atwebpages.com/say-100.php", "POST",
        urllib.urlencode(data), {'Content-Type': 'application/x-www-form-urlencoded'})

print content