How to Track Pizza Delivery

Posted by Prolific Programmer Sat, 10 May 2008 21:37:00 GMT

Someone has put up a Dominoes pizza order tracking script using their XML feed. Cool!

#!/usr/bin/env python


import xml.dom.minidom
import urllib, sys, datetime


class Dominos:


	def __init__(self, *args, **kw):
		self.__feed_url = "http://trkweb.dominos.com/orderstorage/GetTrackerData"

	def get_order_info(self, phone_number):
		xml_data = urllib.urlopen('%s?Phone=%s' % (self.__feed_url, phone_number))
		dom = xml.dom.minidom.parse(xml_data)
		orders_node = dom.getElementsByTagName('OrderStatuses')
		order = orders_node[0].getElementsByTagName('OrderStatus')
		
		if order.length > 0:
			description = order[0].getElementsByTagName('OrderDescription')[0].firstChild.data
			starttime = self.get_time(order[0].getElementsByTagName('StartTime')[0].firstChild)
			oventime = self.get_time(order[0].getElementsByTagName('OvenTime')[0].firstChild)
			racktime = self.get_time(order[0].getElementsByTagName('RackTime')[0].firstChild)
			routetime = self.get_time(order[0].getElementsByTagName('RouteTime')[0].firstChild)
			deliverytime = self.get_time(order[0].getElementsByTagName('DeliveryTime')[0].firstChild)
			return {'description':description, 'starttime':starttime, 'deliverytime':deliverytime, 
					'oventime':oventime, 'racktime':racktime, 'routetime':routetime}
		else:
			return False


	def get_time(self, time_node):
		if time_node:
			[date, time] = time_node.data.split("T")
			[hour, minute, second] = time.split(":")
			ampm = 'pm'
			if hour < 12:
				ampm = 'am'
			return '%s:%s%s' % (int(hour) % 12, minute, ampm)
		else:
			return None


if __name__ == "__main__":
	
	if len(sys.argv) != 2:
		print 'usage: %s ' % sys.argv[0]
		sys.exit(1)
	
	print """Dominos (R) pizza tracker."""	
	d = Dominos()
	order_info = d.get_order_info(sys.argv[1])
	
	if not order_info:
		print "No Orders Found for %s" % sys.argv[1]
	else:
		print order_info['description'] 
		if order_info['starttime']: print "Your pizza is being made! %s" % order_info['starttime']
		if order_info['oventime']: print "Your pizza is in the oven! %s" % order_info['oventime']
		if order_info['racktime']: print "Your pizza is done and awaiting delivery! %s" % order_info['racktime']
		if order_info['routetime']: print "Your pizza is on the way! %s" % order_info['routetime']
		if order_info['deliverytime']: print "Your pizza was delivered! %s" % order_info['deliverytime']	

How to Implement User Authentication

Posted by Prolific Programmer Wed, 09 Jan 2008 02:30:00 GMT

The code after the flip will write apache formatted password files and in an sqlite table.


class htpasswd(object):
    def __init__(self, user):
        self.user = user
        self.password = None
        self.sqlstatement = 'INSERT into Users (name, password) VALUES (?,?)'

    def __str__(self):
        import pysqlite2.dbapi2 as sqlite
        sql=sqlite.connect('user')
        cursor = sql.cursor()
        res=cursor.execute(self.sqlstatement, (self.user, self.password,))
        sql.commit()
        cursor.close()
        sql.close()
        return '%s:%s' % (self.user, self.password)

    def set_password(self, passwd):
        import crypt
        self.password = crypt.crypt(passwd, passwd[0:1])

if __name__ == '__main__':
    import sys
    outfile = open('httppass', mode='a')
    o=htpasswd(sys.argv[1])
    o.set_password(sys.argv[2])
    outfile.write(str(o)+'\n')
    outfile.close()

How to log Messages

Posted by Prolific Programmer Mon, 07 Jan 2008 14:47:00 GMT

The code after the flip solves a problem I encountered, namely the python logging module will not work with jython. This logging implementation may be used as follows:

import logging,Message
message = Message('foo')
message1 = Message('bad foo',999)
message2 = Message('critical foo', 1)
l=logging()
l1=logging(500)
l2 = logging(0)
print l.write(message)
print l.write(message1)
print l.write(message2)
print l1.write(message)
print l1.write(message1)
print l1.write(message2)
print l2.write(message)
print l2.write(message1)
print l2.write(message2)
The code purposely does not use named levels; I'm of the belief that the determination of what to log and what not to log should be at the developer's discretion, along with what the boundary is between what is displayed and what is not.

class logging(object):
    def __init__(self, level = 1000):
        self.level = level

    def write(self, logmsg):
        import time
        if logmsg.level <= self.level:
            timestamp = time.strftime("%Y%m%dT%H:%M:%S", time.gmtime())
            return ('%s: %s' % (timestamp, str(logmsg)))
        return ''
class Message(object):
    def __init__(self, msg, level = 1000):
        self.level = level
        self.message = msg

    def __str__(self):
        return self.message

How to Compute the nth Fibonacci Number

Posted by Prolific Programmer Thu, 13 Dec 2007 04:30:00 GMT

A fairly popular brainteaser that comes up repeatedly during my many job interviews. The answer is just one, leave comments if you have better ways. I'm aware that one can use Python generators to do this more efficiently, but I wanted to keep the code as clean as possible

def fib(n):
    '''Return the nth fibonacci number '''
    f=[1,1,2]
    for x in range(3,n):
        next = f[-1]+f[-2]
        f.append(next)
    return f[-1]

if __name__ == '__main__':
    import sys
    print fib(int(sys.argv[1]))