Skip to content

Commit

Permalink
ignore: whitespace.
Browse files Browse the repository at this point in the history
  • Loading branch information
thruflo committed Aug 27, 2015
1 parent 43d26d7 commit f30536a
Show file tree
Hide file tree
Showing 24 changed files with 351 additions and 352 deletions.
30 changes: 15 additions & 15 deletions src/ntorque/api/auth.py
Expand Up @@ -29,53 +29,53 @@ class AuthenticationPolicy(CallbackAuthenticationPolicy):
"""A Pyramid authentication policy which obtains credential data from the
``request.headers['NTORQUE_API_KEY']``.
"""

def __init__(self, header_key='NTORQUE_API_KEY', **kwargs):
self.header_key = header_key
self.valid_key = kwargs.get('valid_key', VALID_API_KEY)

def unauthenticated_userid(self, request):
"""The ``api_key`` value found within the ``request.headers``."""

api_key = request.headers.get(self.header_key, None)
if api_key and self.valid_key.match(api_key):
return api_key.decode('utf8')

def remember(self, request, principal, **kw):
"""A no-op. There's no way to remember the user.
>>> policy = AuthenticationPolicy()
>>> policy.remember('req', 'ppl')
[]
"""

return []

def forget(self, request):
"""A no-op. There's no user to forget.
>>> policy = AuthenticationPolicy()
>>> policy.forget('req')
[]
"""

return []


class GetAuthenticatedApplication(object):
"""A Pyramid request method that looks up ``model.Application``s from the
``api_key`` provided by the ``AuthenticationPolicy``.
"""

def __init__(self, **kwargs):
self.get_app = kwargs.get('get_app', model.LookupApplication())
self.get_userid = kwargs.get('get_userid', unauthenticated_userid)

def __call__(self, request):
api_key = self.get_userid(request)
if api_key:
return self.get_app(api_key)


16 changes: 8 additions & 8 deletions src/ntorque/api/exc.py
Expand Up @@ -24,38 +24,38 @@ class MethodNotSupportedView(object):
"""Generic view exposed to throw 405 errors when endpoints are requested
with an unsupported request method.
"""

def __init__(self, request, **kwargs):
self.request = request
self.exc_cls = kwargs.get('exc_cls', httpexceptions.HTTPMethodNotAllowed)

def __call__(self):
raise self.exc_cls



@view_config(context=httpexceptions.HTTPError, renderer='string')
class HTTPErrorView(object):
def __init__(self, request):
self.request = request

def __call__(self):
request = self.request
settings = request.registry.settings
if settings.get('ntorque.mode') == 'development':
raise
return request.exception



@view_config(context=Exception, renderer='string')
class SystemErrorView(object):
"""Handle an internal system error."""

def __init__(self, request, **kwargs):
self.request = request
self.exc_cls = kwargs.get('exc_cls', httpexceptions.HTTPInternalServerError)

def __call__(self):
request = self.request
settings = request.registry.settings
Expand All @@ -64,5 +64,5 @@ def __call__(self):
raise
logger.error(request.exception, exc_info=True)
return self.exc_cls()


2 changes: 1 addition & 1 deletion src/ntorque/api/rate.py
@@ -1 +1 @@
# XXX todo: rate limits.
# XXX todo: rate limits.
14 changes: 7 additions & 7 deletions src/ntorque/api/tree.py
Expand Up @@ -18,33 +18,33 @@

class APIRoot(root.TraversalRoot):
"""Support ``tasks`` traversal."""

def __init__(self, *args, **kwargs):
super(APIRoot, self).__init__(*args, **kwargs)
self.tasks_root = kwargs.get('tasks_root', TaskRoot)

def __getitem__(self, key):
if key == 'tasks':
return self.tasks_root(self.request, key=key, parent=self)
raise KeyError(key)


class TaskRoot(root.TraversalRoot):
"""Lookup tasks by ID."""

def __init__(self, *args, **kwargs):
super(TaskRoot, self).__init__(*args, **kwargs)
self.get_task = kwargs.get('get_task', model.LookupTask())
self.valid_id = kwargs.get('valid_id', VALID_INT)

def __getitem__(self, key):
"""Lookup task by ID and, if found, make sure the task is locatable."""

if self.valid_id.match(key):
int_id = int(key)
context = self.get_task(int_id)
if context:
return self.locatable(context, key)
raise KeyError(key)


30 changes: 15 additions & 15 deletions src/ntorque/api/view.py
Expand Up @@ -23,21 +23,21 @@
URL_PATTERN = r"""(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))"""

