]> git.phdru.name Git - m_lib.git/blob - m_lib/net/www/util.py
Use print function for Py3 compatibility
[m_lib.git] / m_lib / net / www / util.py
1 """Common WWW/CGI utilities"""
2
3
4 from __future__ import print_function
5 import sys, os
6
7
8 def exception(str = ""):
9    if sys.exc_type == SystemExit: # pass exit() normally
10       return
11
12    # Add the second linefeed to terminate HTTP headers
13    print("Content-Type: text/html\n")
14
15    import html
16    print(html.exception())
17
18    if str:
19       print(str)
20
21    sys.exit(1)
22
23
24 def error(err_str):
25    if not err_str:
26       err_str = "Unknown error"
27
28    # Add the second linefeed to terminate HTTP headers
29    print("Content-Type: text/html\n")
30
31    print(str(err_str))
32    sys.exit(1)
33
34
35 def get_redirect(_str = ""):
36    server_name = os.environ["SERVER_NAME"]
37    server_port = os.environ["SERVER_PORT"]
38
39    if server_port == "80":
40       server_port = ""
41    else:
42       server_port = ":" + server_port
43
44    return "http://" + server_name + server_port + _str
45
46
47 def convert_empty(estr):
48    if estr:
49       _str = str(estr)
50    else:
51       _str = " "
52    return _str
53
54
55 def gen_html(title, body):
56    print("""
57    <HTML>
58       <HEAD>
59          <TITLE>
60             %s
61          </TITLE>
62       </HEAD>
63
64       <BODY>
65          %s
66       </BODY>
67    </HTML>
68    """ % (title, body))
69
70
71 def mkexpires(hours=1, minutes=0, seconds=0):
72    from datetime import datetime, timedelta
73    expire = datetime.now() + timedelta(hours=hours, minutes=minutes, seconds=seconds)
74    return "Expires: %s" % expire.strftime("%a, %d %b %Y %H:%M:%S GMT")
75
76
77 def parse_time(t):
78    import time
79    for format in ("%a, %d %b %Y %H:%M:%S GMT", "%A, %d-%b-%y %H:%M:%S GMT", "%A, %d-%b-%Y %H:%M:%S GMT"):
80       try:
81          return time.mktime(time.strptime(t, format)) - time.timezone
82       except (ValueError, OverflowError):
83          pass
84
85    return None