Python
  Home arrow Python arrow Page 3 - Python on the Web
Dev Shed Forums 
Administration  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Download TestComplete 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PYTHON

Python on the Web
By: Mark Lee Smith
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 27
    2004-05-18

    Table of Contents:
  • Python on the Web
  • Creating a Warning
  • Cookies
  • Sending Email
  • A Last Example
  • Inside uploads()...

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
     
    ADVERTISEMENT

    Route your faxes to your email inbox. Private, secure fax numbers available from CallWave. Choose your fax number.

    Python on the Web - Cookies
    (Page 3 of 6 )

    Next up we'll use Python's  'Cookie' module to do a little baking! (Ironically I suck at making real cookies.)

    >>> import Cookie
    >>> cookie = Cookie.SimpleCookie()
    >>> cookie['number1'] = 'some values'
    >>> cookie['number2'] = 'some values'
    >>> cookie['number3'] = 'some values'
    >>> cookie['number3']['expires'] = 3600
    >>> print cookie
    Set-Cookie: number1="some values";
    Set-Cookie: number2="some values";
    Set-Cookie: number3="some values"; expires=Fri, 30-Jan-2004 12:03:20 GMT;

    Ok, you have to agree, setting cookies couldn't be much simpler, and the 'Cookie' module wraps it up nicely. The difficulty comes when you want to retrieve your values... ok maybe I'm exaggerating a little here.

    #!/usr/bin/env python

    import os

    def monster():
     if 'HTTP_COOKIE' in os.environ:
      cookies = os.environ['HTTP_COOKIE']
      cookies = cookies.split('; ')
      handler = {}
      
      for cookie in cookies:
       cookie = cookie.split('=')
       handler[cookie[0]] = cookie[1]
       
      return handler
      
    if __name__ == '__main__':
     
     import Cookie
     
     cookie = Cookie.SimpleCookie()
     cookie['monster'] = 'cookievalue'
     print cookie
     
     print 'Content-Type: text/htmln'
     
     print 'Hit refresh to see the cookie!!!<br />'
     print 'Hewwo, im the cookie', monster()

    This is all about parsing the 'HTTP_COOKIE' header and inserting the cookie values into a dictionary.

    We start by importing the 'os' module into our program and defining the monster() function -- this checks if the 'cookies' string exists or not. If it does then we split it, leaving us with a list of 'key=value' strings. After that all we have left to do is loop over the list and split the values again, placing them into the dictionary.

    Ok finally let's do something a little useful with our cookies... and in keeping with our final example, we're going to create a counter function, which allows you to set limits on different processes. Observe and enjoy.

    #!/usr/bin/env python

    import Cookie, os

    def limits(count):
     if 'HTTP_COOKIE' in os.environ:
      cookies = os.environ['HTTP_COOKIE']
      cookies = cookies.split('; ')
      handler = {}
      for cookie in cookies:
       cookie = cookie.split('=')
       handler[cookie[0]] = cookie[1]

      if 'count' in handler:
       number = int(handler['count'])
       if number < count:
        cookie = Cookie.SimpleCookie()
        cookie['count'] = number + 1
        cookie['count']['expires'] = 86400
        print cookie
        return True
     else:
      print Cookie.SimpleCookie('count=1')
      return True

    if __name__ == '__main__':

    if limits(5):
     print 'user was under their limit, do this...'
    else:
     print 'user was over their limit, do nothing!'

    The start of this is exactly the same as in our monster() function except that if there are no cookies set, then we create one and set its value to one. If there are any cookies to unpack, then we check for 'count' in the handler dictionary and type-cast its value to a 'number' using int()... 'number' is then compared to the 'count' variable to check if the user is under or over their limit. Provided they're under their limit, then we update the cookie and set the expiry date to 24 hours before returning True; this is done so we can use if-else blocks to control the users access.

    More Python Articles
    More By Mark Lee Smith


     

       

    PYTHON ARTICLES

    - SSH with Twisted
    - Mobile Programming in Python using PyS60: UI...
    - Python: Count on It
    - Python Strings: Spinning Yarns
    - Python: More Fun with Strings
    - Python: Stringing You Along
    - Python Operators
    - Bluetooth Programming in Python: Network Pro...
    - Python Sets
    - Python Conditionals, Lists, Dictionaries, an...
    - Python: Input and Variables
    - Introduction to Python Programming
    - Mobile Programming in Python using PyS60: Ge...
    - Bluetooth Programming using Python
    - Finishing the PyMailGUI Client: User Help To...

     
    Accelerating Trading Partner Performance
     
    Competing on Analytics
     
    Cost Effective Scaling with Virtualization and Coyote Point Systems
     
    Five Checkpoints to Implementing IP Telephony
     
    Hosted Email Security: Staying Ahead of New Threats
     




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 2 hosted by Hostway