encoding utf-8 def get_js environ start_response start_response 200 Ok

 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
# encoding: utf-8
def get_js(environ, start_response):
start_response('200 Ok', [
('Content-Type', 'text/javascript')
])
js ="""
function handleJsonData(json){
$("#result").text("")
$.each(json, function(i, item)
{$("#result").append('<li>'+item+'</li>')});
$("#result").wrapInner("<ul></ul>")
}
function onDocumentReady(){
$("#retrieve-data").click(function()
{$.getJSON("/json", handleJsonData)});
}
$(document).ready(
onDocumentReady
);
"""
return [js]
def get_json_data(environ, start_response):
start_response('200 Ok', [
('Content-Type', 'text/x-json; encoding=utf-8')
])
json = "['foo', 'bar', 'bazz']"
return [json]
def get_page(environ, start_response):
start_response('200 Ok', [
('Content-Type', 'text/html; encoding=utf-8')
])
html = """
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js">
</script>
<script type="text/javascript" src="/ex.js"></script>
</head>
<body>
<h1>The page</h1>
<p>
<a id="retrieve-data" href="#">Retrieve data from DB</a>
<div id="result">The result</div>
</p>
</body>
</html>
"""
return [html]
def mainapp(environ, start_response):
if environ['PATH_INFO'] == '/json':
print "Return json data"
return get_json_data(environ, start_response)
elif environ['PATH_INFO'] == '/ex.js':
print "Return js"
return get_js(environ, start_response)
else:
print "Regular request, show the page"
return get_page(environ, start_response)
if __name__ == '__main__':
from wsgiref import simple_server
httpd = simple_server.make_server('', 8000, mainapp)
print "Listening on http://127.0.0.1:8000/"
httpd.serve_forever()