Commits

David Guaraglia  committed 557f2ba

Initial PyFlakes/FixWhitespace run

  • Participants
  • Parent commits c4b2d21

Comments (0)

Files changed (9)

File piston/__init__.py

 except ImportError:
     # don't prevent use of paste if pkg_resources isn't installed
     from pkgutil import extend_path
-    __path__ = extend_path(__path__, __name__) 
+    __path__ = extend_path(__path__, __name__)
 
 try:
     import modulefinder

File piston/decorator.py

 
 __all__ = ["decorator", "new_wrapper", "getinfo"]
 
-import inspect, sys
+import inspect
 
 try:
     set
     - doc (the docstring : str)
     - module (the module name : str)
     - dict (the function __dict__ : str)
-    
+
     >>> def f(self, x=1, y=2, *args, **kw): pass
 
     >>> info = getinfo(f)
     'f'
     >>> info["argnames"]
     ['self', 'x', 'y', 'args', 'kw']
-    
+
     >>> info["defaults"]
     (1, 2)
 
 def new_wrapper(wrapper, model):
     """
     An improvement over functools.update_wrapper. The wrapper is a generic
-    callable object. It works by generating a copy of the wrapper with the 
+    callable object. It works by generating a copy of the wrapper with the
     right signature and by updating the copy, not the original.
     Moreovoer, 'model' can be a dictionary with keys 'name', 'doc', 'module',
     'dict', 'defaults'.
      def caller(func, *args, **kw):
          # do something
          return func(*args, **kw)
-    
+
     Here is an example of usage:
 
     >>> @decorator
 
     >>> chatty.__name__
     'chatty'
-    
+
     >>> @chatty
     ... def f(): pass
     ...
     import doctest; doctest.testmod()
 
 ##########################     LEGALESE    ###############################
-      
-##   Redistributions of source code must retain the above copyright 
+
+##   Redistributions of source code must retain the above copyright
 ##   notice, this list of conditions and the following disclaimer.
 ##   Redistributions in bytecode form must reproduce the above copyright
 ##   notice, this list of conditions and the following disclaimer in
 ##   the documentation and/or other materials provided with the
-##   distribution. 
+##   distribution.
 
 ##   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 ##   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT

File piston/doc.py

 import inspect, handler
 
-from piston.handler import typemapper
 from piston.handler import handler_tracker
 
 from django.core.urlresolvers import get_resolver, get_callable, get_script_prefix
     """
     if isinstance(type(handler_cls), handler.HandlerMetaClass):
         raise ValueError("Give me handler, not %s" % type(handler_cls))
-        
+
     return HandlerDocumentation(handler_cls)
-    
+
 class HandlerMethod(object):
     def __init__(self, method, stale=False):
         self.method = method
         self.stale = stale
-        
+
     def iter_args(self):
         args, _, _, defaults = inspect.getargspec(self.method)
 
                 yield (arg, str(defaults[-didx]))
             else:
                 yield (arg, None)
-        
+
     @property
     def signature(self, parse_optional=True):
         spec = ""
 
         for argn, argdef in self.iter_args():
             spec += argn
-            
+
             if argdef:
                 spec += '=%s' % argdef
-            
+
             spec += ', '
-            
+
         spec = spec.rstrip(", ")
-        
+
         if parse_optional:
             return spec.replace("=None", "=<optional>")
-            
+
         return spec
-        
+
     @property
     def doc(self):
         return inspect.getdoc(self.method)
-    
+
     @property
     def name(self):
         return self.method.__name__
-    
+
     @property
     def http_name(self):
         if self.name == 'read':
             return 'DELETE'
         elif self.name == 'update':
             return 'PUT'
-    
+
     def __repr__(self):
         return "<Method: %s>" % self.name
-    
+
 class HandlerDocumentation(object):
     def __init__(self, handler):
         self.handler = handler
-        
+
     def get_methods(self, include_default=False):
         for method in "read create update delete".split():
             met = getattr(self.handler, method, None)
 
             if not met:
                 continue
-                
+
             stale = inspect.getmodule(met.im_func) is not inspect.getmodule(self.handler)
 
             if not self.handler.is_anonymous:
             else:
                 if not stale or met.__name__ == "read" \
                     and 'GET' in self.allowed_methods:
-                    
+
                     yield HandlerMethod(met, stale)
-        
+
     def get_all_methods(self):
         return self.get_methods(include_default=True)
-        
+
     @property
     def is_anonymous(self):
         return self.handler.is_anonymous
 
     def get_model(self):
         return getattr(self, 'model', None)
-            
+
     @property
     def has_anonymous(self):
         return self.handler.anonymous
