Building (HTML)calendars in python...

andre@vandervlies.xs4all.nl andre@vandervlies.xs4all.nl
Tue, 25 May 2004 21:39:26 -0000 (UTC)


------=_20040525213926_99928
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 8bit


I had a need for this thing. Perhaps it is of use....


--
               Andre van der Vlies <andre@vandervlies.xs4all.nl>
               Homepage: http://vandervlies.xs4all.nl/~andre
Key fingerprint =  39 7C 74 79 67 DB 93 06  23 DC B4 23 7B 58 CD 5A 6E FF
5C F8
--
    ()  ascii ribbon campaign - against html e-mail
    /\                        - against microsoft attachments
                              ^[^#]
--
------=_20040525213926_99928
Content-Type: text/x-python; name="GenerateCalender.py"
Content-Transfer-Encoding: 8bit
Content-Disposition: attachment; filename="GenerateCalender.py"

#!/usr/local/bin/python
#
#- Mon May 24 09:35:29 CEST 2004 -- Andre van der Vlies
#
#  Changed initialization. Made it (a bit) more adjustable....
#  
#- Mon May 20 21:35:29 CEST 2004 -- Andre van der Vlies
#
#  Added a year overview....
#
#-Wed Apr  7 11:10:38 METDST 2004 -- Andre van der Vlies
#
#  Origanal coding

import HTMLgen
import time
import os.path
import calendar

class Mon:
	"""
	Class to draw a calendar leaflet of month, takes a year and a month.
	If a directory (in the same path) exists with a name (eg. 20040511) in
	the range of this month is is made 'clickable' (a link).
	Additionally the Size, Lowlite-Color, Hilite-Color and OutLine (the edges) can be set.
	It should be quite adjustable...
	"""
	def __init__(self, Year, Month, **KeyWord):
		self.year = int(Year)
		self.month_number = int(Month)
		self.Size = "+2"
		self.Lo_Color = '#FF9933'
		self.Hi_Color = '#3399FF'
		self.OutLine_Color = '#C0C0C0'
		for item in KeyWord.keys():
			if self.__dict__.has_key(item):
				self.__dict__[item] = KeyWord[item]
			else:
				detail = "%s not a valid parameter of the %s class." % (item, self.__class__)
				raise KeyError, detail
		
		Time_Tuple = (self.year,self.month_number,1,0,0,0,0,0,0)
		self.month_name = time.strftime("%B", Time_Tuple)
		self.table = HTMLgen.Table( "%s %s" % (self.month_name, self.year),
                                    width="0",
                                    heading=['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
                                    heading_color=[self.OutLine_Color]*7,
                                    body_color=['', '', '', '', '', self.OutLine_Color, self.OutLine_Color],
                                    column1_align='left',
                                    cell_align='left',
                                    cell_line_breaks=1)

		MonthMatrix = []
		WeekRow = []

		for week in calendar.monthcalendar(self.year, self.month_number):
			for day in week:
				uri="%.4d%.2d%.2d" % (self.year, self.month_number, day)
				if day == 0:
					datum = "&nbsp;"
				else:
					datum = HTMLgen.Font("%s" % (day), color = self.Lo_Color, size = self.Size)
				if os.path.isdir(uri):
					datum = HTMLgen.Font("%s" % (day), color = self.Hi_Color, size = self.Size)
					cell = HTMLgen.Href(url=uri, text=datum)
				else:
					cell = datum
				WeekRow.append(cell)
			MonthMatrix.append(WeekRow)
			WeekRow = []

     
			self.table.body = MonthMatrix

	def __repr__(self):
		return self.table

	def __str__(self):
		result = "%s" % self.table
		return result

class Year:
	"""
	Draw 12 month's. It only need a year, month is set to zero....
	"""
	def __init__ (self, ThisYear, **KeyWord):
		self.year = int(ThisYear)
		self.Size = "0"
		self.Lo_Color = '#FF9933'
		self.Hi_Color = '#3399FF'
		self.OutLine_Color = '#C0C0C0'
		for item in KeyWord.keys():
			if self.__dict__.has_key(item):
				self.__dict__[item] = KeyWord[item]
			else:
				detail = "%s not a valid parameter of the %s class." % (item, self.__class__)
				raise KeyError, detail
		
		self.table = HTMLgen.Table( "%s" % (self.year),
                                    width="0",
                                    border="0",
                                    column1_align='center',
                                    cell_align='center',
                                    cell_line_breaks=1)

		Quarters = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
		YearMatrix = []
		MonthRow = []
		
		for quarter in Quarters:
			for month in quarter:
				cell = Mon(self.year, month, Size = self.Size,
				 			  Lo_Color = self.Lo_Color,
				 			  Hi_Color = self.Hi_Color,
				 			  OutLine_Color = self.OutLine_Color)
				MonthRow.append( cell )
			YearMatrix.append(MonthRow)
			MonthRow = []

		self.table.body = YearMatrix

	def __repr__(self):
		return self.table

	def __str__(self):
		result = "%s" % self.table
		return result
		
def PreviousMonth(year, month):
	"""
	Made for readabilty.....
	"""
	Y = int(year)
	M = int(month) - 1
	if M == 0:
		M = 12
		Y = Y - 1
	return (str(Y), str(M))


if __name__ == '__main__':
	"""
	Some testing stuff. Added some navigation to go back and forth.
	"""
	import string
	import Formtools
	import cgi
	import sys
	import os.path
	#import cgitb; cgitb.enable()

	Args = cgi.FieldStorage()

	try:
		year = int( Args["varYear"].value )
		month = int( Args["varMonth"].value )
	except:
		(year, month) = string.split( time.strftime("%Y %m", time.localtime()))

	if Args.has_key('ThisMonth'):
		(year, month) = string.split( time.strftime("%Y %m", time.localtime()))
	elif Args.has_key('FastRewind'):
		year = year-1
		month = "0"
	elif Args.has_key('Rewind'):
		if month == 0:
			month = 2
		else:
			month = month-1
			if month == 0:
				month = 12
				year = year-1
	elif Args.has_key('Forward'):
		if month == 0:
			month = 2
		else:
			month = month+1
			if month == 13:
				month = "1"
				year = year+1
	elif Args.has_key('FastForward'):
		year = year+1
		month = "0"
	
	doc = HTMLgen.SimpleDocument(title='Calendar')

	ResetButton = HTMLgen.Input(type="submit", name='ThisMonth', value="Reset")
	FastRewindButton = HTMLgen.Input(type="submit", name='FastRewind', value="<<")
	RewindButton = HTMLgen.Input(type="submit", name='Rewind', value="<")
	ForwardButton = HTMLgen.Input(type="submit", name='Forward', value=">")
	FastForwardButton = HTMLgen.Input(type="submit", name='FastForward', value=">>")
	varYear = HTMLgen.Input(type="hidden", name='varYear', value=year)
	varMonth = HTMLgen.Input(type="hidden", name='varMonth', value=month)

	(head, tail) = os.path.split(sys.argv[0])
	Navigate = HTMLgen.Form(target=tail, submit=ResetButton)
	Navigate.append(FastRewindButton)
	Navigate.append(RewindButton)
	Navigate.append(ForwardButton)
	Navigate.append(FastForwardButton)
	Navigate.append(varYear)
	Navigate.append(varMonth)

	C = HTMLgen.Center()

	doc.append(Navigate)
	doc.append( HTMLgen.BR() )

	if month == '0' :
		ThisYear = Year(year)
		doc.append( C(ThisYear) )
	else:
		(prev_y, prev_m) = PreviousMonth(year, month)
		PreviousMonth = Mon(prev_y, prev_m)
		ThisMonth = Mon(year, month)
		doc.append( C(PreviousMonth) )
		doc.append( C(ThisMonth) )

	print "Content-Type: text/html"
	print
	print doc
------=_20040525213926_99928--