VALID_INT = re.compile(r'^[0-9]+$')
VALID_URL = re.compile(URL_PATTERN)
VALID_URL = re.compile(URL_PATTERN)

@view_config(context=tree.APIRoot, permission=NO_PERMISSION_REQUIRED,
request_method='GET', renderer='string')
def installed_view(object):
"""``POST /`` endpoint."""

return u'Torque installed and reporting for duty, sir!'


@view_config(context=tree.APIRoot, permission='create', request_method='POST',
renderer='string')
class EnqueTask(object):
"""``POST /`` endpoint."""

def __init__(self, request, **kwargs):
self.request = request
self.bad_request = kwargs.get('bad_request', httpexceptions.HTTPBadRequest)
Expand All @@ -47,14 +47,14 @@ def __init__(self, request, **kwargs):
self.valid_int = kwargs.get('valid_int', VALID_INT)
self.valid_methods = kwargs.get('valid_methods', constants.REQUEST_METHODS)
self.valid_url = kwargs.get('valid_url', VALID_URL)

def __call__(self):
"""Validate, store the task and return a 201 response."""

# Unpack.
request = self.request
settings = request.registry.settings

# Validate.
# - url
url = request.GET.get('url', None)
Expand Down Expand Up @@ -87,26 +87,26 @@ def __call__(self):
response.status_int = 201
response.headers['Location'] = request.resource_url(task)[:-1]
return ''


@view_config(context=model.Task, permission='view', request_method='GET',
renderer='json')
class TaskStatus(object):
"""``GET /tasks/task:id`` endpoint."""

def __init__(self, request, **kwargs):
self.request = request

def __call__(self):
"""Validate, store the task and return a 201 response."""

# Unpack.
request = self.request
task = request.context

# Return a 200 response with a JSON repr of the task.
return task


@view_config(context=model.Task, name='push', permission='view',
request_method='POST', renderer='json')
Expand All @@ -116,14 +116,14 @@ class PushTask(object):
def __init__(self, request, **kwargs):
self.request = request
self.push_notify = kwargs.get('push_notify', model.PushTaskNotification(request))

def __call__(self):
"""Push the task onto the queue."""

# Unpack.
request = self.request
task = request.context

# Notify.
self.push_notify(task)

Expand Down
46 changes: 23 additions & 23 deletions src/ntorque/backoff.py
Expand Up @@ -2,7 +2,7 @@

"""Provides ``Backoff``, a numerical value adapter that provides ``linear()`` and
``exponential()`` backoff value calculation::
>>> b = Backoff(1)
>>> b.linear()
2
Expand All @@ -12,37 +12,37 @@
6
>>> b.exponential()
12
The default linear increment is the start value::
>>> b = Backoff(2)
>>> b.linear()
4
>>> b.linear()
6
You can override this by passing an ``incr`` kwarg to the constructor::
>>> b = Backoff(10, incr=2)
>>> b.linear()
12
You can override this by passing an arg to the linear method::
>>> b.linear(4)
16
The default exponential factor is ``2``. You can override this by providing
a ``factor`` kwarg to the constructor, or an arg to the method::
>>> b = Backoff(1, factor=3)
>>> b.exponential()
3
>>> b.exponential(1.5)
4.5
Both can be limited to a maximum value::
>>> b = Backoff(1, max_value=2)
>>> b.linear()
2
Expand All @@ -53,7 +53,7 @@
4
>>> b.exponential()
5
"""

__all__ = [
Expand All @@ -67,45 +67,45 @@ class Backoff(object):
"""Adapts a ``start_value`` to provide ``linear()`` and ``exponential()``
backoff value calculation.
"""

def __init__(self, start_value, factor=2, incr=None, max_value=None):
"""Store the ``value`` and setup the defaults, using the start value
as the default increment if not provided.
"""

if incr is None:
incr = start_value
if max_value is None:
max_value = float('inf')

self.default_factor = factor
self.default_incr = incr
self.max_value = max_value
self.value = start_value

def limit(self, value):
if value > self.max_value:
return self.max_value
return value

def linear(self, incr=None):
"""Add ``incr`` to the current value."""

if incr is None:
incr = self.default_incr

value = self.value + incr
self.value = self.limit(value)
return self.value

def exponential(self, factor=None):
"""Multiple the current value by (fraction * itself)."""

if factor is None:
factor = self.default_factor

value = self.value * factor
self.value = self.limit(value)
return self.value


0 comments on commit f30536a

Please sign in to comment.