calendar cgi script - first iteration - Programmers Heaven

#### Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

#### Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

# calendar cgi script - first iteration

Posts: 2,900Member
[b][red]This message was edited by infidel at 2002-12-31 12:40:20[/red][/b][hr]
Whoops, I messed up the html and body tags at the bottom! Now fixed.

[b][red]This message was edited by infidel at 2002-12-31 12:38:4[/red][/b][hr]
Here is my first attempt at a python script that generates a calendar in the style of DJ's javascript calendar. Notice how much cleaner and simpler the python code is compared to the javascript version. Python's built-in modules made this a breeze. Drop this in your cgi-bin and see what happens:

[code]
#!/usr/bin/python

import calendar
import time

def CalendarHTMLTable(year, month):
# make Sunday the first day of the week
calendar.setfirstweekday(calendar.SUNDAY)

# get the time value
caltime = (year, month, 0, 0, 0, 0, 0, 0, -1)

# get the matrix of calendar days
calmatrix = calendar.monthcalendar(caltime[0],caltime[1])

# begin calendar html table
html = ""

# calendar header
html = html + ""
html = html + ""
html = html + ""
html = html + ""
html = html + ""

# calendar body
for week in calmatrix:
html = html + ""
for day in week:
if day == 0:
html = html + ""
else:
html = html + ""
html = html + ""

# close up calendar table
html = html + "
 (prev) " + time.strftime("%B %Y", caltime) + " (next) " + str(day) + "
"

# return the html table
return html

if __name__ == '__main__':
print "Content-type: text/html
"
print ""
print CalendarHTMLTable(2002,12)
print ""
[/code]

[size=5][italic][blue][RED]i[/RED]nfidel[/blue][/italic][/size]

«1

## Comments

• Posts: 2,900Member
ok, I haven't yet found a way to use builtin functionality to display the weekday names at the top so I had to just create a list and iterate through it.

[code]#!/usr/bin/python

import calendar
import time

weekdays = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']

def CalendarHTMLTable(year, month):
# make Sunday the first day of the week
calendar.setfirstweekday(calendar.SUNDAY)

# get the time value
caltime = (year, month, 0, 0, 0, 0, 0, 0, -1)

# get the matrix of calendar days
calmatrix = calendar.monthcalendar(caltime[0],caltime[1])

# begin calendar html table
html = ""

# calendar header
html = html + ""
html = html + ""
html = html + ""
html = html + ""
html = html + ""

# weekday names
html = html + ""
for day in range(7):
html = html + ""
html = html + ""

# calendar body
for week in calmatrix:
html = html + ""
for day in week:
if day == 0:
html = html + ""
else:
html = html + ""
html = html + ""

# close up calendar table
html = html + " (prev) " + time.strftime("%B %Y", caltime) + " (next) " + weekdays[day] + " " + str(day) + "
"

# return the html table
return html

if __name__ == '__main__':
print "Content-type: text/html
"
print ""
print CalendarHTMLTable(2002,12)
print ""[/code]

[size=5][italic][blue][RED]i[/RED]nfidel[/blue][/italic][/size]

• Posts: 2,900Member
Now we're making progress. The script now has the ability to move forwards and backwards through the calendar in a month-by-month fashion. I would like to extend this eventually so users could jump back to "today" if they wandered too far off and didn't want to have to go through every month again to get back. For the moment, however, this jumps a major hurdle that I wasn't sure how to get around. It does, however, raise a new issue. In order for the script to know what month to display, the current month has to be stored within the html and sent back to the script when the arrows are pressed. The only way I know of to do that so far is to use hidden form elements. This means that the checkboxes will have to be added to the html from within the CalendarHTMLTable function when I was hoping to leave this function as generic as possible and not tie it to our specific problem. It's not that big of a deal, though.

Note that you will need to change the image src attributes to valid URLs and the ACTION attribute of the form tag should be set to the URL of this script. I don't like doing that but it'll suffice for now.

