[Python] Creating Custom Cookies for HTTP Requests

One way of adding a custom cookie is to directly specify the "cookie" field in your request header. For example:

 
request.add_header("Cookie", "something=test+1+2+3; source=script")

Here, two cookies are set in the request ("something" and "source"). Notice that the cookies are fully specified in the string, instead of using urllib.urlencode. Another way of adding cookies is to create Cookie objects and add them to your CookieJar. Before sending your request, add the cookies by using add_cookie_header.

An example for Python 2.7:

from cookielib import Cookie
from cookielib import CookieJar
from urllib2 import Request
import urllib2
import urllib

'''
    Makes a cookie with provided name and value.
'''
def makeCookie(name, value):
    return Cookie(
        version=0, 
        name=name, 
        value=value,
        port=None, 
        port_specified=False,
        domain="kahdev.bur.st", 
        domain_specified=True, 
        domain_initial_dot=False,
        path="/", 
        path_specified=True,
        secure=False,
        expires=None,
        discard=False,
        comment=None,
        comment_url=None,
        rest=None
    )

# Create a cookie jar to store our custom cookies.
jar = CookieJar()

# Generate a request to make use of these cookies.
request = Request(url="http://kahdev.bur.st/python/cookies/receiver.php")

# Use makeCookie to generate a cookie and add it to the cookie jar.
jar.set_cookie(makeCookie("name", "kahdev"))
jar.set_cookie(makeCookie("where", "here"))

# Add the cookies from the jar to the request.
jar.add_cookie_header(request)

# Now, let us try open and read.
opener = urllib2.build_opener()
f = opener.open(request)

print "Server responds with: "
print f.read()

The above source can also be downloaded from my Github repository. If you run it, you should see the following output:

# python cookies.py
Server responds with: 
Cookies:
    [where] = [here] 
    [name] = [kahdev] 

Note that the 2.7 documentation for Cookie indicates that you should not need to be doing this often:

It is not expected that users of cookielib construct their own Cookie instances. Instead, if necessary, call make_cookies() on a CookieJar instance.

However, the method make_cookies is for extracting cookies from HTTP responses.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: