Commit b44522e4 authored by Denis Bilenko's avatar Denis Bilenko

improve readability of the examples

parent a4e08d40
......@@ -8,12 +8,12 @@ results faster.
"""
from gevent import socket
from gevent import pool
from gevent.pool import Pool
N = 1000
# limit ourselves to max 10 simultaneous outstanding requests
p = pool.Pool(10)
pool = Pool(10)
finished = 0
......@@ -29,7 +29,7 @@ def job(url):
finished += 1
for x in xrange(10, N):
p.spawn(job, '%s.com' % x)
pool.spawn(job, '%s.com' % x)
p.join(timeout=2)
pool.join(timeout=2)
print 'finished within 2 seconds: %s/%s' % (finished, N)
......@@ -32,14 +32,14 @@ and then 'quit')
import gevent
from gevent import socket
def handle_socket(f):
def handle_socket(fileobj):
while True:
x = f.readline()
if not x:
line = fileobj.readline()
if not line:
break
f.write(x)
f.flush()
print "echoed", repr(x)
fileobj.write(line)
fileobj.flush()
print "echoed", repr(line)
print "client disconnected"
if __name__ == '__main__':
......
......@@ -6,14 +6,14 @@ WSGI interface is a safer choice, see examples/wsgiserver.py.
"""
from gevent import http
def callback(r):
print r
if r.uri == '/':
r.add_output_header('Content-Type', 'text/html')
r.send_reply(200, "OK", '<b>hello world</b>')
def callback(request):
print request
if request.uri == '/':
request.add_output_header('Content-Type', 'text/html')
request.send_reply(200, "OK", '<b>hello world</b>')
else:
r.add_output_header('Content-Type', 'text/html')
r.send_reply(404, "Not Found", "<h1>Not Found</h1>")
request.add_output_header('Content-Type', 'text/html')
request.send_reply(404, "Not Found", "<h1>Not Found</h1>")
print 'Serving on 8088...'
http.HTTPServer(callback).serve_forever(('0.0.0.0', 8088))
......@@ -10,8 +10,11 @@ from cgi import escape
from urllib import unquote
PORT = 8088
PROXY_URL = 'http://127.0.0.1:%s/' % PORT
def application(env, start_response):
proxy_url = 'http://127.0.0.1:%(SERVER_PORT)s/' % env
method = env['REQUEST_METHOD']
path = env['PATH_INFO']
if env['QUERY_STRING']:
......@@ -21,33 +24,11 @@ def application(env, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
return [FORM]
elif method == 'GET':
if '://' not in path:
path = 'http://' + path
try:
try:
r = urllib2.urlopen(path)
except urllib2.HTTPError, ex:
r = ex
print '%s: %s %s' % (path, r.code, r.msg)
headers = [(k, v) for (k, v) in r.headers.items() if k not in drop_headers]
parsed_path = urlparse(path)
host = (parsed_path.scheme or 'http') + '://' + parsed_path.netloc
except Exception, ex:
sys.stderr.write('error while reading %s:\n' % path)
traceback.print_exc()
tb = traceback.format_exc()
start_response('502 Bad Gateway', [('Content-Type', 'text/html')])
return ['<h1>%s</h1><h2>%s</h2><pre>%s</pre>' % (escape(str(ex) or ex.__class__.__name__ or 'Error'), escape(path), escape(tb))]
#for key, value in r.headers:
else:
start_response('%s %s' % (r.code, r.msg), headers)
data = r.read()
data = fix_links(data, proxy_url, host)
return [data]
return proxy(path, start_response)
elif (method, path) == ('POST', ''):
key, value = env['wsgi.input'].read().strip().split('=')
assert key == 'url', repr(key)
start_response('302 Found', [('Location', join(proxy_url, unquote(value)))])
start_response('302 Found', [('Location', join(PROXY_URL, unquote(value)))])
elif method == 'POST':
start_response('404 Not Found', [])
else:
......@@ -55,6 +36,31 @@ def application(env, start_response):
return []
def proxy(path, start_response):
if '://' not in path:
path = 'http://' + path
try:
try:
response = urllib2.urlopen(path)
except urllib2.HTTPError, ex:
response = ex
print '%s: %s %s' % (path, response.code, response.msg)
headers = [(k, v) for (k, v) in response.headers.items() if k not in drop_headers]
parsed_path = urlparse(path)
host = (parsed_path.scheme or 'http') + '://' + parsed_path.netloc
except Exception, ex:
sys.stderr.write('error while reading %s:\n' % path)
traceback.print_exc()
tb = traceback.format_exc()
start_response('502 Bad Gateway', [('Content-Type', 'text/html')])
error_str = escape(str(ex) or ex.__class__.__name__ or 'Error')
return ['<h1>%s</h1><h2>%s</h2><pre>%s</pre>' % (error_str, escape(path), escape(tb))]
else:
start_response('%s %s' % (response.code, response.msg), headers)
data = response.read()
data = fix_links(data, PROXY_URL, host)
return [data]
def join(url1, *rest):
if not rest:
......@@ -108,6 +114,6 @@ FORM = """<html><head>
if __name__ == '__main__':
#import doctest
#doctest.testmod()
print 'Serving on 8088...'
wsgi.WSGIServer(('', 8088), application).serve_forever()
print 'Serving on %s...' % PORT
wsgi.WSGIServer(('', PORT), application).serve_forever()
#!/usr/bin/python
"""A web.py application powered by gevent"""
from gevent import monkey; monkey.patch_all()
from gevent.wsgi import WSGIServer
import gevent
import web
urls = ("/", "index",
'/long', 'long_polling')
class index:
def GET(self):
return 'Hello, world!<br><a href="/long">/long</a>'
class long_polling:
# Since gevent.wsgi executes each incoming connection in a separate greenlet
# long running requests such as this one don't block one another;
# and thanks to "monkey.patch_all()" statement at the top, thread-local storage used by web.ctx
# becomes greenlet-local storage thus making requests isolated as they should be.
def GET(self):
print 'handling GET context id = %s' % (id(web.ctx._getd()), )
gevent.sleep(10) # possible to block the request indefinitely, without harming others
return 'Hello, 10 seconds later'
if __name__ == "__main__":
application = web.application(urls, globals()).wsgifunc()
print 'Serving on 8088...'
WSGIServer(('', 8088), application).serve_forever()
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment