-
Notifications
You must be signed in to change notification settings - Fork 550
/
Copy pathproxy.py
78 lines (63 loc) · 2.43 KB
/
proxy.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
#!/usr/bin/env python
# coding: utf-8
import time
import hashlib
import tornado
import tornado.ioloop
import tornado.web
from tornado import gen, httpclient, ioloop
from tornado.options import define, options
define("port", default=8200, help="Run server on a specific port", type=int)
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, proxy")
class ProxyHandler(tornado.web.RequestHandler):
http_client = httpclient.AsyncHTTPClient()
@gen.coroutine
def get(self, url):
print time.strftime('%Y-%m-%d %H:%M:%S'), 'PROXY http://' + url
response = yield self.http_client.fetch('http://'+url) #www.google.com')
# print response.body
if (response.error and not
isinstance(response.error, tornado.httpclient.HTTPError)):
self.set_status(500)
self.write('Internal server error:\n' + str(response.error))
else:
self.set_status(response.code, response.reason)
for header, v in response.headers.get_all():
if header not in ('Content-Length', 'Transfer-Encoding', 'Content-Encoding', 'Connection'):
self.set_header(header, v) # some header appear multiple times, eg 'Set-Cookie'
if response.body:
self.set_header('Content-Length', len(response.body))
self.write(response.body)
self.finish()
class PlistStoreHandler(tornado.web.RequestHandler):
db = {}
def post(self):
body = self.request.body
if len(body) > 5000:
self.set_status(500)
self.finish("request body too long")
m = hashlib.md5()
m.update(body)
key = m.hexdigest()[8:16]
self.db[key] = body
self.write({'key': key})
def get(self):
key = self.get_argument('key')
value = self.db.get(key)
if value is None:
raise tornado.web.HTTPError(404)
self.set_header('Content-Type', 'text/xml')
self.finish(value)
def make_app(debug=True):
return tornado.web.Application([
(r"/", MainHandler),
(r"/proxy/(.*)", ProxyHandler),
(r"/plist", PlistStoreHandler),
], debug=debug)
if __name__ == "__main__":
app = make_app()
tornado.options.parse_command_line()
app.listen(options.port)
ioloop.IOLoop.current().start()