PEP8 of most of the API app

This commit is contained in:
2010-10-26 09:02:05 +01:00
parent 8823217066
commit dee89dff68
6 changed files with 48 additions and 45 deletions

View File

@@ -1,13 +1,15 @@
from django.contrib import admin from django.contrib import admin
from api.models import AuthAPIKey, AuthAPILog from api.models import AuthAPIKey, AuthAPILog
class AuthAPIKeyAdmin(admin.ModelAdmin): class AuthAPIKeyAdmin(admin.ModelAdmin):
list_display = ('key', 'name', 'url', 'active') list_display = ('key', 'name', 'url', 'active')
search_fields = ['name'] search_fields = ['name']
admin.site.register(AuthAPIKey, AuthAPIKeyAdmin)
class AuthAPILogAdmin(admin.ModelAdmin): class AuthAPILogAdmin(admin.ModelAdmin):
list_display = ('key', 'url', 'access_datetime') list_display = ('key', 'url', 'access_datetime')
admin.site.register(AuthAPIKey, AuthAPIKeyAdmin)
admin.site.register(AuthAPILog, AuthAPILogAdmin) admin.site.register(AuthAPILog, AuthAPILogAdmin)

View File

@@ -2,12 +2,13 @@ from django.http import HttpResponseForbidden
from django.contrib.auth.models import AnonymousUser from django.contrib.auth.models import AnonymousUser
from api.models import AuthAPIKey from api.models import AuthAPIKey
class APIKeyAuthentication(object): class APIKeyAuthentication(object):
def is_authenticated(self, request): def is_authenticated(self, request):
params = {} params = {}
for key,value in request.GET.items(): for key, value in request.GET.items():
params[key.lower()] = value params[key.lower()] = value
if 'apikey' in params: if 'apikey' in params:
@@ -24,4 +25,3 @@ class APIKeyAuthentication(object):
def challenge(self): def challenge(self):
return HttpResponseForbidden('Access Denied, use a API Key') return HttpResponseForbidden('Access Denied, use a API Key')

View File

