forked from marianoguerra/webless
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.py
81 lines (61 loc) · 2.01 KB
/
server.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
import sys
import Queue
sys.path.append('tubes')
try:
import tubes
except ImportError:
print "you need tubes to make it work"
print "http://github.com/marianoguerra/tubes"
sys.exit(-1)
import webless
handler = tubes.Handler()
handler.register_static_path('/css', 'css/')
handler.register_static_path('/js', 'js/')
counter = 0
scripts = {}
def run_script(url, script):
result = Queue.Queue()
browser = webless.Browserless(url)
def inject_fun(view, frame):
browser.inject_file('js/jquery.js')
browser.inject_file('js/json2.js')
browser.inject_script(script)
code = browser.get_code()
result.put(code)
browser.view.connect('load-finished', inject_fun)
while True:
webless.process_events()
try:
return result.get(True, 1.0)
except Queue.Empty:
pass
def run_script1(url, script):
result = run_script(url, script)
if result is None:
return tubes.Response('timeout', 408)
return result
@handler.get('^/?$', produces=tubes.HTML)
@handler.get('^/index.html$', produces=tubes.HTML)
def get_main(request):
return file('index.html')
@handler.get('^/(.*)/?$', produces=tubes.HTML)
def get_script(request, sid):
global scripts
if sid in scripts:
return run_script1(*scripts[sid])
return tubes.Response('not found', 404)
@handler.post('^/?$', produces=tubes.HTML, accepts=tubes.JSON)
def new_script(request, body):
global scripts, counter
if 'url' not in body or 'code' not in body:
return tubes.Response('Invalid request', 500)
scripts[str(counter)] = (body['url'], body['code'])
counter += 1
return '<a href="/%d">test your script</a>' % (counter - 1,)
@handler.post('^/test/?$', produces=tubes.HTML, accepts=tubes.JSON)
def test_script(request, body):
if 'url' not in body or 'code' not in body:
return tubes.Response('Invalid request', 500)
return run_script1(body['url'], body['code'])
if __name__ == '__main__':
tubes.run(handler)