Skip to content

Commit

Permalink
Reindent everything to 4 spaces.
Browse files Browse the repository at this point in the history
  • Loading branch information
bdarnell committed Aug 10, 2010
1 parent 02d07de commit 9d4444e
Show file tree
Hide file tree
Showing 9 changed files with 186 additions and 190 deletions.
9 changes: 4 additions & 5 deletions tornado/httpclient.py
Expand Up @@ -62,7 +62,7 @@ def fetch(self, request, **kwargs):
If an error occurs during the fetch, we raise an HTTPError.
"""
if not isinstance(request, HTTPRequest):
request = HTTPRequest(url=request, **kwargs)
request = HTTPRequest(url=request, **kwargs)
buffer = cStringIO.StringIO()
headers = httputil.HTTPHeaders()
try:
Expand Down Expand Up @@ -175,7 +175,7 @@ def fetch(self, request, callback, **kwargs):
throw the exception (if any) in the callback.
"""
if not isinstance(request, HTTPRequest):
request = HTTPRequest(url=request, **kwargs)
request = HTTPRequest(url=request, **kwargs)
self._requests.append((request, stack_context.wrap(callback)))
self._process_queue()
self._set_timeout(0)
Expand Down Expand Up @@ -504,8 +504,8 @@ def _curl_setup_request(curl, request, buffer, headers):
curl.setopt(pycurl.URL, request.url)
# Request headers may be either a regular dict or HTTPHeaders object
if isinstance(request.headers, httputil.HTTPHeaders):
curl.setopt(pycurl.HTTPHEADER,
[_utf8("%s: %s" % i) for i in request.headers.get_all()])
curl.setopt(pycurl.HTTPHEADER,
[_utf8("%s: %s" % i) for i in request.headers.get_all()])
else:
curl.setopt(pycurl.HTTPHEADER,
[_utf8("%s: %s" % i) for i in request.headers.iteritems()])
Expand Down Expand Up @@ -630,4 +630,3 @@ def main():

if __name__ == "__main__":
main()

5 changes: 2 additions & 3 deletions tornado/httpserver.py
Expand Up @@ -212,8 +212,8 @@ def start(self, num_processes=1):
ioloop.IOLoop.READ)

def stop(self):
self.io_loop.remove_handler(self._socket.fileno())
self._socket.close()
self.io_loop.remove_handler(self._socket.fileno())
self._socket.close()

def _handle_events(self, fd, events):
while True:
Expand Down Expand Up @@ -451,4 +451,3 @@ def __repr__(self):
args = ", ".join(["%s=%r" % (n, getattr(self, n)) for n in attrs])
return "%s(%s, headers=%s)" % (
self.__class__.__name__, args, dict(self.headers))

147 changes: 73 additions & 74 deletions tornado/stack_context.py
Expand Up @@ -55,88 +55,87 @@ def die_on_error():
import threading

class _State(threading.local):
def __init__(self):
self.contexts = ()
def __init__(self):
self.contexts = ()
_state = _State()

@contextlib.contextmanager
def StackContext(context_factory):
'''Establishes the given context as a StackContext that will be transferred.
Note that the parameter is a callable that returns a context
manager, not the context itself. That is, where for a
non-transferable context manager you would say
with my_context():
StackContext takes the function itself rather than its result:
with StackContext(my_context):
'''
old_contexts = _state.contexts
try:
_state.contexts = old_contexts + (context_factory,)
with context_factory():
yield
finally:
_state.contexts = old_contexts
'''Establishes the given context as a StackContext that will be transferred.
Note that the parameter is a callable that returns a context
manager, not the context itself. That is, where for a
non-transferable context manager you would say
with my_context():
StackContext takes the function itself rather than its result:
with StackContext(my_context):
'''
old_contexts = _state.contexts
try:
_state.contexts = old_contexts + (context_factory,)
with context_factory():
yield
finally:
_state.contexts = old_contexts

@contextlib.contextmanager
def NullContext():
'''Resets the StackContext.
'''Resets the StackContext.
Useful when creating a shared resource on demand (e.g. an AsyncHTTPClient)
where the stack that caused the creating is not relevant to future
operations.
'''
old_contexts = _state.contexts
try:
_state.contexts = ()
yield
finally:
_state.contexts = old_contexts
Useful when creating a shared resource on demand (e.g. an AsyncHTTPClient)
where the stack that caused the creating is not relevant to future
operations.
'''
old_contexts = _state.contexts
try:
_state.contexts = ()
yield
finally:
_state.contexts = old_contexts