@@ -30,25 +30,25 @@ class UserHandler(BaseHandler):
try: try:
u = User.objects.get(id=id) u = User.objects.get(id=id)
except (User.DoesNotExist, ValueError): except (User.DoesNotExist, ValueError):
return { 'auth': 'missing', 'missing': 'userid'} return {'auth': 'missing', 'missing': 'userid'}
elif 'user' in request.GET: elif 'user' in request.GET:
try: try:
u = User.objects.get(username=request.GET['user']) u = User.objects.get(username=request.GET['user'])
except User.DoesNotExist: except User.DoesNotExist:
return { 'auth': 'missing', 'missing': 'username'} return {'auth': 'missing', 'missing': 'username'}
elif 'serviceuid' in request.GET: elif 'serviceuid' in request.GET:
try: try:
u = ServiceAccount.objects.get(service_uid=request.GET['serviceuid']).user u = ServiceAccount.objects.get(service_uid=request.GET['serviceuid']).user
except ServiceAccount.DoesNotExist: except ServiceAccount.DoesNotExist:
return { 'auth': 'missing', 'missing': 'ServiceAccount'} return {'auth': 'missing', 'missing': 'ServiceAccount'}
chars = [] chars = []
for a in u.eveaccount_set.all(): for a in u.eveaccount_set.all():
chars.extend(a.characters.all()) chars.extend(a.characters.all())
d = { 'id': u.id, 'username': u.username, 'email': u.email, d = {'id': u.id, 'username': u.username, 'email': u.email,
'serviceaccounts': u.serviceaccount_set.all(), 'characters': chars, 'serviceaccounts': u.serviceaccount_set.all(), 'characters': chars,
'groups': u.groups.all(), 'staff': u.is_staff, 'superuser': u.is_superuser } 'groups': u.groups.all(), 'staff': u.is_staff, 'superuser': u.is_superuser}
return d return d
@@ -63,23 +63,23 @@ class LoginHandler(BaseHandler):
try: try:
u = User.objects.get(id=id) u = User.objects.get(id=id)
except (User.DoesNotExist, ValueError): except (User.DoesNotExist, ValueError):
return { 'auth': 'missing', 'missing': 'UserID' } return {'auth': 'missing', 'missing': 'UserID'}
if request.GET.get('user', None): if request.GET.get('user', None):
try: try:
u = User.objects.get(username=request.GET['user']) u = User.objects.get(username=request.GET['user'])
except User.DoesNotExist: except User.DoesNotExist:
return { 'auth': 'missing', 'missing': 'Username' } return {'auth': 'missing', 'missing': 'Username'}
if u: if u:
if request.GET.get('pass', None) and request.GET['pass'] == u.get_profile().api_service_password: if request.GET.get('pass', None) and request.GET['pass'] == u.get_profile().api_service_password:
return { 'auth': 'ok', 'id': u.id, 'username': u.username, return {'auth': 'ok', 'id': u.id, 'username': u.username,
'email': u.email, 'groups': u.groups.all(), 'email': u.email, 'groups': u.groups.all(),
'staff': u.is_staff, 'superuser': u.is_superuser } 'staff': u.is_staff, 'superuser': u.is_superuser}
else: else:
return { 'auth': 'failed' } return {'auth': 'failed'}
return { 'auth': 'missing', 'missing': 'all' } return {'auth': 'missing', 'missing': 'all'}
class EveAPIHandler(BaseHandler): class EveAPIHandler(BaseHandler):
@@ -87,25 +87,26 @@ class EveAPIHandler(BaseHandler):
exclude = ('api_key') exclude = ('api_key')
def read(self, request): def read(self, request):
if request.GET.get('id', None): if request.GET.get('id', None):
s = get_object_or_404(EVEAccount, pk=id) s = get_object_or_404(EVEAccount, pk=id)
elif request.GET.get('userid', None): elif request.GET.get('userid', None):
s = EVEAccount.objects.filter(user=request.GET['userid']) s = EVEAccount.objects.filter(user=request.GET['userid'])
elif request.GET.get('corpid', None): elif request.GET.get('corpid', None):
s = EVEAccount.objects.filter(characters__corporation__id=request.GET['corpid']) s = EVEAccount.objects.filter(characters__corporation__id=request.GET['corpid'])
elif request.GET.get('allianceid', None): elif request.GET.get('allianceid', None):
s = EVEAccount.objects.filter(characters__corporation__alliance__id=request.GET['allianceid']) s = EVEAccount.objects.filter(characters__corporation__alliance__id=request.GET['allianceid'])
return {'keys': s.values('id', 'user_id', 'api_status', 'api_last_updated')}
return { 'keys': s.values('id', 'user_id', 'api_status', 'api_last_updated') }
class EveAPIProxyHandler(BaseHandler): class EveAPIProxyHandler(BaseHandler):
allowed_methods = ('GET') allowed_methods = ('GET')
def read(self, request): def read(self, request):
url_path = request.META['PATH_INFO'].replace(reverse('api-eveapiproxy'),"/") url_path = request.META['PATH_INFO'].replace(reverse('api-eveapiproxy'), "/")
params = {} params = {}
for key,value in request.GET.items(): for key, value in request.GET.items():
params[key.lower()] = value params[key.lower()] = value
if 'userid' in params: if 'userid' in params:
@@ -116,13 +117,14 @@ class EveAPIProxyHandler(BaseHandler):
return HttpResponse(cached_doc.body) return HttpResponse(cached_doc.body)
class OpTimerHandler(BaseHandler): class OpTimerHandler(BaseHandler):
allowed_methods = ('GET') allowed_methods = ('GET')
def read(self, request, id=None): def read(self, request, id=None):
obj = get_object_or_404(EVEAccount, id=FULL_API_USER_ID) obj = get_object_or_404(EVEAccount, id=FULL_API_USER_ID)
params = {'userID':obj.id,'apiKey':obj.api_key,'characterID':FULL_API_CHARACTER_ID} params = {'userID': obj.id, 'apiKey': obj.api_key, 'characterID': FULL_API_CHARACTER_ID}
cached_doc = CachedDocument.objects.api_query('/char/UpcomingCalendarEvents.xml.aspx', params, exceptions=False) cached_doc = CachedDocument.objects.api_query('/char/UpcomingCalendarEvents.xml.aspx', params, exceptions=False)
@@ -130,7 +132,7 @@ class OpTimerHandler(BaseHandler):
dom = minidom.parseString(cached_doc.body.encode('utf-8')) dom = minidom.parseString(cached_doc.body.encode('utf-8'))
enode = dom.getElementsByTagName('error') enode = dom.getElementsByTagName('error')
if not cached_doc or enode: if not cached_doc or enode:
return {'ops':[{ return {'ops': [{
'startsIn': -1, 'startsIn': -1,
'eventID': 0, 'eventID': 0,
'ownerName': '', 'ownerName': '',
@@ -140,8 +142,7 @@ class OpTimerHandler(BaseHandler):
'isImportant': 0, 'isImportant': 0,
'eventText': 'Fuck CCP tbqh imho srsly', 'eventText': 'Fuck CCP tbqh imho srsly',
'endsIn':-1, 'endsIn':-1,
'forumLink': '' 'forumLink': ''}]}
}]}
events = [] events = []
events_node_children = dom.getElementsByTagName('rowset')[0].childNodes events_node_children = dom.getElementsByTagName('rowset')[0].childNodes
@@ -151,7 +152,7 @@ class OpTimerHandler(BaseHandler):
ownerID = node.getAttribute('ownerID') ownerID = node.getAttribute('ownerID')
if ownerID != '1': if ownerID != '1':
date = node.getAttribute('eventDate') date = node.getAttribute('eventDate')
dt = datetime.strptime(date,'%Y-%m-%d %H:%M:%S') dt = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
now = datetime.utcnow() now = datetime.utcnow()
startsIn = int(dt.strftime('%s')) - int(now.strftime('%s')) startsIn = int(dt.strftime('%s')) - int(now.strftime('%s'))
duration = int(node.getAttribute('duration')) duration = int(node.getAttribute('duration'))
@@ -178,8 +179,7 @@ class OpTimerHandler(BaseHandler):
'isImportant': node.getAttribute('importance'), 'isImportant': node.getAttribute('importance'),
'eventText': node.getAttribute('eventText'), 'eventText': node.getAttribute('eventText'),
'endsIn':endsIn, 'endsIn':endsIn,
'forumLink': forumlink 'forumLink': forumlink}
}
events.append(event) events.append(event)
if len(events) == 0: if len(events) == 0:
return {'ops':[{ return {'ops':[{
@@ -192,8 +192,6 @@ class OpTimerHandler(BaseHandler):
'isImportant': 0, 'isImportant': 0,
'eventText': 'Add ops using EVE-Gate or the in-game calendar', 'eventText': 'Add ops using EVE-Gate or the in-game calendar',
'endsIn':-1, 'endsIn':-1,
'forumLink': '' 'forumLink': ''}]}
}]}
else: else:
return {'ops':events} return {'ops':events}

