Welcome, guest | Sign In | My Account | Store | Cart

This CGI program is designed to create schedules once given valid information on a form. It is not designed to look pretty but tests the ability to combine custom modules in different sized projects. It has minimal functionality but gets its job done in a timely manner and in a format that can be understood.

Python, 507 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
################################################################################
# index.py
################################################################################

import html_help
import os
import sys
import time
import Zcgi

KEYS = 'description', 'start', 'end', 'sunday', 'monday', \
       'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'

class soft_dict:
    
    def __init__(self, dictionary, format):
        self.__dictionary = dictionary
        self.__format = format
        
    def __getitem__(self, key):
        try:
            if self.__dictionary[key]:
                return self.__format % self.__dictionary[key]
        except:
            pass
        return ''

class WeekError:

    def __init__(self, string):
        self.__string = string

    def __str__(self):
        return self.__string

def main():
    if Zcgi.dictionary is None:
        show_form()
    elif has_keys(Zcgi.dictionary, KEYS):
        show_table()
    else:
        show_form()

def show_form(error=''):
    if error:
        error = '\t\t<b>' + error + '</b>\n'
    values = soft_dict(Zcgi.dictionary, ' value="%s"')
    Zcgi.print_html('''<html>
\t<head>
\t\t<title>
\t\t\tSchedule Maker
\t\t</title>
\t</head>
\t<body>
%s\t\t<form action="%s">
\t\t\tDescription:<br>
\t\t\t<input type="text"%s name="description" size="25"><br>
\t\t\tStart Date:<br>
\t\t\t<input type="text"%s name="start" size="25"><br>
\t\t\tEnd Date:<br>
\t\t\t<input type="text"%s name="end" size="25"><br>
\t\t\tSunday:<br>
\t\t\t<input type="text"%s name="sunday" size="25"><br>
\t\t\tMonday:<br>
\t\t\t<input type="text"%s name="monday" size="25"><br>
\t\t\tTuesday:<br>
\t\t\t<input type="text"%s name="tuesday" size="25"><br>
\t\t\tWednesday:<br>
\t\t\t<input type="text"%s name="wednesday" size="25"><br>
\t\t\tThursday:<br>
\t\t\t<input type="text"%s name="thursday" size="25"><br>
\t\t\tFriday:<br>
\t\t\t<input type="text"%s name="friday" size="25"><br>
\t\t\tSaturday:<br>
\t\t\t<input type="text"%s name="saturday" size="25"><br>
\t\t\t<input type="submit" value="Create Schedule">
\t\t</form>
\t</body>
</html>''' % tuple([error, os.path.basename(sys.argv[0])] \
                   + unpack(values, KEYS)))

def has_keys(dictionary, keys):
    for key in keys:
        if not dictionary.has_key(key):
            return False
    return True

def show_table():
    values = Zcgi.dictionary
    if not values['description']:
        show_form('You must enter a description.')
    try:
        start = time.strptime(values['start'], '%m/%d/%y')
        end = time.strptime(values['end'], '%m/%d/%y')
    except:
        show_form('Dates must be in the MM/DD/YY format.')
    try:
        assert time.mktime(end) > time.mktime(start)
    except:
        show_form('The end date must come after the start date.')
    try:
        check_week(values, KEYS[3:])
    except WeekError, problem:
        show_form(str(problem))
    html = create_html(values['description'], start, end, unpack(values, KEYS[3:]))
    Zcgi.print_html(html)

def unpack(values, keys):
    unpacked = []
    for key in keys:
        unpacked.append(values[key])
    return unpacked

def check_week(dictionary, keys):
    for key in keys:
        try:
            if not dictionary[key]:
                continue
            hm = dictionary[key].split('-')
            assert len(hm) == 2
            first = time.strptime(hm[0].strip(), '%H:%M')
            second = time.strptime(hm[1].strip(), '%H:%M')
            dictionary[key] = hm[0].strip() + ' - ' + hm[1].strip()
        except:
            raise WeekError(key.capitalize() + ' should be in the HH:MM - HH:MM format.')
        try:
            assert second.tm_hour * 60 + second.tm_min > first.tm_hour * 60 + first.tm_min
        except:
            raise WeekError('Start time must come before end time on ' + key.capitalize() + '.')

def create_html(description, start, end, week):
    html = '''<html>
\t<head>
\t\t<title>
\t\t\tThe Schedule
\t\t</title>
\t</head>
\t<body>
\t\t<center>
'''
    start_month = start.tm_year * 12 + (start.tm_mon - 1)
    end_month = end.tm_year * 12 + (end.tm_mon - 1)
    for month in range(start_month, end_month + 1):
        html += html_help.html_table(1, 1, 3, '\t').mutate(0, 0, create_month_html(description, start, end, week, month)).html() + '\n'
        if month != end_month:
            html += '\t\t\t<hr>\n'
    return html + '\t\t</center>\n\t</body>\n</html>'

def create_month_html(description, start, end, week, month):
    start = time.mktime(start) - 43200
    end = time.mktime(end) + 43200
    now = time.strptime(str((month / 12) % 100).zfill(2) + ' ' +  str(month % 12 + 1) + ' 01', '%y %m %d')
    html = '<b>' + time.strftime('%B %Y', now) + '</b>\n'
    html_month = html_help.html_month((month / 12) % 100, month % 12 + 1, 0, '\t')
    html_month.table_option('border="1" width="800"').row_option('valign="top"').column_option('width="14%"')
    now_month = now.tm_mon
    while now.tm_mon == now_month:
        mktime = time.mktime(now)
        if start <= mktime <= end:
            week_day = (now.tm_wday + 1) % 7
            if week[week_day]:
                html_month.mutate(now.tm_mday, '<b>' + description + '</b><br>\n' + week[week_day])
        now = time.localtime(mktime + 86400)
    return html + html_month.html()

if __name__ == '__main__':
    Zcgi.execute(main, 'cgi')

################################################################################
# html_help.py
################################################################################

import time
import Zam

class html_table:

    def __init__(self, rows, columns, indent, style):
        self.__matrix = Zam.matrix(rows, columns, '')
        self.__indent = indent
        self.__style = style
        self.__table_option = ''
        self.__row_option = ''
        self.__column_option = ''

    def mutate(self, row, column, text):
        assert type(text) is str
        self.__matrix[row][column] = text
        return self

    def access(self, row, column):
        return self.__matrix[row][column]

    def table_option(self, string):
        assert type(string) is str
        self.__table_option = string
        return self

    def row_option(self, string):
        assert type(string) is str
        self.__row_option = string
        return self

    def column_option(self, string):
        assert type(string) is str
        self.__column_option = string
        return self

    def html(self):
        html = self.__style * self.__indent + '<table'
        if self.__table_option:
            html += ' ' + self.__table_option
        html += '>\n'
        for row in self.__matrix:
            html += self.__style * (self.__indent + 1) + '<tr'
            if self.__row_option:
                html += ' ' + self.__row_option
            html += '>\n'
            for item in row:
                html += self.__style * (self.__indent + 2) + '<td'
                if self.__column_option:
                    html += ' ' + self.__column_option
                html += '>\n'
                html += ''.join([self.__style * (self.__indent  + 3) + line + '\n' for line in item.splitlines()])
                html += self.__style * (self.__indent + 2) + '</td>\n'
            html += self.__style * (self.__indent + 1) + '</tr>\n'
        return html + self.__style * self.__indent + '</table>'