-            
+
     @property
     def anonymous(self):
         if self.has_anonymous:
             return HandlerDocumentation(self.handler.anonymous)
-            
+
     @property
     def doc(self):
         return self.handler.__doc__
-    
+
     @property
     def name(self):
         return self.handler.__name__
-    
+
     @property
     def allowed_methods(self):
         return self.handler.allowed_methods
-    
+
     def get_resource_uri_template(self):
         """
         URI template processor.
-        
+
         See http://bitworking.org/projects/URI-Templates/
         """
         def _convert(template, params=[]):
             """URI template converter"""
             paths = template % dict([p, "{%s}" % p] for p in params)
             return u'%s%s' % (get_script_prefix(), paths)
-        
+
         try:
             resource_uri = self.handler.resource_uri()
-            
+
             components = [None, [], {}]
 
             for i, value in enumerate(resource_uri):
                 components[i] = value
-        
+
             lookup_view, args, kwargs = components
             lookup_view = get_callable(lookup_view, True)
 
             possibilities = get_resolver(None).reverse_dict.getlist(lookup_view)
-            
+
             for possibility, pattern in possibilities:
                 for result, params in possibility:
                     if args:
                         return _convert(result, params)
         except:
             return None
-        
+
     resource_uri_template = property(get_resource_uri_template)
-    
+
     def __repr__(self):
         return u'<Documentation for "%s">' % self.name
 
     """
     docs = [ ]
 
-    for handler in handler_tracker: 
+    for handler in handler_tracker:
         docs.append(generate_doc(handler))
 
-    def _compare(doc1, doc2): 
+    def _compare(doc1, doc2):
        #handlers and their anonymous counterparts are put next to each other.
        name1 = doc1.name.replace("Anonymous", "")
        name2 = doc2.name.replace("Anonymous", "")
-       return cmp(name1, name2)    
- 
+       return cmp(name1, name2)
+
     docs.sort(_compare)
-       
-    return render_to_response('documentation.html', 
+
+    return render_to_response('documentation.html',
         { 'docs': docs }, RequestContext(request))

File piston/emitters.py

 from __future__ import generators
 
 import decimal, re, inspect
-import copy
 
 try:
     # yaml isn't standard with python.  It shouldn't be required if it
 from django.utils import simplejson
 from django.utils.xmlutils import SimplerXMLGenerator
 from django.utils.encoding import smart_unicode
-from django.core.urlresolvers import reverse, NoReverseMatch
+from django.core.urlresolvers import NoReverseMatch
 from django.core.serializers.json import DateTimeAwareJSONEncoder
 from django.http import HttpResponse
 from django.core import serializers
                 v = lambda f: getattr(data, f.attname)
 
                 if handler:
-                    fields = getattr(handler, 'fields')    
-                
+                    fields = getattr(handler, 'fields')
+
                 if not fields or hasattr(handler, 'fields'):
                     """
                     Fields was not specified, try to find teh correct
                     if not get_fields:
                         get_fields = set([ f.attname.replace("_id", "", 1)
                             for f in data._meta.fields + data._meta.virtual_fields])
-                    
+
                     if hasattr(mapped, 'extra_fields'):
                         get_fields.update(mapped.extra_fields)
 

File piston/models.py

 from django.db.models.signals import post_save, post_delete
 from django.db import models
 from django.contrib.auth.models import User
-from django.core.mail import send_mail, mail_admins
 
 # Piston imports
-from managers import TokenManager, ConsumerManager, ResourceManager
+from managers import TokenManager, ConsumerManager
 from signals import consumer_post_save, consumer_post_delete
 
 KEY_SIZE = 18
     token_key = models.CharField(max_length=KEY_SIZE)
     consumer_key = models.CharField(max_length=KEY_SIZE)
     key = models.CharField(max_length=255)
-    
+
     def __unicode__(self):
         return u"Nonce %s for %s" % (self.key, self.consumer_key)
 
     user = models.ForeignKey(User, null=True, blank=True, related_name='consumers')
 
     objects = ConsumerManager()
