-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathknife.py
252 lines (196 loc) · 7.16 KB
/
knife.py
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
knife is a scalable mini-webframework based wsgi. It offers request routes with
url parameter support and simple templates engines
--------------------------The MIT License---------------------------
Copyright (c) 2011 Qi Wang
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import os, sys, re, cgi, threading
from posixpath import normpath
def get_headers(env):
return [(
'Content-type',
env.get('CONTENT_TYPE', "text/plain")
)]
def get_req(env, **args):
return updated(env, {
'method' : env.get('REQUEST_METHOD', "GET"),
'path_info' : env.get('PATH_INFO', ""),
'http_host' : env.get('HTTP_HOST', settings['http_host']),
'args' : args,
'session' : (env['com.saddi.service.session'].session
if env.has_key('com.saddi.service.session') else None),
})
def get_resp(content, status='200', content_type='text/plain'):
return {
'content' : content,
'status' : settings['status_dic'][status],
'content_type' : content_type
}
def route(env):
for k, v in settings['mapping']:
sre = re.search(k, normpath(env['PATH_INFO']))
if sre:
args = sre.groupdict()
for k_, v_ in args.items():
args[k_] = v_[1:] if v_.startswith('/') else v_
args[k_] = v_[:-1] if v_.endswith('/') else v_
return k, v, args
raise HTTP404Error
def get_app(env, start_response):
local.tplstream = "" #reset tplstream
try:
path, app_parts, args = route(env)
except HTTP404Error:
start_response('404 error!', get_headers(env))
return app_404()
if env['REQUEST_METHOD'] == "POST":
for k, v in cgi.parse_qs(env['wsgi.input'].read(
int(env['CONTENT_LENGTH']))).items():
args[k] = v if len(v) > 1 else v[0]
response = getattr(
__import__(app_parts[0]),
app_parts[1])(get_req(env, **args)) if app_parts[0] else eval(
app_parts[1])(get_req(env, **args))
if response['status'] == settings['status_dic']["302"]:
start_response("302 redirect!", [('Location', response['content'])])
return []
env['CONTENT_TYPE'] = response['content_type']
start_response(response['status'], get_headers(env))
return [response['content']]
def get_tpl(path, data={}):
""" a simple template engine """
path = "%s/%s" % (settings['template_dir'], path)
startblocks = ('if', 'for')
endblocks = ('endif', 'endfor')
indent_width = 4
stack = [
"\n",
'\n'.join(
map(lambda x : "%s = %s" % (x[0], repr(x[1])),
data.items()
)
)
]
def getblock(line):
return (re.split(r'[^a-zA-Z0-9_]', line)[0].rstrip(':')
if line else ''
)
def translate(line):
def linevar():
for v in re.findall('{{.+?}}', line):
yield v.replace("{{", "").replace("}}", "")
yield ''
return 'local.tplstream += ' + '+'.join(reduce(lambda x,y : x + y,
zip(
map(lambda x : repr(x),
re.split('{{.+?}}', line)
),
linevar()
)
)).rstrip('+')
def format(line):
_indentfunc = lambda line, indent : stack.append(
(''.join([' ' * indent, line])))
prev_stack_indent = len(stack[-1]) - len(stack[-1].lstrip())
indent = prev_stack_indent + \
[0, indent_width][getblock(stack[-1]) in startblocks]
if getblock(line) in startblocks:
_indentfunc(line, indent)
elif getblock(line) in endblocks:
_indentfunc('', indent - indent_width)
else:
_indentfunc(translate(line), indent)
for line in open(path).read().splitlines(True):
line = line.strip() if isinstance(line, unicode) \
else unicode(line.strip(), encoding='utf8')
format(line.replace("{% ","").replace(" %}",":"))
eval(compile('\n'.join(stack), "<string>", "exec"))
return local.tplstream.encode("utf-8")
"""
TEST SERVER
"""
def runserver():
from wsgiref.simple_server import make_server
httpd = make_server(
settings['host'], settings['port'],
get_app
)
print "Serving HTTP on port %d" % settings["port"]
httpd.serve_forever()
"""
TOOLS
"""
def loop(var, funcs):
for func in funcs:
var = func(var)
return var
def updated(dic,exdic):
dic.update(exdic)
return dic
def appended(li, item):
li.append(item)
return li
def extended(li, exli):
li.extended(item)
return li
"""
SETTINGS AND GLOBAL VAR
"""
try:
from settings import config
except:
config = {}
settings = {
'http_host' : "http://0.0.0.0:8000",
"host" : "0.0.0.0",
"port" : 8000,
'status_dic' : {
"200" : "200 ok!",
"302" : "302 redirect!",
"404" : "404 app not find!"
},
'session' : lambda : lambda func : func,
'middlewares' : [],
'template_dir' : ".",
'mapping' : [('^/$', ('','example_app'))],
}
settings.update(config)
get_headers = settings.get("get_headers", get_headers)
get_req = settings.get("get_req", get_req)
get_resp = settings.get("get_resp", get_resp)
route = settings.get("route", route)
get_app = loop(settings.get("get_app", get_app), settings['middlewares'])
get_tpl = settings.get("get_tpl", get_tpl)
runserver = settings.get("runserver", runserver)
redirect = lambda url : get_resp(url, status='302')
render = lambda p, d : get_resp(get_tpl(p, d), content_type="text/html")
app_404 = settings.get("app_404", lambda : ['404 error'])
HTTP404Error = type('HTTP404Error', (Exception,), {})
example_app = lambda req: get_resp("hello!")
local = threading.local()
local.tplstream = ""
if __name__ == "__main__":
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-p", "--port", dest="port", type="int", default=8000, help="listen port")
(options, args) = parser.parse_args()
settings["http_host"] = "0.0.0.0:%d" % options.port
settings["port"] = options.port
runserver()