One last thing, I've begun to add the foundation for passing a dictionary of events to the calendar so when it is generating the calendar body it can quickly list any events occurring on each day.

[code]
#!/usr/bin/python

import calendar
import time

weekdays = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']

def CalendarHTMLTable(year, month, events = {}):
# make Sunday the first day of the week
calendar.setfirstweekday(calendar.SUNDAY)

# get the time value
caltime = (year, month, 0, 0, 0, 0, 0, 0, -1)

# get the matrix of calendar days
calmatrix = calendar.monthcalendar(caltime[0],caltime[1])

# begin calendar html table
html = ''
html = html + ''
html = html + ''
html = html + ''

# calendar header
html = html + ''
html = html + ''
html = html + '"
html = html + ''
html = html + ""

# weekday names
html = html + ""
for day in range(7):
html = html + ""
html = html + ""

# calendar body
for week in calmatrix:
html = html + ""
for day in week:
if day == 0:
html = html + ""
else:
html = html + ""
html = html + ""

# close up calendar table
html = html + " ' + '' + ' ' + time.strftime("%B %Y", caltime) + " ' + '' + ' " + weekdays[day] + " " html = html + str(day) + "" if events.has_key(day): eventlist = events[day] for event in eventlist: html = html + '' html = html + event["time"] + ": " + event["title"] + "" html = html + '' html = html + "
"

# return the html table
return html

if __name__ == '__main__':
# get parameters
import cgi
form = cgi.FieldStorage()
if form.has_key("year"):
year = int(form["year"].value)
else:
year = time.localtime()[0]
if form.has_key("month"):
month = int(form["month"].value)
else:
month = time.localtime()[1]
if form.has_key("next.x"):
month += 1
if month > 12:
month = 1
year += 1
if form.has_key("prev.x"):
month -= 1
if month < 1:
month = 12
year -= 1

# print http header
print "Content-type: text/html
"

# spit out html calendar displaying events
print ""
print CalendarHTMLTable(year,month)
print ""
[/code]
[size=5][italic][blue][RED]i[/RED]nfidel[/blue][/italic][/size]

• Posts: 27Member
*Gasp!!!* I was just about to tell you that I have now purchased a book that I think you will enjoy as much as I will. It is called Python2.1 Bible. It includes a complete language reference and talks about object oriented programming. With it, I was about to do what you just did and show you that I was making progress! But little did I know you were DAYS ahead of me. I shall speed things up. I am testing the calendar out and trying not to drool too much over it. I will be back with some more info in a day or so. PEACE!
: [code]
: #!/usr/bin/python
:
: import calendar
: import time
:
: weekdays = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
:
: def CalendarHTMLTable(year, month, events = {}):
: # make Sunday the first day of the week
: calendar.setfirstweekday(calendar.SUNDAY)
:
: # get the time value
: caltime = (year, month, 0, 0, 0, 0, 0, 0, -1)
:
: # get the matrix of calendar days
: calmatrix = calendar.monthcalendar(caltime[0],caltime[1])
:
: # begin calendar html table
: html = ''
: html = html + ''
: html = html + ''
: html = html + ''
:
: # calendar header
: html = html + ''
: html = html + ''
: html = html + '"
: html = html + ''
: html = html + ""
:
: # weekday names
: html = html + ""
: for day in range(7):
: html = html + ""
: html = html + ""
:
: # calendar body
: for week in calmatrix:
: html = html + ""
: for day in week:
: if day == 0:
: html = html + ""
: else:
: html = html + ""
: html = html + ""
:
: # close up calendar table
: html = html + " ' + : '' + : ' ' + : time.strftime("%B %Y", caltime) + " ' + : '' + : ' " + weekdays[day] + " ": html = html + str(day) + "": if events.has_key(day):: eventlist = events[day]: for event in eventlist:: html = html + '': html = html + event["time"] + ": " + event["title"] + "": html = html + '': html = html + "
"
:
: # return the html table
: return html
:
: if __name__ == '__main__':
: # get parameters
: import cgi
: form = cgi.FieldStorage()
: if form.has_key("year"):
: year = int(form["year"].value)
: else:
: year = time.localtime()[0]
: if form.has_key("month"):
: month = int(form["month"].value)
: else:
: month = time.localtime()[1]
: if form.has_key("next.x"):
: month += 1
: if month > 12:
: month = 1
: year += 1
: if form.has_key("prev.x"):
: month -= 1
: if month < 1:
: month = 12
: year -= 1
:
: # print http header
: print "Content-type: text/html
"
:
: # spit out html calendar displaying events
: print ""
: print CalendarHTMLTable(year,month)
: print ""
: [/code]
: [size=5][italic][blue][RED]i[/RED]nfidel[/blue][/italic][/size]
:
:

[hr][size=4][blue][b]D[/b][/blue][/size][size=5][italic][grey][b]J[/b][/grey][/italic][/size]

• Posts: 27Member
: [code]
: #!/usr/bin/python
:
: import calendar
: import time
:
: def CalendarHTMLTable(year, month):
: # make Sunday the first day of the week
: calendar.setfirstweekday(calendar.SUNDAY)
:
: # get the time value
: caltime = (year, month, 0, 0, 0, 0, 0, 0, -1)
:
: # get the matrix of calendar days
: calmatrix = calendar.monthcalendar(caltime[0],caltime[1])
:
: # begin calendar html table
: html = ""
:
: # calendar header
: html = html + ""
: html = html + ""
: html = html + ""
: html = html + ""
: html = html + ""
:
: # calendar body
: for week in calmatrix:
: html = html + ""
: for day in week:
: if day == 0:
: html = html + ""
: else:
: html = html + ""
: html = html + ""
:
: # close up calendar table
: html = html + " (prev) " + : time.strftime("%B %Y", caltime) + " (next) " + str(day) + "
"
:
: # return the html table
: return html
:
: if __name__ == '__main__':
: print "Content-type: text/html
"
: print ""
: print CalendarHTMLTable(2002,12)
: print ""
: [/code]
:
: [size=5][italic][blue][RED]i[/RED]nfidel[/blue][/italic][/size]
[green]I tried to load this script and your third iteration. The paths were the same on my server as you wrote so I didn't have to change anything. I copied the script, pasted it in Notepad and saved it as [red]'cal.py'[/red] and [red]'eventcal.py'[/red] then uploaded into my cgi-bin. I then tried to load it into my browser and got a 500 error. See for yourself. [blue]http://www.febconline.com/cgi-bin/eventcal.py[/blue]. This path is the same one that the "Welcome CGI World script I tried and that works. Try it. "/pythontest.py" I am at a loss. Any suggestions?[/green]
[hr][size=4][blue][b]D[/b][/blue][/size][size=5][italic][grey][b]J[/b][/grey][/italic][/size]

• Posts: 2,900Member
: [green]I tried to load this script and your third iteration. The paths were the same on my server as you wrote so I didn't have to change anything. I copied the script, pasted it in Notepad and saved it as [red]'cal.py'[/red] and [red]'eventcal.py'[/red] then uploaded into my cgi-bin. I then tried to load it into my browser and got a 500 error. See for yourself. [blue]http://www.febconline.com/cgi-bin/eventcal.py[/blue]. This path is the same one that the "Welcome CGI World script I tried and that works. Try it. "/pythontest.py" I am at a loss. Any suggestions?[/green]
: [hr][size=4][blue][b]D[/b][/blue][/size][size=5][italic][grey][b]J[/b][/grey][/italic][/size]

Good! This will be a lesson in debugging cgi. Apache isn't very helpful when something bad happens. The best thing you can do when you get a 500 is to try running your script with the python interpreter. Log in to your webserver and go to the cgi-bin directory and type:

[code]python eventcal.py[/code]

Depending on how your environment is set up you may need to prefix python with the full path, i.e. /usr/bin/python

This will execute the code and spit out a traceback message for any syntax errors (which is what is most likely causing the 500).

If you can't decipher the tracebacks, post them here and I'll take a look at them.

[size=5][italic][blue][RED]i[/RED]nfidel[/blue][/italic][/size]

• Posts: 27Member
[b][red]This message was edited by djshadmego at 2003-1-6 22:14:36[/red][/b][hr]
: : [green]I tried to load this script and your third iteration. The paths were the same on my server as you wrote so I didn't have to change anything. I copied the script, pasted it in Notepad and saved it as [red]'cal.py'[/red] and [red]'eventcal.py'[/red] then uploaded into my cgi-bin. I then tried to load it into my browser and got a 500 error. See for yourself. [blue]http://www.febconline.com/cgi-bin/eventcal.py[/blue]. This path is the same one that the "Welcome CGI World script I tried and that works. Try it. "/pythontest.py" I am at a loss. Any suggestions?[/green]
: : [hr][size=4][blue][b]D[/b][/blue][/size][size=5][italic][grey][b]J[/b][/grey][/italic][/size]
:
: Good! This will be a lesson in debugging cgi. Apache isn't very helpful when something bad happens. The best thing you can do when you get a 500 is to try running your script with the python interpreter. Log in to your webserver and go to the cgi-bin directory and type:
:
: [code]python eventcal.py[/code]
:
: Depending on how your environment is set up you may need to prefix python with the full path, i.e. /usr/bin/python
:
: This will execute the code and spit out a traceback message for any syntax errors (which is what is most likely causing the 500).
:
: If you can't decipher the tracebacks, post them here and I'll take a look at them.
:
:
: [size=5][italic][blue][RED]i[/RED]nfidel[/blue][/italic][/size]

