aboutsummaryrefslogtreecommitdiffstats
path: root/djangorestframework/utils
diff options
context:
space:
mode:
Diffstat (limited to 'djangorestframework/utils')
-rw-r--r--djangorestframework/utils/__init__.py110
-rw-r--r--djangorestframework/utils/staticviews.py61
2 files changed, 41 insertions, 130 deletions
diff --git a/djangorestframework/utils/__init__.py b/djangorestframework/utils/__init__.py
index afef4f19..9d250be2 100644
--- a/djangorestframework/utils/__init__.py
+++ b/djangorestframework/utils/__init__.py
@@ -1,24 +1,18 @@
-import django
from django.utils.encoding import smart_unicode
from django.utils.xmlutils import SimplerXMLGenerator
-from django.core.urlresolvers import resolve, reverse as django_reverse
-from django.conf import settings
+from django.core.urlresolvers import resolve
from djangorestframework.compat import StringIO
+from djangorestframework.compat import RequestFactory as DjangoRequestFactory
+from djangorestframework.request import Request
import re
import xml.etree.ElementTree as ET
-#def admin_media_prefix(request):
-# """Adds the ADMIN_MEDIA_PREFIX to the request context."""
-# return {'ADMIN_MEDIA_PREFIX': settings.ADMIN_MEDIA_PREFIX}
-
-from mediatypes import media_type_matches, is_form_media_type
-from mediatypes import add_media_type_param, get_media_type_params, order_by_precedence
-
MSIE_USER_AGENT_REGEX = re.compile(r'^Mozilla/[0-9]+\.[0-9]+ \([^)]*; MSIE [0-9]+\.[0-9]+[a-z]?;[^)]*\)(?!.* Opera )')
+
def as_tuple(obj):
"""
Given an object which may be a list/tuple, another object, or None,
@@ -49,45 +43,6 @@ def url_resolves(url):
return True
-def allowed_methods(view):
- """
- Return the list of uppercased allowed HTTP methods on `view`.
- """
- return [method.upper() for method in view.http_method_names if hasattr(view, method)]
-
-
-# From http://www.koders.com/python/fidB6E125C586A6F49EAC38992CF3AFDAAE35651975.aspx?s=mdef:xml
-#class object_dict(dict):
-# """object view of dict, you can
-# >>> a = object_dict()
-# >>> a.fish = 'fish'
-# >>> a['fish']
-# 'fish'
-# >>> a['water'] = 'water'
-# >>> a.water
-# 'water'
-# >>> a.test = {'value': 1}
-# >>> a.test2 = object_dict({'name': 'test2', 'value': 2})
-# >>> a.test, a.test2.name, a.test2.value
-# (1, 'test2', 2)
-# """
-# def __init__(self, initd=None):
-# if initd is None:
-# initd = {}
-# dict.__init__(self, initd)
-#
-# def __getattr__(self, item):
-# d = self.__getitem__(item)
-# # if value is the only key in object, you can omit it
-# if isinstance(d, dict) and 'value' in d and len(d) == 1:
-# return d['value']
-# else:
-# return d
-#
-# def __setattr__(self, item, value):
-# self.__setitem__(item, value)
-
-
# From xml2dict
class XML2Dict(object):
@@ -99,24 +54,23 @@ class XML2Dict(object):
# Save attrs and text, hope there will not be a child with same name
if node.text:
node_tree = node.text
- for (k,v) in node.attrib.items():
- k,v = self._namespace_split(k, v)
+ for (k, v) in node.attrib.items():
+ k, v = self._namespace_split(k, v)
node_tree[k] = v
#Save childrens
for child in node.getchildren():
tag, tree = self._namespace_split(child.tag, self._parse_node(child))
- if tag not in node_tree: # the first time, so store it in dict
+ if tag not in node_tree: # the first time, so store it in dict
node_tree[tag] = tree
continue
old = node_tree[tag]
if not isinstance(old, list):
node_tree.pop(tag)
- node_tree[tag] = [old] # multi times, so change old dict to a list
- node_tree[tag].append(tree) # add the new one
+ node_tree[tag] = [old] # multi times, so change old dict to a list
+ node_tree[tag].append(tree) # add the new one
return node_tree
-
def _namespace_split(self, tag, value):
"""
Split the tag '{http://cs.sfsu.edu/csc867/myscheduler}patients'
@@ -179,23 +133,41 @@ class XMLRenderer():
xml.endDocument()
return stream.getvalue()
+
def dict2xml(input):
return XMLRenderer().dict2xml(input)
-def reverse(viewname, request, *args, **kwargs):
+class RequestFactory(DjangoRequestFactory):
"""
- Do the same as :py:func:`django.core.urlresolvers.reverse` but using
- *request* to build a fully qualified URL.
+ Replicate RequestFactory, but return Request, not HttpRequest.
"""
- return request.build_absolute_uri(django_reverse(viewname, *args, **kwargs))
-
-if django.VERSION >= (1, 4):
- from django.core.urlresolvers import reverse_lazy as django_reverse_lazy
-
- def reverse_lazy(viewname, request, *args, **kwargs):
- """
- Do the same as :py:func:`django.core.urlresolvers.reverse_lazy` but using
- *request* to build a fully qualified URL.
- """
- return request.build_absolute_uri(django_reverse_lazy(viewname, *args, **kwargs))
+ def get(self, *args, **kwargs):
+ parsers = kwargs.pop('parsers', None)
+ request = super(RequestFactory, self).get(*args, **kwargs)
+ return Request(request, parsers)
+
+ def post(self, *args, **kwargs):
+ parsers = kwargs.pop('parsers', None)
+ request = super(RequestFactory, self).post(*args, **kwargs)
+ return Request(request, parsers)
+
+ def put(self, *args, **kwargs):
+ parsers = kwargs.pop('parsers', None)
+ request = super(RequestFactory, self).put(*args, **kwargs)
+ return Request(request, parsers)
+
+ def delete(self, *args, **kwargs):
+ parsers = kwargs.pop('parsers', None)
+ request = super(RequestFactory, self).delete(*args, **kwargs)
+ return Request(request, parsers)
+
+ def head(self, *args, **kwargs):
+ parsers = kwargs.pop('parsers', None)
+ request = super(RequestFactory, self).head(*args, **kwargs)
+ return Request(request, parsers)
+
+ def options(self, *args, **kwargs):
+ parsers = kwargs.pop('parsers', None)
+ request = super(RequestFactory, self).options(*args, **kwargs)
+ return Request(request, parsers)
diff --git a/djangorestframework/utils/staticviews.py b/djangorestframework/utils/staticviews.py
deleted file mode 100644
index 7cbc0b9b..00000000
--- a/djangorestframework/utils/staticviews.py
+++ /dev/null
@@ -1,61 +0,0 @@
-from django.contrib.auth.views import *
-from django.conf import settings
-from django.http import HttpResponse
-from django.shortcuts import render_to_response
-from django.template import RequestContext
-import base64
-
-
-# BLERGH
-# Replicate django.contrib.auth.views.login simply so we don't have get users to update TEMPLATE_CONTEXT_PROCESSORS
-# to add ADMIN_MEDIA_PREFIX to the RequestContext. I don't like this but really really want users to not have to
-# be making settings changes in order to accomodate django-rest-framework
-@csrf_protect
-@never_cache
-def api_login(request, template_name='djangorestframework/login.html',
- redirect_field_name=REDIRECT_FIELD_NAME,
- authentication_form=AuthenticationForm):
- """Displays the login form and handles the login action."""
-
- redirect_to = request.REQUEST.get(redirect_field_name, '')
-
- if request.method == "POST":
- form = authentication_form(data=request.POST)
- if form.is_valid():
- # Light security check -- make sure redirect_to isn't garbage.
- if not redirect_to or ' ' in redirect_to:
- redirect_to = settings.LOGIN_REDIRECT_URL
-
- # Heavier security check -- redirects to http://example.com should
- # not be allowed, but things like /view/?param=http://example.com
- # should be allowed. This regex checks if there is a '//' *before* a
- # question mark.
- elif '//' in redirect_to and re.match(r'[^\?]*//', redirect_to):
- redirect_to = settings.LOGIN_REDIRECT_URL
-
- # Okay, security checks complete. Log the user in.
- auth_login(request, form.get_user())
-
- if request.session.test_cookie_worked():
- request.session.delete_test_cookie()
-
- return HttpResponseRedirect(redirect_to)
-
- else:
- form = authentication_form(request)
-
- request.session.set_test_cookie()
-
- #current_site = get_current_site(request)
-
- return render_to_response(template_name, {
- 'form': form,
- redirect_field_name: redirect_to,
- #'site': current_site,
- #'site_name': current_site.name,
- 'ADMIN_MEDIA_PREFIX': settings.ADMIN_MEDIA_PREFIX,
- }, context_instance=RequestContext(request))
-
-
-def api_logout(request, next_page=None, template_name='djangorestframework/login.html', redirect_field_name=REDIRECT_FIELD_NAME):
- return logout(request, next_page, template_name, redirect_field_name)