def wrap(fn, *args, **kwargs):
'''Returns a callable object that will resore the current StackContext
when executed.
Use this whenever saving a callback to be executed later in a
different execution context (either in a different thread or
asynchronously in the same thread).
As a convenience, also binds parameters to the given function
like functools.partial.
'''
# functools.wraps doesn't appear to work on functools.partial objects
#@functools.wraps(fn)
def wrapped(callback, contexts, *args, **kwargs):
# _state.contexts and contexts may share a common prefix.
# For each element of contexts not in that prefix, create a new
# StackContext object.
# TODO(bdarnell): do we want to be strict about the order,
# or is what we really want just set(contexts) - set(_state.contexts)?
# I think we do want to be strict about using identity comparison,
# so a set may not be quite right. Conversely, it's not very stack-like
# to have new contexts pop up in the middle, so would we want to
# ensure there are no existing contexts not in the stack being restored?
# That feels right, but given the difficulty of handling errors at this
# level I'm not going to check for it now.
pairs = itertools.izip(itertools.chain(_state.contexts,
itertools.repeat(None)),
contexts)
new_contexts = []
for old, new in itertools.dropwhile(lambda x: x[0] is x[1], pairs):
new_contexts.append(StackContext(new))
if new_contexts:
with contextlib.nested(*new_contexts):
callback(*args, **kwargs)
'''Returns a callable object that will resore the current StackContext
when executed.
Use this whenever saving a callback to be executed later in a
different execution context (either in a different thread or
asynchronously in the same thread).
As a convenience, also binds parameters to the given function
like functools.partial.
'''
# functools.wraps doesn't appear to work on functools.partial objects
#@functools.wraps(fn)
def wrapped(callback, contexts, *args, **kwargs):
# _state.contexts and contexts may share a common prefix.
# For each element of contexts not in that prefix, create a new
# StackContext object.
# TODO(bdarnell): do we want to be strict about the order,
# or is what we really want just set(contexts) - set(_state.contexts)?
# I think we do want to be strict about using identity comparison,
# so a set may not be quite right. Conversely, it's not very stack-like
# to have new contexts pop up in the middle, so would we want to
# ensure there are no existing contexts not in the stack being restored?
# That feels right, but given the difficulty of handling errors at this
# level I'm not going to check for it now.
pairs = itertools.izip(itertools.chain(_state.contexts,
itertools.repeat(None)),
contexts)
new_contexts = []
for old, new in itertools.dropwhile(lambda x: x[0] is x[1], pairs):
new_contexts.append(StackContext(new))
if new_contexts:
with contextlib.nested(*new_contexts):
callback(*args, **kwargs)
else:
callback(*args, **kwargs)
if getattr(fn, 'stack_context_wrapped', False):
return fn
if args or kwargs:
callback = functools.partial(fn, *args, **kwargs)
else:
callback(*args, **kwargs)
if getattr(fn, 'stack_context_wrapped', False):
return fn
if args or kwargs:
callback = functools.partial(fn, *args, **kwargs)
else:
callback = fn
contexts = _state.contexts
result = functools.partial(wrapped, callback, contexts, *args, **kwargs)
result.stack_context_wrapped = True
return result

callback = fn
contexts = _state.contexts
result = functools.partial(wrapped, callback, contexts, *args, **kwargs)
result.stack_context_wrapped = True
return result
2 changes: 1 addition & 1 deletion tornado/template.py
Expand Up @@ -170,7 +170,7 @@ def __init__(self, root_directory):
self.templates = {}

def reset(self):
self.templates = {}
self.templates = {}

def resolve_path(self, name, parent_path=None):
if parent_path and not parent_path.startswith("<") and \
Expand Down
54 changes: 27 additions & 27 deletions tornado/test/httpserver_test.py
Expand Up @@ -7,36 +7,36 @@
import urllib

class AuthRedirectRequestHandler(RequestHandler):
def initialize(self, login_url):
self.login_url = login_url
def initialize(self, login_url):
self.login_url = login_url

def get_login_url(self):
return self.login_url
def get_login_url(self):
return self.login_url

@authenticated
def get(self):
# we'll never actually get here because the test doesn't follow redirects
self.send_error(500)
@authenticated
def get(self):
# we'll never actually get here because the test doesn't follow redirects
self.send_error(500)

class AuthRedirectTest(AsyncHTTPTestCase, LogTrapTestCase):
def get_app(self):
return Application([('/relative', AuthRedirectRequestHandler,
dict(login_url='/login')),
('/absolute', AuthRedirectRequestHandler,
dict(login_url='http://example.com/login'))])
def get_app(self):
return Application([('/relative', AuthRedirectRequestHandler,
dict(login_url='/login')),
('/absolute', AuthRedirectRequestHandler,
dict(login_url='http://example.com/login'))])

def test_relative_auth_redirect(self):
self.http_client.fetch(self.get_url('/relative'), self.stop,
follow_redirects=False)
response = self.wait()
self.assertEqual(response.code, 302)
self.assertEqual(response.headers['Location'], '/login?next=%2Frelative')
def test_relative_auth_redirect(self):
self.http_client.fetch(self.get_url('/relative'), self.stop,
follow_redirects=False)
response = self.wait()
self.assertEqual(response.code, 302)
self.assertEqual(response.headers['Location'], '/login?next=%2Frelative')

def test_absolute_auth_redirect(self):
self.http_client.fetch(self.get_url('/absolute'), self.stop,
follow_redirects=False)
response = self.wait()
self.assertEqual(response.code, 302)
self.assertTrue(re.match(
'http://example.com/login\?next=http%3A%2F%2Flocalhost%3A[0-9]+%2Fabsolute',
response.headers['Location']), response.headers['Location'])
def test_absolute_auth_redirect(self):
self.http_client.fetch(self.get_url('/absolute'), self.stop,
follow_redirects=False)
response = self.wait()
self.assertEqual(response.code, 302)
self.assertTrue(re.match(
'http://example.com/login\?next=http%3A%2F%2Flocalhost%3A[0-9]+%2Fabsolute',
response.headers['Location']), response.headers['Location'])

0 comments on commit 9d4444e

Please sign in to comment.