class html_month:

    def __init__(self, year, month, indent, style):
        matrix = self.__make_matrix(year, month)
        self.__table = html_table(len(matrix) + 1, 7, indent, style)
        for index, item in enumerate(('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')):
            self.__table.mutate(0, index, '<b>' + item + '</b>')
        for row in range(len(matrix)):
            for column in range(7):
                if matrix[row][column]:
                    self.__table.mutate(row + 1, column, '<b>' + str(matrix[row][column]).zfill(2) + '</b>\n<hr>\n')

    def __make_matrix(self, year, month):
        rows = [Zam.array(7, 0)]
        row = 0
        now = time.localtime(time.mktime(time.strptime(str(year).zfill(2) + ' ' + str(month).zfill(2) + ' 01', '%y %m %d')) + 14400)
        self.__first_day = (now.tm_wday + 1) % 7
        once = False
        while now.tm_mon == month:
            if once:
                if now.tm_wday == 6:
                    rows.append(Zam.array(7, 0))
                    row += 1
            else:
                once = True
            rows[row][(now.tm_wday + 1) % 7] = now.tm_mday
            self.__days_in_month = now.tm_mday
            now = time.localtime(time.mktime(now) + 86400)
        return rows

    def mutate(self, day, text):
        row, column = self.__get_pos(day)
        self.__table.mutate(row, column, self.__table.access(row, column)[:15] + text)
        return self

    def access(self, day):
        row, column = self.__get_pos(day)
        return self.__table.access(row, column)[15:]

    def __get_pos(self, day):
        assert 1 <= day <= self.__days_in_month
        pos = self.__first_day - 1 + day
        return pos / 7 + 1, pos % 7

    def table_option(self, string):
        self.__table.table_option(string)
        return self

    def row_option(self, string):
        self.__table.row_option(string)
        return self

    def column_option(self, string):
        self.__table.column_option(string)
        return self

    def html(self):
        return self.__table.html()

################################################################################
# Zam.py
################################################################################

# Name & Description
# ==================

'''Support module for array and matrix use.

This module provides two classes that emulate one and two
dimentional lists with fixed sizes but mutable internals.'''

# Data & Imports
# ==============

__all__ = ['array', 'matrix']
__version__ = '1.1'

import sys

# Public Names
# ============

class array(object):

    '''array(length) -> new array
    array(length, value) -> initialized from value'''

    def __init__(self, length, value=None):
        '''x.__init__(...) initializes x'''
        self.__data = range(length)
        for index in range(length):
            self.__data[index] = value

    def __repr__(self):
        '''x.__repr__() <==> repr(x)'''
        return repr(self.__data)

    def __len__(self):
        '''x.__len__() <==> len(x)'''
        return len(self.__data)

    def __getitem__(self, key):
        '''x.__getitem__(y) <==> x[y]'''
        return self.__data[key]

    def __setitem__(self, key, value):
        '''x.__setitem__(i, y) <==> x[i]=y'''
        self.__data[key] = value

    def __delitem__(self, key):
        '''x.__delitem__(y) <==> del x[y]'''
        self.__data[key] = None

    def __iter__(self):
        '''x.__iter__() <==> iter(x)'''
        return iter(self.__data)

    def __contains__(self, value):
        '''x.__contains__(y) <==> y in x'''
        return value in self.__data

class matrix(object):

    '''matrix(rows, columns) -> new matrix
    matrix(rows, columns, value) -> initialized from value'''

    def __init__(self, rows, columns, value=None):
        '''x.__init__(...) initializes x'''
        self.__data = array(rows)
        for index in range(rows):
            self.__data[index] = array(columns, value)

    def __repr__(self):
        '''x.__repr__() <==> repr(x)'''
        return repr(self.__data)

    def __len__(self):
        '''x.__len__() <==> len(x)'''
        return len(self.__data)

    def __getitem__(self, key):
        '''x.__getitem__(y) <==> x[y]'''
        return self.__data[key]

    def __setitem__(self, key, value):
        '''x.__setitem__(i, y) <==> x[i]=y'''
        self.__data[key] = array(len(self.__data[key]), value)

    def __delitem__(self, key):
        '''x.__delitem__(y) <==> del x[y]'''
        self.__data[key] = array(len(self.__data[key]))

    def __iter__(self):
        '''x.__iter__() <==> iter(x)'''
        return iter(self.__data)

    def __contains__(self, value):
        '''x.__contains__(y) <==> y in x'''
        for item in self.__data:
            if value in item:
                return True
        return False

# Private Names
# =============

def main():
    print 'Content-Type: text/plain'
    print
    print file(sys.argv[0]).read()

# Execute Main
# ============

if __name__ == '__main__':
    main()

################################################################################
# Zcgi.py
################################################################################

# Name & Description
# ==================

'''Support module for use by CGI scripts.

This module provides several functions and variables
that help with printing text and accessing form data.'''

# Data & Imports
# ==============

__all__ = ['execute', 'print_html', 'print_plain', 'print_self',
           'dictionary', 'string']
__version__ = '1.2'

import os
import sys
import types

# Public Names
# ============

def execute(main, exception):
    '''execute(function main, str exception)

    Execute main unless exception.'''
    assert_type((types.FunctionType, main), (str, exception))
    if exception == string:
        print_self()
    else:
        main()

def print_html(text):
    '''print_html(str text)

    Print text as HTML.'''
    assert_type((str, text))
    print 'Content-Type: text/html'
    print
    print text
    sys.exit(0)

def print_plain(text):
    '''print_plain(str text)

    Print text as plain.'''
    assert_type((str, text))
    print 'Content-Type: text/plain'
    print
    print text
    sys.exit(0)

def print_self():
    '''print_self()

    Print __main__ as plain.'''
    print 'Content-Type: text/plain'
    print
    print file(sys.argv[0]).read()
    sys.exit(0)

# Private Names
# =============

def export():
    global dictionary, string
    dictionary = string = None
    try:
        string = os.environ['QUERY_STRING']
        temp = string.replace('+', ' ').split('&')
        for index in range(len(temp)):
            temp[index] = temp[index].split('=')
        dictionary = dict()
        for parameter, value in temp:
            dictionary[decode(parameter)] = decode(value)
    except:
        pass

def decode(string):
    assert_type((str, string))
    index = string.find('%')
    while index != -1:
        string = string[:index] + chr(int(string[index+1:index+3], 16)) + string[index+3:]
        index = string.find('%', index + 1)
    return string

def assert_type(*tuples):
    for types, objects in tuples:
        if type(objects) is not types:
            raise TypeError

# Execute Conditional
# ===================

if __name__ == '__main__':
    print_self()
else:
    export()

The code here is useful to demonstrate a multi-custom-module CGI program. Some of the code presented here also has some useful applications else where because of its modular structure (such as html_help.py). This program was created for the purpose of entering limited scheduling information and have that information presented in an HTML format that could easily be read and understood. There are no known issues with this recipe, but you are welcome to find them and point them out for correction. This is the very first version of this code and was not designed to be fast -- just to work. The Python Library Reference was found to be extremely helpful in the creation of this recipe (as with the writing of most programs).

Note that several original bugs have been fixed including:

  • DST bug causing incorect rendering of months
  • month calculation bug causing crash of program

5 comments

Stephen Chappell (author) 18 years, 1 month ago  # | flag

Oops.

description=HI+102&start=01%2F16%2F06&end=04%2F28%2F06&sunday=&monday=13%3A00+-+13%3A50&tuesday=10%3A00+-+10%3A50&wednesday=13%3A00+-+13%3A50&thursday=10%3A00+-+10%3A50&friday=13%3A00+-+13%3A50&saturday=

The previous query string works for me, and many query strings will work, but it has been demonstrated (by adding another year to the end date) that this recipe is incomplete. It seems that the following line has a problem with it.

now = time.strptime(str((month / 12) % 100).zfill(2) + ' ' +  str(month % 12) + ' 01', '%y %m %d')

The problem has not yet been solved.

Stephen Chappell (author) 18 years, 1 month ago  # | flag

Corrected. The most current version of this program should now work correctly.

Austin Trombley 12 years, 8 months ago  # | flag

Where do you save the different .py files so that they import into the program? When I saved this program and ran it, it bunks out at the

================================================================================

schedule_maker.py

Because there is no leading # which I assume it means you need to save these separate .py's? But where do I save them so that python knows where to import them?

Stephen Chappell (author) 12 years, 8 months ago  # | flag

(1) First of all, you need to configure a web server to run Python CGI programs. If you have not already done so, you may check http://www.aprelium.com/ and see their documentation on setting up their particular server for Python CGI. (2) The second thing to do is place the four different files up above in a directory together that you can reach by way of the server. (3) Going to the correct path and running schedule_maker.py should allow you to see what the program does.

Please note that this is old code that has hardly been maintained for the past five years. By my own current standards, this program would be rewritten from scratch if there were time to do so. If you need any other help, you can contact me at Noctis.Skytower@gmail.com and ask whatever other questions you might have.

Victor Mutasa Kyefulumya 8 years, 10 months ago  # | flag

I tried to run this code on terminal and got this error message Traceback (most recent call last): File "Schedule.py", line 5, in <module> import html_help ImportError: No module named html_help what does this mean?