[PATCH v2 08/10] trivial: Clean up 'views/xmlrpc.py'
Stephen Finucane
stephen.finucane at intel.com
Fri Oct 2 00:52:32 AEST 2015
From: Stephen Finucane <stephenfinucane at hotmail.com>
Resolve some issues with the aforementioned file. These are mostly
stylistic changes.
Signed-off-by: Stephen Finucane <stephenfinucane at hotmail.com>
---
patchwork/views/xmlrpc.py | 301 ++++++++++++++++++++++++----------------------
1 file changed, 157 insertions(+), 144 deletions(-)
diff --git a/patchwork/views/xmlrpc.py b/patchwork/views/xmlrpc.py
index c025c09..8715dea 100644
--- a/patchwork/views/xmlrpc.py
+++ b/patchwork/views/xmlrpc.py
@@ -21,17 +21,19 @@
#
from SimpleXMLRPCServer import SimpleXMLRPCDispatcher
-from django.http import HttpResponse, HttpResponseRedirect, \
- HttpResponseServerError
+import base64
+import sys
+import xmlrpclib
+
from django.core import urlresolvers
from django.contrib.auth import authenticate
+from django.http import (
+ HttpResponse, HttpResponseRedirect, HttpResponseServerError)
+from django.views.decorators.csrf import csrf_exempt
+
from patchwork.models import Patch, Project, Person, State
from patchwork.views import patch_to_mbox
-from django.views.decorators.csrf import csrf_exempt
-import sys
-import base64
-import xmlrpclib
class PatchworkXMLRPCDispatcher(SimpleXMLRPCDispatcher):
@@ -52,7 +54,6 @@ class PatchworkXMLRPCDispatcher(SimpleXMLRPCDispatcher):
def register_function(self, fn, auth_required):
self.func_map[fn.__name__] = (auth_required, fn)
-
def _user_for_request(self, request):
auth_header = None
@@ -62,23 +63,22 @@ class PatchworkXMLRPCDispatcher(SimpleXMLRPCDispatcher):
auth_header = request.META.get('Authorization')
if auth_header is None or auth_header == '':
- raise Exception("No authentication credentials given")
+ raise Exception('No authentication credentials given')
- str = auth_header.strip()
+ header = auth_header.strip()
- if not str.startswith('Basic '):
- raise Exception("Authentication scheme not supported")
+ if not header.startswith('Basic '):
+ raise Exception('Authentication scheme not supported')
- str = str[len('Basic '):].strip()
+ header = header[len('Basic '):].strip()
try:
- decoded = base64.decodestring(str)
+ decoded = base64.decodestring(header)
username, password = decoded.split(':', 1)
except:
- raise Exception("Invalid authentication credentials")
-
- return authenticate(username = username, password = password)
+ raise Exception('Invalid authentication credentials')
+ return authenticate(username=username, password=password)
def _dispatch(self, request, method, params):
if method not in self.func_map.keys():
@@ -89,7 +89,7 @@ class PatchworkXMLRPCDispatcher(SimpleXMLRPCDispatcher):
if auth_required:
user = self._user_for_request(request)
if not user:
- raise Exception("Invalid username/password")
+ raise Exception('Invalid username/password')
params = (user,) + params
@@ -108,20 +108,21 @@ class PatchworkXMLRPCDispatcher(SimpleXMLRPCDispatcher):
except:
# report exception back to server
response = self.dumps(
- xmlrpclib.Fault(1, "%s:%s" % (sys.exc_type, sys.exc_value)),
- )
+ xmlrpclib.Fault(1, '%s:%s' % (sys.exc_type, sys.exc_value)),
+ )
return response
dispatcher = PatchworkXMLRPCDispatcher()
# XMLRPC view function
+
+
@csrf_exempt
def xmlrpc(request):
if request.method != 'POST':
- return HttpResponseRedirect(
- urlresolvers.reverse('patchwork.views.help',
- kwargs = {'path': 'pwclient/'}))
+ return HttpResponseRedirect(urlresolvers.reverse(
+ 'patchwork.views.help', kwargs={'path': 'pwclient/'}))
response = HttpResponse()
try:
@@ -134,7 +135,9 @@ def xmlrpc(request):
# decorator for XMLRPC methods. Setting login_required to true will call
# the decorated function with a non-optional user as the first argument.
-def xmlrpc_method(login_required = False):
+
+
+def xmlrpc_method(login_required=False):
def wrap(f):
dispatcher.register_function(f, login_required)
return f
@@ -142,11 +145,11 @@ def xmlrpc_method(login_required = False):
return wrap
-
# We allow most of the Django field lookup types for remote queries
-LOOKUP_TYPES = ["iexact", "contains", "icontains", "gt", "gte", "lt",
- "in", "startswith", "istartswith", "endswith",
- "iendswith", "range", "year", "month", "day", "isnull" ]
+LOOKUP_TYPES = ['iexact', 'contains', 'icontains', 'gt', 'gte', 'lt',
+ 'in', 'startswith', 'istartswith', 'endswith',
+ 'iendswith', 'range', 'year', 'month', 'day', 'isnull']
+
#######################################################################
# Helper functions
@@ -155,12 +158,12 @@ LOOKUP_TYPES = ["iexact", "contains", "icontains", "gt", "gte", "lt",
def project_to_dict(obj):
"""Return a trimmed down dictionary representation of a Project
object which is OK to send to the client."""
- return \
- {
- 'id' : obj.id,
- 'linkname' : obj.linkname,
- 'name' : obj.name,
- }
+ return {
+ 'id': obj.id,
+ 'linkname': obj.linkname,
+ 'name': obj.name,
+ }
+
def person_to_dict(obj):
"""Return a trimmed down dictionary representation of a Person
@@ -173,71 +176,72 @@ def person_to_dict(obj):
else:
name = obj.email
- return \
- {
- 'id' : obj.id,
- 'email' : obj.email,
- 'name' : name,
- 'user' : unicode(obj.user).encode("utf-8"),
- }
+ return {
+ 'id': obj.id,
+ 'email': obj.email,
+ 'name': name,
+ 'user': unicode(obj.user).encode('utf-8'),
+ }
+
def patch_to_dict(obj):
"""Return a trimmed down dictionary representation of a Patch
object which is OK to send to the client."""
- return \
- {
- 'id' : obj.id,
- 'date' : unicode(obj.date).encode("utf-8"),
- 'filename' : obj.filename(),
- 'msgid' : obj.msgid,
- 'name' : obj.name,
- 'project' : unicode(obj.project).encode("utf-8"),
- 'project_id' : obj.project_id,
- 'state' : unicode(obj.state).encode("utf-8"),
- 'state_id' : obj.state_id,
- 'archived' : obj.archived,
- 'submitter' : unicode(obj.submitter).encode("utf-8"),
- 'submitter_id' : obj.submitter_id,
- 'delegate' : unicode(obj.delegate).encode("utf-8"),
- 'delegate_id' : max(obj.delegate_id, 0),
- 'commit_ref' : max(obj.commit_ref, ''),
- }
+ return {
+ 'id': obj.id,
+ 'date': unicode(obj.date).encode('utf-8'),
+ 'filename': obj.filename(),
+ 'msgid': obj.msgid,
+ 'name': obj.name,
+ 'project': unicode(obj.project).encode('utf-8'),
+ 'project_id': obj.project_id,
+ 'state': unicode(obj.state).encode('utf-8'),
+ 'state_id': obj.state_id,
+ 'archived': obj.archived,
+ 'submitter': unicode(obj.submitter).encode('utf-8'),
+ 'submitter_id': obj.submitter_id,
+ 'delegate': unicode(obj.delegate).encode('utf-8'),
+ 'delegate_id': max(obj.delegate_id, 0),
+ 'commit_ref': max(obj.commit_ref, ''),
+ }
+
def bundle_to_dict(obj):
"""Return a trimmed down dictionary representation of a Bundle
object which is OK to send to the client."""
- return \
- {
- 'id' : obj.id,
- 'name' : obj.name,
- 'n_patches' : obj.n_patches(),
- 'public_url' : obj.public_url(),
- }
+ return {
+ 'id': obj.id,
+ 'name': obj.name,
+ 'n_patches': obj.n_patches(),
+ 'public_url': obj.public_url(),
+ }
+
def state_to_dict(obj):
"""Return a trimmed down dictionary representation of a State
object which is OK to send to the client."""
- return \
- {
- 'id' : obj.id,
- 'name' : obj.name,
- }
+ return {
+ 'id': obj.id,
+ 'name': obj.name,
+ }
+
#######################################################################
# Public XML-RPC methods
#######################################################################
- at xmlrpc_method(False)
+ at xmlrpc_method()
def pw_rpc_version():
"""Return Patchwork XML-RPC interface version."""
return 1
- at xmlrpc_method(False)
-def project_list(search_str="", max_count=0):
+
+ at xmlrpc_method()
+def project_list(search_str='', max_count=0):
"""Get a list of projects matching the given filters."""
try:
if len(search_str) > 0:
- projects = Project.objects.filter(linkname__icontains = search_str)
+ projects = Project.objects.filter(linkname__icontains=search_str)
else:
projects = Project.objects.all()
@@ -245,25 +249,27 @@ def project_list(search_str="", max_count=0):
return map(project_to_dict, projects)[:max_count]
else:
return map(project_to_dict, projects)
- except:
+ except Project.DoesNotExist:
return []
- at xmlrpc_method(False)
+
+ at xmlrpc_method()
def project_get(project_id):
"""Return structure for the given project ID."""
try:
- project = Project.objects.filter(id = project_id)[0]
+ project = Project.objects.filter(id=project_id)[0]
return project_to_dict(project)
- except:
+ except Project.DoesNotExist:
return {}
- at xmlrpc_method(False)
+
+ at xmlrpc_method()
def person_list(search_str="", max_count=0):
"""Get a list of Person objects matching the given filters."""
try:
if len(search_str) > 0:
- people = (Person.objects.filter(name__icontains = search_str) |
- Person.objects.filter(email__icontains = search_str))
+ people = (Person.objects.filter(name__icontains=search_str) |
+ Person.objects.filter(email__icontains=search_str))
else:
people = Person.objects.all()
@@ -271,46 +277,50 @@ def person_list(search_str="", max_count=0):
return map(person_to_dict, people)[:max_count]
else:
return map(person_to_dict, people)
-
- except:
+ except Person.DoesNotExist:
return []
- at xmlrpc_method(False)
+
+ at xmlrpc_method()
def person_get(person_id):
"""Return structure for the given person ID."""
try:
- person = Person.objects.filter(id = person_id)[0]
+ person = Person.objects.filter(id=person_id)[0]
return person_to_dict(person)
- except:
+ except Person.DoesNotExist:
return {}
- at xmlrpc_method(False)
-def patch_list(filter={}):
+
+ at xmlrpc_method()
+def patch_list(filt=None):
"""Get a list of patches matching the given filters."""
+ if filt is None:
+ filt = {}
+
try:
# We allow access to many of the fields. But, some fields are
# filtered by raw object so we must lookup by ID instead over
# XML-RPC.
ok_fields = [
- "id",
- "name",
- "project_id",
- "submitter_id",
- "delegate_id",
- "archived",
- "state_id",
- "date",
- "commit_ref",
- "hash",
- "msgid",
- "max_count",
- ]
+ 'id',
+ 'name',
+ 'project_id',
+ 'submitter_id',
+ 'delegate_id',
+ 'archived',
+ 'state_id',
+ 'date',
+ 'commit_ref',
+ 'hash',
+ 'msgid',
+ 'max_count',
+ ]
dfilter = {}
max_count = 0
- for key in filter:
- parts = key.split("__")
+ for key in filt:
+ parts = key.split('__')
if parts[0] not in ok_fields:
# Invalid field given
return []
@@ -320,21 +330,17 @@ def patch_list(filter={}):
return []
if parts[0] == 'project_id':
- dfilter['project'] = Project.objects.filter(id =
- filter[key])[0]
+ dfilter['project'] = Project.objects.filter(id=filt[key])[0]
elif parts[0] == 'submitter_id':
- dfilter['submitter'] = Person.objects.filter(id =
- filter[key])[0]
+ dfilter['submitter'] = Person.objects.filter(id=filt[key])[0]
elif parts[0] == 'delegate_id':
- dfilter['delegate'] = Person.objects.filter(id =
- filter[key])[0]
+ dfilter['delegate'] = Person.objects.filter(id=filt[key])[0]
elif parts[0] == 'state_id':
- dfilter['state'] = State.objects.filter(id =
- filter[key])[0]
+ dfilter['state'] = State.objects.filter(id=filt[key])[0]
elif parts[0] == 'max_count':
- max_count = filter[key]
+ max_count = filt[key]
else:
- dfilter[key] = filter[key]
+ dfilter[key] = filt[key]
patches = Patch.objects.filter(**dfilter)
@@ -342,64 +348,69 @@ def patch_list(filter={}):
return map(patch_to_dict, patches[:max_count])
else:
return map(patch_to_dict, patches)
-
- except:
+ except Patch.DoesNotExist:
return []
- at xmlrpc_method(False)
+
+ at xmlrpc_method()
def patch_get(patch_id):
"""Return structure for the given patch ID."""
try:
- patch = Patch.objects.filter(id = patch_id)[0]
+ patch = Patch.objects.filter(id=patch_id)[0]
return patch_to_dict(patch)
- except:
+ except Patch.DoesNotExist:
return {}
- at xmlrpc_method(False)
+
+ at xmlrpc_method()
def patch_get_by_hash(hash):
"""Return structure for the given patch hash."""
try:
- patch = Patch.objects.filter(hash = hash)[0]
+ patch = Patch.objects.filter(hash=hash)[0]
return patch_to_dict(patch)
- except:
+ except Patch.DoesNotExist:
return {}
- at xmlrpc_method(False)
+
+ at xmlrpc_method()
def patch_get_by_project_hash(project, hash):
"""Return structure for the given patch hash."""
try:
- patch = Patch.objects.filter(project__linkname = project,
- hash = hash)[0]
+ patch = Patch.objects.filter(project__linkname=project,
+ hash=hash)[0]
return patch_to_dict(patch)
- except:
+ except Patch.DoesNotExist:
return {}
- at xmlrpc_method(False)
+
+ at xmlrpc_method()
def patch_get_mbox(patch_id):
"""Return mbox string for the given patch ID."""
try:
- patch = Patch.objects.filter(id = patch_id)[0]
+ patch = Patch.objects.filter(id=patch_id)[0]
return patch_to_mbox(patch).as_string(True)
- except:
- return ""
+ except Patch.DoesNotExist:
+ return ''
- at xmlrpc_method(False)
+
+ at xmlrpc_method()
def patch_get_diff(patch_id):
"""Return diff for the given patch ID."""
try:
- patch = Patch.objects.filter(id = patch_id)[0]
+ patch = Patch.objects.filter(id=patch_id)[0]
return patch.content
- except:
- return ""
+ except Patch.DoesNotExist:
+ return ''
+
- at xmlrpc_method(True)
+ at xmlrpc_method(login_required=True)
def patch_set(user, patch_id, params):
"""Update a patch with the key,value pairs in params. Only some parameters
can be set"""
try:
ok_params = ['state', 'commit_ref', 'archived']
- patch = Patch.objects.get(id = patch_id)
+ patch = Patch.objects.get(id=patch_id)
if not patch.is_editable(user):
raise Exception('No permissions to edit this patch')
@@ -409,7 +420,7 @@ def patch_set(user, patch_id, params):
continue
if k == 'state':
- patch.state = State.objects.get(id = v)
+ patch.state = State.objects.get(id=v)
else:
setattr(patch, k, v)
@@ -418,15 +429,16 @@ def patch_set(user, patch_id, params):
return True
- except:
+ except Patch.DoesNotExist:
raise
- at xmlrpc_method(False)
-def state_list(search_str="", max_count=0):
+
+ at xmlrpc_method()
+def state_list(search_str='', max_count=0):
"""Get a list of state structures matching the given search string."""
try:
if len(search_str) > 0:
- states = State.objects.filter(name__icontains = search_str)
+ states = State.objects.filter(name__icontains=search_str)
else:
states = State.objects.all()
@@ -434,14 +446,15 @@ def state_list(search_str="", max_count=0):
return map(state_to_dict, states)[:max_count]
else:
return map(state_to_dict, states)
- except:
+ except State.DoesNotExist:
return []
- at xmlrpc_method(False)
+
+ at xmlrpc_method()
def state_get(state_id):
"""Return structure for the given state ID."""
try:
- state = State.objects.filter(id = state_id)[0]
+ state = State.objects.filter(id=state_id)[0]
return state_to_dict(state)
- except:
+ except State.DoesNotExist:
return {}
--
2.0.0
More information about the Patchwork
mailing list