importing ephelon's fork, resolving a few conflicts and refactoring oauth datastore caching

This commit is contained in:
Jesper Noehr 2009-06-03 16:37:32 +02:00
Родитель 292a6f15e9 042969176e
Коммит db633551f3
7 изменённых файлов: 46 добавлений и 20 удалений

Просмотреть файл

@ -1,3 +1,4 @@
import oauth
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.models import User, AnonymousUser
from django.contrib.auth.decorators import login_required
@ -10,7 +11,6 @@ from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils.importlib import import_module
import oauth
from piston import forms
class NoAuthentication(object):
@ -65,8 +65,6 @@ class HttpBasicAuthentication(object):
resp.status_code = 401
return resp
DataStore = None
def load_data_store():
'''Load data store for OAuth Consumers, Tokens, Nonces and Resources
'''
@ -75,6 +73,7 @@ def load_data_store():
# stolen from django.contrib.auth.load_backend
i = path.rfind('.')
module, attr = path[:i], path[i+1:]
try:
mod = import_module(module)
except ImportError, e:
@ -87,6 +86,9 @@ def load_data_store():
return cls
# Set the datastore here.
oauth_datastore = load_data_store()
def initialize_server_request(request):
"""
Shortcut for initialization.
@ -97,11 +99,7 @@ def initialize_server_request(request):
query_string=request.environ.get('QUERY_STRING', ''))
if oauth_request:
global DataStore
if DataStore is None:
DataStore = load_data_store()
oauth_server = oauth.OAuthServer(DataStore(oauth_request))
oauth_server = oauth.OAuthServer(oauth_datastore(oauth_request))
oauth_server.add_signature_method(oauth.OAuthSignatureMethod_PLAINTEXT())
oauth_server.add_signature_method(oauth.OAuthSignatureMethod_HMAC_SHA1())
else:
@ -143,6 +141,7 @@ def oauth_auth_view(request, token, callback, params):
'oauth_token': token.key,
'oauth_callback': callback,
})
return render_to_response('piston/authorize_token.html',
{ 'form': form }, RequestContext(request))

Просмотреть файл

@ -1,6 +1,6 @@
from __future__ import generators
import types, decimal, types, re, inspect
import decimal, re, inspect
try:
# yaml isn't standard with python. It shouldn't be required if it
@ -99,9 +99,13 @@ class Emitter(object):
ret = _model(thing, fields=fields)
elif isinstance(thing, HttpResponse):
raise HttpStatusCode(thing)
elif isinstance(thing, types.FunctionType):
elif inspect.isfunction(thing):
if not inspect.getargspec(thing)[0]:
ret = _any(thing())
elif hasattr(thing, '__emittable__'):
f = thing.__emittable__
if inspect.ismethod(f) and len(inspect.getargspec(f)[0]) == 1:
ret = _any(f())
else:
ret = smart_unicode(thing, strings_only=True)

Просмотреть файл

@ -1,6 +1,7 @@
import sys, inspect
from django.http import HttpResponse, Http404, HttpResponseNotAllowed, HttpResponseForbidden
from django.http import (HttpResponse, Http404, HttpResponseNotAllowed,
HttpResponseForbidden, HttpResponseServerError)
from django.views.debug import ExceptionReporter
from django.views.decorators.vary import vary_on_headers
from django.conf import settings
@ -143,20 +144,19 @@ class Resource(object):
If `PISTON_DISPLAY_ERRORS` is not enabled, the caller will
receive a basic "500 Internal Server Error" message.
"""
exc_type, exc_value, tb = sys.exc_info()
rep = ExceptionReporter(request, exc_type, exc_value, tb.tb_next)
if self.email_errors:
exc_type, exc_value, tb = sys.exc_info()
rep = ExceptionReporter(request, exc_type, exc_value, tb.tb_next)
self.email_exception(rep)
if self.display_errors:
result = format_error('\n'.join(rep.format_exception()))
return HttpResponseServerError(
format_error('\n'.join(rep.format_exception())))
else:
raise
emitter, ct = Emitter.get(em_format)
srl = emitter(result, typemapper, handler, handler.fields, anonymous)
try:
"""
Decide whether or not we want a generator here,

Просмотреть файл

@ -3,7 +3,7 @@ from django.core.paginator import Paginator
from piston.handler import BaseHandler
from piston.utils import rc, validate
from models import TestModel, ExpressiveTestModel, Comment, InheritedModel
from models import TestModel, ExpressiveTestModel, Comment, InheritedModel, PlainOldObject
from forms import EchoForm
from test_project.apps.testapp import signals
@ -62,6 +62,13 @@ class AbstractHandler(BaseHandler):
else:
return super(AbstractHandler, self).read(request)
class PlainOldObjectHandler(BaseHandler):
allowed_methods = ('GET',)
fields = ('type', 'field')
model = PlainOldObject
def read(self, request):
return self.model()
class EchoHandler(BaseHandler):
allowed_methods = ('GET', )

Просмотреть файл

@ -23,4 +23,9 @@ class InheritedModel(AbstractModel):
some_other = models.CharField(max_length=32, default='something else')
class Meta:
db_table = 'testing_abstracts'
db_table = 'testing_abstracts'
class PlainOldObject(object):
def __emittable__(self):
return {'type': 'plain',
'field': 'a field'}

Просмотреть файл

@ -326,3 +326,10 @@ class ValidationTest(MainTests):
resp = self.client.get('/api/echo', data)
self.assertEquals(resp.status_code, 200)
self.assertEquals(data, simplejson.loads(resp.content))
class PlainOldObject(MainTests):
def test_plain_object_serialization(self):
resp = self.client.get('/api/popo')
self.assertEquals(resp.status_code, 200)
self.assertEquals({'type': 'plain', 'field': 'a field'}, simplejson.loads(resp.content))

Просмотреть файл

@ -2,7 +2,7 @@ from django.conf.urls.defaults import *
from piston.resource import Resource
from piston.authentication import HttpBasicAuthentication
from test_project.apps.testapp.handlers import EntryHandler, ExpressiveHandler, AbstractHandler, EchoHandler
from test_project.apps.testapp.handlers import EntryHandler, ExpressiveHandler, AbstractHandler, EchoHandler, PlainOldObjectHandler
auth = HttpBasicAuthentication(realm='TestApplication')
@ -10,6 +10,7 @@ entries = Resource(handler=EntryHandler, authentication=auth)
expressive = Resource(handler=ExpressiveHandler, authentication=auth)
abstract = Resource(handler=AbstractHandler, authentication=auth)
echo = Resource(handler=EchoHandler)
popo = Resource(handler=PlainOldObjectHandler)
urlpatterns = patterns('',
@ -25,9 +26,12 @@ urlpatterns = patterns('',
url(r'^echo$', echo),
# oauth entrypoints
url(r'^oauth/request_token$', 'piston.authentication.oauth_request_token'),
url(r'^oauth/authorize$', 'piston.authentication.oauth_user_auth'),
url(r'^oauth/access_token$', 'piston.authentication.oauth_access_token'),
url(r'^popo$', popo),
)