-        
+
     def __unicode__(self):
         return u"Consumer %s with key %s" % (self.name, self.key)
 
     def generate_random_codes(self):
         """
         Used to generate random key/secret pairings. Use this after you've
-        added the other data in place of save(). 
+        added the other data in place of save().
 
         c = Consumer()
-        c.name = "My consumer" 
+        c.name = "My consumer"
         c.description = "An app that makes ponies from the API."
         c.user = some_user_object
         c.generate_random_codes()
     REQUEST = 1
     ACCESS = 2
     TOKEN_TYPES = ((REQUEST, u'Request'), (ACCESS, u'Access'))
-    
+
     key = models.CharField(max_length=KEY_SIZE)
     secret = models.CharField(max_length=SECRET_SIZE)
     verifier = models.CharField(max_length=VERIFIER_SIZE)
     token_type = models.IntegerField(choices=TOKEN_TYPES)
     timestamp = models.IntegerField(default=long(time.time()))
     is_approved = models.BooleanField(default=False)
-    
+
     user = models.ForeignKey(User, null=True, blank=True, related_name='tokens')
     consumer = models.ForeignKey(Consumer)
-    
+
     callback = models.CharField(max_length=255, null=True, blank=True)
     callback_confirmed = models.BooleanField(default=False)
-    
+
     objects = TokenManager()
-    
+
     def __unicode__(self):
         return u"%s Token %s for %s" % (self.get_token_type_display(), self.key, self.consumer)
 
     def to_string(self, only_key=False):
         token_dict = {
-            'oauth_token': self.key, 
+            'oauth_token': self.key,
             'oauth_token_secret': self.secret,
             'oauth_callback_confirmed': 'true',
         }
         self.key = key
         self.secret = secret
         self.save()
-        
+
     # -- OAuth 1.0a stuff
 
     def get_callback_url(self):
             return urlparse.urlunparse((scheme, netloc, path, params,
                 query, fragment))
         return self.callback
-    
+
     def set_callback(self, callback):
         if callback != "oob": # out of band, says "we can't do this!"
             self.callback = callback

File piston/resource.py

-import sys, inspect
+import sys
 
 from django.http import (HttpResponse, Http404, HttpResponseNotAllowed,
-    HttpResponseForbidden, HttpResponseServerError)
+    HttpResponseServerError)
 from django.views.debug import ExceptionReporter
 from django.views.decorators.vary import vary_on_headers
 from django.conf import settings
-from django.core.mail import send_mail, EmailMessage
+from django.core.mail import EmailMessage
 from django.db.models.query import QuerySet
-from django.http import Http404
 
 from emitters import Emitter
 from handler import typemapper
 
     def form_validation_response(self, e):
         """
-        Method to return form validation error information. 
+        Method to return form validation error information.
         You will probably want to override this in your own
         `Resource` subclass.
         """
         status_code = 200
 
         # If we're looking at a response object which contains non-string
-        # content, then assume we should use the emitter to format that 
+        # content, then assume we should use the emitter to format that
         # content
         if isinstance(result, HttpResponse) and not result._is_string:
             status_code = result.status_code
             # Note: We can't use result.content here because that method attempts
-            # to convert the content into a string which we don't want. 
+            # to convert the content into a string which we don't want.
             # when _is_string is False _container is the raw data
             result = result._container
-     
+
         srl = emitter(result, typemapper, handler, fields, anonymous)
 
         try:
 
     def error_handler(self, e, request, meth, em_format):
         """
-        Override this method to add handling of errors customized for your 
+        Override this method to add handling of errors customized for your
         needs
         """
         if isinstance(e, FormValidationError):
 
         elif isinstance(e, HttpStatusCode):
             return e.response
- 
-        else: 
+
+        else:
             """
             On errors (like code errors), we'd like to be able to
             give crash reports to both admins and also the calling

File piston/signals.py

 # Django imports
-import django.dispatch 
 
 # Piston imports
 from utils import send_consumer_mail

File piston/test.py

 
 # Piston imports
 from piston import oauth
-from piston.models import Consumer, Token
 
 # 3rd/Python party imports
-import httplib2, urllib, cgi
+import cgi
 
 URLENCODED_FORM_CONTENT = 'application/x-www-form-urlencoded'
 
         url = "http://testserver" + request['PATH_INFO']
 
         req = oauth.OAuthRequest.from_consumer_and_token(
-            self.consumer, token=self.token, 
-            http_method=request['REQUEST_METHOD'], http_url=url, 
+            self.consumer, token=self.token,
+            http_method=request['REQUEST_METHOD'], http_url=url,
             parameters=params
         )
 
 
         if isinstance(data, dict):
             data = urlencode(data)
-        
+
         return super(OAuthClient, self).post(path, data, content_type, follow, **extra)
 
 class TestCase(test.TestCase):

File piston/utils.py

 import time
-from django.http import HttpResponseNotAllowed, HttpResponseForbidden, HttpResponse, HttpResponseBadRequest
-from django.core.urlresolvers import reverse
+from django.http import HttpResponse
 from django.core.cache import cache
 from django import get_version as django_version
 from django.core.mail import send_mail, mail_admins
 from django.contrib.sites.models import Site
 from decorator import decorator
 
-from datetime import datetime, timedelta
-
 __version__ = '0.2.3rc1'
 
 def get_version():