May 26

Running a HTTP Server

Python has a built in server. It's a simple server server and shouldn't be used in a production environment, but it's great for testing, and for small tasks on an internal network. To run the server folllow these instructions.

  1. open a command prompt
  2. navigate to the directory with your website
  3. run the command python -m SimpleHTTPServer 80
  4. or in Python 3 run python -m http.server 80

That's it. If you go to your ip address in a web browser you should be able to see your website.

How it works

The -m switch tells python to look for a module with the specified name and run it. SimpleHTTPServer is a built in module that when run directly, instead of being imported will start up a server. It is also possible to run the server from within a python file, but at that point you may want to use BaseHTTPServer instead of SimpleHTTPServer. The 80 at the end of the command is the port to run on. Port 80 is the port used for websites.

June 1

Modifying Exceptions

Python exceptions can be customized in a few ways
At any time you can get a traceback of the stack by doing sys.exc_info[2]
you can then use that traceback later on in an exception by raising the exception like so
raise Exception, "My exception message", previously_saved_traceback
This can be useful if the traceback originated in a different thread and you want to preserve the traceback, or if you don't want to include some cleanup or exception handling code as part of the traceback, however, you must be very careful to preserve the origin of the exception when you mess with the traceback.
When you catch an error you can change the message displayed like so

except Exception as exc:
   raise exc, str(exc) + "additional exception info"

June 8

Protecting Objects

If you want to keep people from messing with your objects delete the __setitem__ function

del DataSet.__dict__["__setitem__"]

June 13

Useful 3rd party Python Libraries

Awesom External Libraries
1 Requests
2 Karrigell
3 Lxml
4 Blender API

June 16


dict(d, **d2) #combines two dictionaries together
d.setdefault('lists',[]).append(d2) #inbeds a list of dictionaries in a dictionary

July 21

Add a function to a object

def add(self, func, obj):
    '''add function func to the object obj'''
    assert func.__name__ not in obj.__dict__, 'function already added'
    setattr(obj, func.__name__, func)

August 29

Using parenthesis

use parenthesis instead of using backslashes at the end of lines when wrapping code onto multiple line

def illogical_logic():
    if (
            True or False
            and True or True
            and False or True
            and False or False
        return True

def logical_logic(sub):
    ret = (
              sub in
              'this is a '
              'very very very'
              'very very long'
    return ret

August 30

Love of Python

    >>> import this
    >>> love = this
    >>> this is love
    >>> love is True
    >>> love is False
    >>> love is not True or False
    >>> love is not True or False; love is love

September 19

When to use exceptions, asserts, and logical error handling statements

Returning False

Don't return False when something goes wrong. Return False when indicating state for example an in_good_state() or a logged_in() function should return True or False.

Using Asserts

Use assert statements for your internal logic that you don't expect the user of your API to have to handle. These are only there as a warning to alert you as soon as possible if the code is misbehaving.

Raising Exceptions

For any other circumstances use an exception


import time
import requests

class WebSiteAPI():
    def __init__(self):
        self.sessions = {}

    def login(self, user, passwd):
        timeout = 10

        if user not in self.sessions:

Using an assert

 #here we are testing internal logic that we don't expect to ever need to be handled
 #so we use an assert statement
 assert user in self.sessions
        #log in the user, '',
                  params={'username': user, 'password': passwd})

        #make sure the login was successful
        for i in range(timeout):
            if self.logged_in():

Raising an exception

     #it is likely the user of our API would want to take action
     #if we timeout so we use an exception here
     raise TimeOutError('failed to login %s with the password %s' % (user, passwd))

Returning state

    def logged_in(self, user):
        '''checks if the indicated user is logged in'''
        #returning false should be done with functions that indicate state,
        #not because something went wrong inside a function
        if user not in self.sessions:
            return False
        if user in, ''):
            return True
            return False
    def add_user(user):
        '''creates a new session for the user passed into this function
        the session will persist cookies across different api calls'''
        self.sessions[user] = request.session()

    def call(user, url, *args, **kwargs):
        '''performs an api call
        for each user who calls this function the cookies for that user
        are remembered, kept, and reused the next time that user calls this function'''
        return self.sessions[user].get(url, args, kwargs).content

class TimeOutError(Exception):

using the above WebSiteAPI class

api = WebSiteAPI()
my_user = 'mrme'
api.login(my_user, 'awesome_password'), '')

Further reading

Exception handling best practices

Using assert statements

purpose of an assert statement

HTML Comment Box is loading comments...