View File

@@ -1,8 +1,9 @@
import uuid import uuid
from django.db import models from django.db import models
class AuthAPIKey(models.Model): class AuthAPIKey(models.Model):
""" Auth API Key storage model """
name = models.CharField("Service Name", max_length=200) name = models.CharField("Service Name", max_length=200)
url = models.CharField("Service URL", max_length=200, blank=True) url = models.CharField("Service URL", max_length=200, blank=True)
@@ -25,7 +26,9 @@ class AuthAPIKey(models.Model):
verbose_name = 'API Key' verbose_name = 'API Key'
verbose_name_plural = "API Keys" verbose_name_plural = "API Keys"
class AuthAPILog(models.Model): class AuthAPILog(models.Model):
""" Auth API Access Log """
access_datetime = models.DateTimeField("Date/Time Accessed") access_datetime = models.DateTimeField("Date/Time Accessed")
key = models.ForeignKey(AuthAPIKey) key = models.ForeignKey(AuthAPIKey)

View File

@@ -5,9 +5,9 @@ from piston.authentication import HttpBasicAuthentication, OAuthAuthentication,
from api.auth import APIKeyAuthentication from api.auth import APIKeyAuthentication
from api.handlers import * from api.handlers import *
oauth = { 'authentication': OAuthAuthentication() } oauth = {'authentication': OAuthAuthentication() }
noauth = { 'authentication': NoAuthentication() } noauth = {'authentication': NoAuthentication() }
apikeyauth = { 'authentication': APIKeyAuthentication() } apikeyauth = {'authentication': APIKeyAuthentication() }
user_resource = Resource(handler=UserHandler, **apikeyauth) user_resource = Resource(handler=UserHandler, **apikeyauth)
login_resource = Resource(handler=LoginHandler, **noauth) login_resource = Resource(handler=LoginHandler, **noauth)
@@ -28,4 +28,3 @@ urlpatterns += patterns('piston.authentication',
url(r'^oauth/authorize/$','oauth_user_auth'), url(r'^oauth/authorize/$','oauth_user_auth'),
url(r'^oauth/access_token/$','oauth_access_token'), url(r'^oauth/access_token/$','oauth_access_token'),
) )

View File

@@ -1,4 +1,5 @@
from django.http import HttpResponse from django.http import HttpResponse
def oauth_callback(request, other): def oauth_callback(request, other):
return HttpResponse('Fake callback view.') return HttpResponse('Fake callback view.')