Ok. Here is what I did. I don't have a place in my cgi directory to type
[code]python eventcal.py[/code]
If there is a place, I don't know where it is so I didn't do anything with that. I did however find my error log and looked at the problem with the 500 error. It said this:
[code][Mon Jan 6 11:34:30 2003] [error] [client ] Premature end of script headers: /home/virtual/site78/fst/var/www/cgi-bin/cal.py
[Mon Jan 6 23:41:09 2003] [error] [client ] Premature end of script headers: /home/virtual/site78/fst/var/www/cgi-bin/eventcal.py
File "eventcal.py", line 79
month += 1
^
SyntaxError: invalid syntax
[Mon Jan 6 23:46:24 2003] [error] [client ] Premature end of script headers: /home/virtual/site78/fst/var/www/cgi-bin/eventcal.py
File "eventcal.py", line 79
month += 1
^
SyntaxError: invalid syntax
[Mon Jan 6 23:51:19 2003] [error] [client ] Premature end of script headers: /home/virtual/site78/fst/var/www/cgi-bin/eventcal.py
[/code]
This is all fine and good. I don't know how to change my end of script headers to fix the problem though. The script I just cut-and-pasted. The line:[code]#!/usr/bin/python [/code]
Is no different than the "Hello cgi world" script. And I don't really understand about the environment or how to set it up. I am guessing it's set up correctly because the cgi world script works just fine. I dunno. I will look at it again tomorrow then see what you have to say about it. *Sigh* the joy of programming!! (Secretly I love this stuff but I can't let people know!) *wink*
I actually just remembered what the environment was. Yes, the scripts are executable. "pythontest.py", "cal.py", and "eventcal.py". *sheesh*
[hr][size=4][blue][b]D[/b][/blue][/size][size=5][italic][grey][b]J[/b][/grey][/italic][/size]

• Posts: 2,900Member
: Ok. Here is what I did. I don't have a place in my cgi directory to type
: [code]python eventcal.py[/code]

Oh, you don't have a command line? How do you log in to your server? Do they only give you a graphical interface?

: If there is a place, I don't know where it is so I didn't do anything with that. I did however find my error log and looked at the problem with the 500 error. It said this:
: [code][Mon Jan 6 11:34:30 2003] [error] [client ] Premature end of script headers: /home/virtual/site78/fst/var/www/cgi-bin/cal.py
: [Mon Jan 6 23:41:09 2003] [error] [client ] Premature end of script headers: /home/virtual/site78/fst/var/www/cgi-bin/eventcal.py
: File "eventcal.py", line 79
: month += 1
: ^
: SyntaxError: invalid syntax
: [Mon Jan 6 23:46:24 2003] [error] [client ] Premature end of script headers: /home/virtual/site78/fst/var/www/cgi-bin/eventcal.py
: File "eventcal.py", line 79
: month += 1
: ^
: SyntaxError: invalid syntax
: [Mon Jan 6 23:51:19 2003] [error] [client ] Premature end of script headers: /home/virtual/site78/fst/var/www/cgi-bin/eventcal.py
: [/code]
: This is all fine and good. I don't know how to change my end of script headers to fix the problem though. The script I just cut-and-pasted.

The script headers aren't the problem. If you look closely, the script has a syntax error which is causing it to abort before it prints out anything. The http "headers" are lines like "Content-type: text/html". I don't understand why month += 1 is throwing a syntax error. It works fine on my machine and "+=" is pretty standard programming notation. I suppose though, that an older version of python might not support that operator. Here is the block of code where the offending line is:
[code]
if form.has_key("next.x"):
month += 1
if month > 12:
month = 1
year += 1
if form.has_key("prev.x"):
month -= 1
if month < 1:
month = 12
year -= 1
[/code]

Try changing this part to:

[code]
if form.has_key("next.x"):
month = month + 1
if month > 12:
month = 1
year = year + 1
if form.has_key("prev.x"):
month = month - 1
if month < 1:
month = 12
year = year - 1
[/code]

We'll replace the += and -= shorthand operators with the full expressions and see if that gets us past the syntax error. Got that?

: The line:[code]#!/usr/bin/python [/code]
: Is no different than the "Hello cgi world" script. And I don't really understand about the environment or how to set it up. I am guessing it's set up correctly because the cgi world script works just fine.

Ok, don't worry about it for now then.

: I actually just remembered what the environment was. Yes, the scripts are executable. "pythontest.py", "cal.py", and "eventcal.py". *sheesh*

Actually, I was just wondering if python is in your PATH or if you would have to type /usr/bin/python to run the interpreter manually, but since you don't seem to have a command line anyways this is rather moot.

Onward and upward!

[size=5][italic][blue][RED]i[/RED]nfidel[/blue][/italic][/size]

• Posts: 27Member
Here is the block of code where the offending line is:
: [code]
: if form.has_key("next.x"):
: month += 1
: if month > 12:
: month = 1
: year += 1
: if form.has_key("prev.x"):
: month -= 1
: if month < 1:
: month = 12
: year -= 1
: [/code]
:
: Try changing this part to:
:
: [code]
: if form.has_key("next.x"):
: month = month + 1
: if month > 12:
: month = 1
: year = year + 1
: if form.has_key("prev.x"):
: month = month - 1
: if month < 1:
: month = 12
: year = year - 1
: [/code]
:
: We'll replace the += and -= shorthand operators with the full expressions and see if that gets us past the syntax error. Got that?

New Error:
[code]Traceback (innermost last):
File "eventcal.py", line 73, in ?
year = time.localtime()[0]
TypeError: function requires at least one argument
[/code]

I do have a graphical interface. I can't find a way to get a command line and I am thinking I don't have one at all from what you said. As for the Python thing, well, I am asking them what version of it they have. But I thought They had the newest one. I should find out in a day or two.

*putt....putt*

[hr][size=4][blue][b]D[/b][/blue][/size][size=5][italic][grey][b]J[/b][/grey][/italic][/size]

• Posts: 2,900Member
: New Error:
: [code]Traceback (innermost last):
: File "eventcal.py", line 73, in ?
: year = time.localtime()[0]
: TypeError: function requires at least one argument
: [/code]
:
: I do have a graphical interface. I can't find a way to get a command line and I am thinking I don't have one at all from what you said. As for the Python thing, well, I am asking them what version of it they have. But I thought They had the newest one. I should find out in a day or two.

Ok, I just checked my module reference and there's a note that says the argument to localtime() was made optional in version 2.1 and defaults to "now", so you must have an older version of Python than that. The quick solution is:

[code]
year = time.localtime(time.time())[0]
[/code]

time.time() returns the number of seconds since the epoch began ("now"), and time.localtime(secs) converts a number of seconds into a tuple like:

(2003, 1, 8, 8, 11, 31, 2, 8, 0)

The [0] is list notation to get the zeroth element from the tuple, so
"time.localtime(time.time())[0]" returns 2003.

[size=5][italic][blue][RED]i[/RED]nfidel[/blue][/italic][/size]

• Posts: 2,900Member
: : New Error:
: : [code]Traceback (innermost last):
: : File "eventcal.py", line 73, in ?
: : year = time.localtime()[0]
: : TypeError: function requires at least one argument
: : [/code]

I just figured out something that might help. I moved printing of the http header to the top so if any errors occur, at least apache will not throw the 500 error at us. I also imported the sys module and changed the standard error stream to be the same as the standard out stream. This way, any errors that normally will go to the error logs will get printed to the output so when we try to view the script in a browser, we'll know immediately what error was thrown by python.

[code]
#!/usr/bin/python

# http header
print "Content-type: text/html
"

# redirect stderr to stdout
import sys
sys.stderr = sys.stdout

# define calendar functions
import calendar
import time

weekdays = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']

def CalendarHTMLTable(year, month, events = {}):
# make Sunday the first day of the week
calendar.setfirstweekday(calendar.SUNDAY)

# get the time value
caltime = (year, month, 0, 0, 0, 0, 0, 0, -1)

# get the matrix of calendar days
calmatrix = calendar.monthcalendar(caltime[0],caltime[1])

# begin calendar html table
html = ''
html = html + ''
html = html + ''
html = html + ''

# calendar header
html = html + ''
html = html + ''
html = html + '"
html = html + ''
html = html + ""

# weekday names
html = html + ""
for day in range(7):
html = html + ""
html = html + ""

# calendar body
for week in calmatrix:
html = html + ""
for day in week:
if day == 0:
html = html + ""
else:
html = html + ""
html = html + ""

# close up calendar table
html = html + " ' + '' + ' ' + time.strftime("%B %Y", caltime) + " ' + '' + ' " + weekdays[day] + " " html = html + str(day) + "" if events.has_key(day): eventlist = events[day] for event in eventlist: html = html + '' html = html + event["time"] + ": " + event["title"] + "" html = html + '' html = html + "
"

# return the html table
return html

if __name__ == '__main__':
# get parameters
import cgi
form = cgi.FieldStorage()
if form.has_key("year"):
year = int(form["year"].value)
else:
year = time.localtime(time.time())[0]
if form.has_key("month"):
month = int(form["month"].value)
else:
month = time.localtime(time.time())[1]
if form.has_key("next.x"):
month = month + 1
if month > 12:
month = 1
year = year + 1
if form.has_key("prev.x"):
month = month - 1
if month < 1:
month = 12
year = year - 1

# spit out html calendar displaying events
print ""
print CalendarHTMLTable(year,month)
print ""
[/code]

[size=5][italic][blue][RED]i[/RED]nfidel[/blue][/italic][/size]

«1
Sign In or Register to comment.