OILS / mycpp / examples / cgi.py View on Github | oilshell.org

62 lines, 31 significant
1#!/usr/bin/env python2
2"""
3cgi.py - Copied from Python stdlib.
4
5We don't want the side effects of importing tempfile, which imports random,
6which opens /dev/urandom!
7"""
8from __future__ import print_function
9
10import os
11
12from mycpp import mylib
13from mycpp.mylib import log
14
15# For testing what the code generator does
16BACKSLASH = '\\'
17RAW_BACKSLASH = r'\d+'
18
19
20def escape(s, quote=False):
21 # type: (str, bool) -> str
22 '''Replace special characters "&", "<" and ">" to HTML-safe sequences.
23 If the optional flag quote is true, the quotation mark character (")
24 is also translated.'''
25 s = s.replace("&", "&amp;") # Must be done first!
26 s = s.replace("<", "&lt;")
27 s = s.replace(">", "&gt;")
28 if quote:
29 s = s.replace('"', "&quot;")
30 return s
31
32
33def run_tests():
34 # type: () -> None
35
36 mystr = 'xo--xo'
37 log('s: %s', mystr)
38
39 log("escaped: %s", escape('<html>', True))
40
41 # Let's only replace one character for now
42 log("%s\n", mystr.replace('x', 'X'))
43
44
45def run_benchmarks():
46 # type: () -> None
47 i = 0
48 n = 1000000
49 while i < n:
50 escape('<html>', True)
51 i = i + 1
52 #log("i = %d", i)
53
54 mylib.MaybeCollect()
55
56
57if __name__ == '__main__':
58 if os.getenv('BENCHMARK'):
59 log('Benchmarking...')
60 run_benchmarks()
61 else:
62 run_tests()