Remove old dajaxice to make room for incoming later version.

- Legacy-Id: 7622
This commit is contained in:
Henrik Levkowetz 2014-04-22 18:07:17 +00:00
parent 2f142bb918
commit 4a2c615c3f
19 changed files with 0 additions and 800 deletions

View file

@ -1 +0,0 @@
__version__ = (0, 5, 5, 'beta')

View file

@ -1,137 +0,0 @@
import logging
from django.utils.importlib import import_module
log = logging.getLogger('dajaxice')
class DajaxiceFunction(object):
""" Basic representation of a dajaxice ajax function."""
def __init__(self, function, name, method):
self.function = function
self.name = name
self.method = method
def call(self, *args, **kwargs):
""" Call the function. """
return self.function(*args, **kwargs)
class DajaxiceModule(object):
""" Basic representation of a dajaxice module. """
def __init__(self, name=None):
self.name = name
self.functions = {}
self.submodules = {}
def add(self, name, function):
""" Add this function at the ``name`` deep. If the submodule already
exists, recusively call the add method into the submodule. If not,
create the module and call the add method."""
# If this is not the final function name (there are more modules)
# split the name again an register a new submodule.
if '.' in name:
module, extra = name.split('.', 1)
if module not in self.submodules:
self.submodules[module] = DajaxiceModule(module)
self.submodules[module].add(extra, function)
else:
self.functions[name] = function
class Dajaxice(object):
def __init__(self):
self._registry = {}
self._modules = None
def register(self, function, name=None, method='POST'):
"""
Register this function as a dajaxice function.
If no name is provided, the module and the function name will be used.
The final (customized or not) must be unique. """
method = self.clean_method(method)
# Generate a default name
if not name:
module = ''.join(str(function.__module__).rsplit('.ajax', 1))
name = '.'.join((module, function.__name__))
if ':' in name:
log.error('Ivalid function name %s.' % name)
return
# Check for already registered functions
if name in self._registry:
log.error('%s was already registered.' % name)
return
# Create the dajaxice function.
function = DajaxiceFunction(function=function,
name=name,
method=method)
# Register this new ajax function
self._registry[name] = function
def is_callable(self, name, method):
""" Return if the function callable or not. """
return name in self._registry and self._registry[name].method == method
def clean_method(self, method):
""" Clean the http method. """
method = method.upper()
if method not in ['GET', 'POST']:
method = 'POST'
return method
def get(self, name):
""" Return the dajaxice function."""
return self._registry[name]
@property
def modules(self):
""" Return an easy to loop module hierarchy with all the functions."""
if not self._modules:
self._modules = DajaxiceModule()
for name, function in self._registry.items():
self._modules.add(name, function)
return self._modules
LOADING_DAJAXICE = False
def dajaxice_autodiscover():
"""
Auto-discover INSTALLED_APPS ajax.py modules and fail silently when
not present. NOTE: dajaxice_autodiscover was inspired/copied from
django.contrib.admin autodiscover
"""
global LOADING_DAJAXICE
if LOADING_DAJAXICE:
return
LOADING_DAJAXICE = True
import imp
from django.conf import settings
for app in settings.INSTALLED_APPS:
try:
app_path = import_module(app).__path__
except AttributeError:
continue
try:
imp.find_module('ajax', app_path)
except ImportError:
continue
import_module("%s.ajax" % app)
LOADING_DAJAXICE = False

View file

@ -1,38 +0,0 @@
from django.conf import settings
from Dajaxice import Dajaxice, dajaxice_autodiscover
class DajaxiceConfig(object):
""" Provide an easy to use way to read the dajaxice configuration and
return the default values if no configuration is present."""
default_config = {'DAJAXICE_XMLHTTPREQUEST_JS_IMPORT': True,
'DAJAXICE_JSON2_JS_IMPORT': True,
'DAJAXICE_EXCEPTION': 'DAJAXICE_EXCEPTION',
'DAJAXICE_MEDIA_PREFIX': 'dajaxice'}
def __getattr__(self, name):
""" Return the customized value for a setting (if it exists) or the
default value if not. """
if name in self.default_config:
if hasattr(settings, name):
return getattr(settings, name)
return self.default_config.get(name)
return None
@property
def dajaxice_url(self):
return r'^%s/' % self.DAJAXICE_MEDIA_PREFIX
@property
def django_settings(self):
return settings
@property
def modules(self):
return dajaxice_functions.modules
dajaxice_functions = Dajaxice()
dajaxice_config = DajaxiceConfig()

View file

@ -1,48 +0,0 @@
import functools
from dajaxice.core import dajaxice_functions
def dajaxice_register(*dargs, **dkwargs):
""" Register some function as a dajaxice function
For legacy purposes, if only a function is passed register it a simple
single ajax function using POST, i.e:
@dajaxice_register
def ajax_function(request):
...
After 0.5, dajaxice allow to customize the http method and the final name
of the registered function. This decorator covers both the legacy and
the new functionality, i.e:
@dajaxice_register(method='GET')
def ajax_function(request):
...
@dajaxice_register(method='GET', name='my.custom.name')
def ajax_function(request):
...
You can also register the same function to use a different http method
and/or use a different name.
@dajaxice_register(method='GET', name='users.get')
@dajaxice_register(method='POST', name='users.update')
def ajax_function(request):
...
"""
if len(dargs) and not dkwargs:
function = dargs[0]
dajaxice_functions.register(function)
return function
def decorator(function):
@functools.wraps(function)
def wrapper(request, *args, **kwargs):
return function(request, *args, **kwargs)
dajaxice_functions.register(function, *dargs, **dkwargs)
return wrapper
return decorator

View file

@ -1,10 +0,0 @@
class DajaxiceError(Exception):
pass
class FunctionNotCallableError(DajaxiceError):
pass
class DajaxiceImportError(DajaxiceError):
pass

View file

@ -1,75 +0,0 @@
import os
import tempfile
from django.contrib.staticfiles import finders
from django.template import Context
from django.template.loader import get_template
from django.core.exceptions import SuspiciousOperation
class VirtualStorage(finders.FileSystemStorage):
"""" Mock a FileSystemStorage to build tmp files on demand."""
def __init__(self, *args, **kwargs):
self._files_cache = {}
super(VirtualStorage, self).__init__(*args, **kwargs)
def get_or_create_file(self, path):
if path not in self.files:
return ''
data = getattr(self, self.files[path])()
try:
current_file = open(self._files_cache[path])
current_data = current_file.read()
current_file.close()
if current_data != data:
os.remove(path)
raise Exception("Invalid data")
except Exception:
handle, tmp_path = tempfile.mkstemp()
tmp_file = open(tmp_path, 'w')
tmp_file.write(data)
tmp_file.close()
self._files_cache[path] = tmp_path
return self._files_cache[path]
def exists(self, name):
return name in self.files
def listdir(self, path):
folders, files = [], []
for f in self.files:
if f.startswith(path):
f = f.replace(path, '', 1)
if os.sep in f:
folders.append(f.split(os.sep, 1)[0])
else:
files.append(f)
return folders, files
def path(self, name):
try:
path = self.get_or_create_file(name)
except ValueError:
raise SuspiciousOperation("Attempted access to '%s' denied." % name)
return os.path.normpath(path)
class DajaxiceStorage(VirtualStorage):
files = {os.path.join('dajaxice', 'dajaxice.core.js'): 'dajaxice_core_js'}
def dajaxice_core_js(self):
from dajaxice.core import dajaxice_autodiscover, dajaxice_config
dajaxice_autodiscover()
c = Context({'dajaxice_config': dajaxice_config})
return get_template(os.path.join('dajaxice', 'dajaxice.core.js')).render(c)
class DajaxiceFinder(finders.BaseStorageFinder):
storage = DajaxiceStorage()

View file

@ -1 +0,0 @@
# Don't delete me

View file

@ -1,145 +0,0 @@
{% load url from future %}
var Dajaxice = {
{% with module=dajaxice_config.modules top='top' %}
{% include "dajaxice/dajaxice_function_loop.js" %}
{% endwith %}
{% for name, module in dajaxice_config.modules.submodules.items %}
{% include "dajaxice/dajaxice_module_loop.js" %},
{% endfor %}
get_cookie: function(name)
{
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].toString().replace(/^\s+/, "").replace(/\s+$/, "");
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
},
call: function(dajaxice_function, method, dajaxice_callback, argv, custom_settings)
{
var custom_settings = custom_settings || {},
error_callback = Dajaxice.get_setting('default_exception_callback');
if('error_callback' in custom_settings && typeof(custom_settings['error_callback']) == 'function'){
error_callback = custom_settings['error_callback'];
}
var send_data = 'argv='+encodeURIComponent(JSON.stringify(argv)),
oXMLHttpRequest = new XMLHttpRequest,
endpoint = '{% url 'dajaxice-endpoint' %}'+dajaxice_function+'/';
if(method == 'GET'){
endpoint = endpoint + '?' + send_data;
}
oXMLHttpRequest.open(method, endpoint);
oXMLHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
oXMLHttpRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest");
oXMLHttpRequest.setRequestHeader("X-CSRFToken", Dajaxice.get_cookie('{{ dajaxice_config.django_settings.CSRF_COOKIE_NAME }}'));
oXMLHttpRequest.onreadystatechange = function() {
if (this.readyState == XMLHttpRequest.DONE) {
if(this.responseText == Dajaxice.EXCEPTION || !(this.status in Dajaxice.valid_http_responses())){
error_callback();
}
else{
var response;
try {
response = JSON.parse(this.responseText);
}
catch (exception) {
response = this.responseText;
}
dajaxice_callback(response);
}
}
}
if(method == 'POST'){
oXMLHttpRequest.send(send_data);
}
else{
oXMLHttpRequest.send();
}
return oXMLHttpRequest;
},
setup: function(settings)
{
this.settings = settings;
},
get_setting: function(key){
if(this.settings == undefined || this.settings[key] == undefined){
return Dajaxice.default_settings[key];
}
return this.settings[key];
},
valid_http_responses: function(){
return {200: null, 301: null, 302: null, 304: null}
},
EXCEPTION: '{{ dajaxice_config.DAJAXICE_EXCEPTION }}',
default_settings: {'default_exception_callback': function(){ console.log('Dajaxice: Something went wrong.')}}
};
window['Dajaxice'] = Dajaxice;
{% comment %}
/*
XMLHttpRequest.js Compiled with Google Closure
XMLHttpRequest.js Copyright (C) 2008 Sergey Ilinsky (http://www.ilinsky.com)
This work is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This work is distributed in the hope that it will be useful,
but without any warranty; without even the implied warranty of
merchantability or fitness for a particular purpose. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
{% endcomment %}
{% if dajaxice_config.DAJAXICE_XMLHTTPREQUEST_JS_IMPORT %}
(function(){function n(){this._object=h&&!p?new h:new window.ActiveXObject("Microsoft.XMLHTTP");this._listeners=[]}function a(){return new n}function j(b){a.onreadystatechange&&a.onreadystatechange.apply(b);b.dispatchEvent({type:"readystatechange",bubbles:!1,cancelable:!1,timeStamp:new Date+0})}function o(b){try{b.responseText=b._object.responseText}catch(a){}try{var d;var g=b._object,c=g.responseXML,f=g.responseText;i&&(f&&c&&!c.documentElement&&g.getResponseHeader("Content-Type").match(/[^\/]+\/[^\+]+\+xml/))&&
(c=new window.ActiveXObject("Microsoft.XMLDOM"),c.async=!1,c.validateOnParse=!1,c.loadXML(f));d=c&&(i&&0!==c.parseError||!c.documentElement||c.documentElement&&"parsererror"==c.documentElement.tagName)?null:c;b.responseXML=d}catch(h){}try{b.status=b._object.status}catch(k){}try{b.statusText=b._object.statusText}catch(j){}}function l(b){b._object.onreadystatechange=new window.Function}var h=window.XMLHttpRequest,m=!!window.controllers,i=window.document.all&&!window.opera,p=i&&window.navigator.userAgent.match(/MSIE 7.0/);
a.prototype=n.prototype;m&&h.wrapped&&(a.wrapped=h.wrapped);a.UNSENT=0;a.OPENED=1;a.HEADERS_RECEIVED=2;a.LOADING=3;a.DONE=4;a.prototype.readyState=a.UNSENT;a.prototype.responseText="";a.prototype.responseXML=null;a.prototype.status=0;a.prototype.statusText="";a.prototype.priority="NORMAL";a.prototype.onreadystatechange=null;a.onreadystatechange=null;a.onopen=null;a.onsend=null;a.onabort=null;a.prototype.open=function(b,e,d,g,c){delete this._headers;arguments.length<3&&(d=true);this._async=d;var f=
this,h=this.readyState,k=null;if(i&&d){k=function(){if(h!=a.DONE){l(f);f.abort()}};window.attachEvent("onunload",k)}a.onopen&&a.onopen.apply(this,arguments);arguments.length>4?this._object.open(b,e,d,g,c):arguments.length>3?this._object.open(b,e,d,g):this._object.open(b,e,d);this.readyState=a.OPENED;j(this);this._object.onreadystatechange=function(){if(!m||d){f.readyState=f._object.readyState;o(f);if(f._aborted)f.readyState=a.UNSENT;else if(f.readyState==a.DONE){delete f._data;l(f);i&&d&&window.detachEvent("onunload",
k);h!=f.readyState&&j(f);h=f.readyState}}}};a.prototype.send=function(b){a.onsend&&a.onsend.apply(this,arguments);arguments.length||(b=null);if(b&&b.nodeType){b=window.XMLSerializer?(new window.XMLSerializer).serializeToString(b):b.xml;this._headers["Content-Type"]||this._object.setRequestHeader("Content-Type","application/xml")}this._data=b;a:{this._object.send(this._data);if(m&&!this._async){this.readyState=a.OPENED;for(o(this);this.readyState<a.DONE;){this.readyState++;j(this);if(this._aborted)break a}}}};
a.prototype.abort=function(){a.onabort&&a.onabort.apply(this,arguments);if(this.readyState>a.UNSENT)this._aborted=true;this._object.abort();l(this);this.readyState=a.UNSENT;delete this._data};a.prototype.getAllResponseHeaders=function(){return this._object.getAllResponseHeaders()};a.prototype.getResponseHeader=function(b){return this._object.getResponseHeader(b)};a.prototype.setRequestHeader=function(b,a){if(!this._headers)this._headers={};this._headers[b]=a;return this._object.setRequestHeader(b,
a)};a.prototype.addEventListener=function(a,e,d){for(var g=0,c;c=this._listeners[g];g++)if(c[0]==a&&c[1]==e&&c[2]==d)return;this._listeners.push([a,e,d])};a.prototype.removeEventListener=function(a,e,d){for(var g=0,c;c=this._listeners[g];g++)if(c[0]==a&&c[1]==e&&c[2]==d)break;c&&this._listeners.splice(g,1)};a.prototype.dispatchEvent=function(a){a={type:a.type,target:this,currentTarget:this,eventPhase:2,bubbles:a.bubbles,cancelable:a.cancelable,timeStamp:a.timeStamp,stopPropagation:function(){},preventDefault:function(){},
initEvent:function(){}};a.type=="readystatechange"&&this.onreadystatechange&&(this.onreadystatechange.handleEvent||this.onreadystatechange).apply(this,[a]);for(var e=0,d;d=this._listeners[e];e++)d[0]==a.type&&!d[2]&&(d[1].handleEvent||d[1]).apply(this,[a])};a.prototype.toString=function(){return"[object XMLHttpRequest]"};a.toString=function(){return"[XMLHttpRequest]"};window.Function.prototype.apply||(window.Function.prototype.apply=function(a,e){e||(e=[]);a.__func=this;a.__func(e[0],e[1],e[2],e[3],
e[4]);delete a.__func});window.XMLHttpRequest=a})();
{% endif %}
{% comment %}
/*
http://www.json.org/json2.js Compiled with Google Closure
This code was released under Public Domain by json.org , Thanks!
I hope that in the future this code won't be neccessary, but today all browsers doesn't supports JSON.stringify().
*/
{% endcomment %}
{% if dajaxice_config.DAJAXICE_JSON2_JS_IMPORT %}
var JSON;JSON||(JSON={});
(function(){function k(a){return 10>a?"0"+a:a}function o(a){p.lastIndex=0;return p.test(a)?'"'+a.replace(p,function(a){var c=r[a];return"string"===typeof c?c:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+a+'"'}function m(a,j){var c,d,h,n,g=e,f,b=j[a];b&&("object"===typeof b&&"function"===typeof b.toJSON)&&(b=b.toJSON(a));"function"===typeof i&&(b=i.call(j,a,b));switch(typeof b){case "string":return o(b);case "number":return isFinite(b)?String(b):"null";case "boolean":case "null":return String(b);case "object":if(!b)return"null";
e+=l;f=[];if("[object Array]"===Object.prototype.toString.apply(b)){n=b.length;for(c=0;c<n;c+=1)f[c]=m(c,b)||"null";h=0===f.length?"[]":e?"[\n"+e+f.join(",\n"+e)+"\n"+g+"]":"["+f.join(",")+"]";e=g;return h}if(i&&"object"===typeof i){n=i.length;for(c=0;c<n;c+=1)"string"===typeof i[c]&&(d=i[c],(h=m(d,b))&&f.push(o(d)+(e?": ":":")+h))}else for(d in b)Object.prototype.hasOwnProperty.call(b,d)&&(h=m(d,b))&&f.push(o(d)+(e?": ":":")+h);h=0===f.length?"{}":e?"{\n"+e+f.join(",\n"+e)+"\n"+g+"}":"{"+f.join(",")+
"}";e=g;return h}}"function"!==typeof Date.prototype.toJSON&&(Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+k(this.getUTCMonth()+1)+"-"+k(this.getUTCDate())+"T"+k(this.getUTCHours())+":"+k(this.getUTCMinutes())+":"+k(this.getUTCSeconds())+"Z":null},String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(){return this.valueOf()});var q=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
p=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,e,l,r={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},i;"function"!==typeof JSON.stringify&&(JSON.stringify=function(a,j,c){var d;l=e="";if(typeof c==="number")for(d=0;d<c;d=d+1)l=l+" ";else typeof c==="string"&&(l=c);if((i=j)&&typeof j!=="function"&&(typeof j!=="object"||typeof j.length!=="number"))throw Error("JSON.stringify");return m("",{"":a})});
"function"!==typeof JSON.parse&&(JSON.parse=function(a,e){function c(a,d){var g,f,b=a[d];if(b&&typeof b==="object")for(g in b)if(Object.prototype.hasOwnProperty.call(b,g)){f=c(b,g);f!==void 0?b[g]=f:delete b[g]}return e.call(a,d,b)}var d,a=String(a);q.lastIndex=0;q.test(a)&&(a=a.replace(q,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)}));if(/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){d=eval("("+a+")");return typeof e==="function"?c({"":d},""):d}throw new SyntaxError("JSON.parse");})})();
{% endif %}

View file

@ -1,5 +0,0 @@
{% for function_name, function in module.functions.items %}
{{ function_name }}: function(callback_function, argv, custom_settings){
return Dajaxice.call('{{ function.name }}', '{{ function.method }}', callback_function, argv, custom_settings);
}{% if not forloop.last or top or module.submodules %},{% endif %}
{% endfor %}

View file

@ -1,11 +0,0 @@
{{ name }}: {
{% include "dajaxice/dajaxice_function_loop.js" %}
{% with parent_foorloop=forloop %}
{% for name, sub_module in module.submodules.items %}
{% with filename="dajaxice/dajaxice_module_loop.js" module=sub_module %}
{% include filename %}
{% endwith %}
{% if not forloop.last %},{% endif %}
{% endfor %}
}
{% endwith %}

View file

@ -1,35 +0,0 @@
import logging
from django import template
from django.middleware.csrf import get_token
from django.conf import settings
from django.core.files.storage import get_storage_class
staticfiles_storage = get_storage_class(settings.STATICFILES_STORAGE)()
register = template.Library()
log = logging.getLogger('dajaxice')
@register.simple_tag(takes_context=True)
def dajaxice_js_import(context, csrf=True):
""" Return the js script tag for the dajaxice.core.js file
If the csrf argument is present and it's ``nocsrf`` dajaxice will not
try to mark the request as if it need the csrf token. By default use
the dajaxice_js_import template tag will make django set the csrftoken
cookie on the current request."""
csrf = csrf != 'nocsrf'
request = context.get('request')
if request and csrf:
get_token(request)
elif csrf:
log.warning("The 'request' object must be accesible within the "
"context. You must add 'django.contrib.messages.context"
"_processors.request' to your TEMPLATE_CONTEXT_PROCESSORS "
"and render your views using a RequestContext.")
url = staticfiles_storage.url('dajaxice/dajaxice.core.js')
return '<script src="%s" type="text/javascript" charset="utf-8"></script>' % url

View file

@ -1,165 +0,0 @@
from django.test import TestCase
from django.conf import settings
from dajaxice.core import DajaxiceConfig
from dajaxice.core.Dajaxice import DajaxiceModule, DajaxiceFunction, Dajaxice
from dajaxice.exceptions import FunctionNotCallableError
class DajaxiceModuleTest(TestCase):
def setUp(self):
self.module = DajaxiceModule()
def test_constructor(self):
self.assertEqual(self.module.functions, {})
self.assertEqual(self.module.submodules, {})
def test_add_function(self):
function = lambda x: x
self.module.add('test', function)
self.assertEqual(self.module.functions, {'test': function})
self.assertEqual(self.module.submodules, {})
self.module.add('foo.bar', function)
self.assertEqual(self.module.functions, {'test': function})
self.assertEqual(self.module.submodules.keys(), ['foo'])
self.assertEqual(self.module.submodules['foo'].functions, {'bar': function})
class DajaxiceFunctionTest(TestCase):
def test_constructor(self):
class CalledEception(Exception):
pass
def callback():
raise CalledEception
function = DajaxiceFunction(callback, 'foo', 'POST')
self.assertEqual(function.function, callback)
self.assertEqual(function.name, 'foo')
self.assertEqual(function.method, 'POST')
self.assertRaises(CalledEception, function.call)
class DajaxiceTest(TestCase):
def setUp(self):
self.dajaxice = Dajaxice()
self.function = lambda x: x
def test_constructor(self):
self.assertEqual(self.dajaxice._registry, {})
def test_register(self):
self.dajaxice.register(self.function, 'foo')
self.assertTrue('foo' in self.dajaxice._registry)
self.assertEqual(type(self.dajaxice._registry['foo']), DajaxiceFunction)
def bar_function():
return
self.dajaxice.register(bar_function)
self.assertTrue('dajaxice.tests.bar_function' in self.dajaxice._registry)
self.assertEqual(type(self.dajaxice._registry['dajaxice.tests.bar_function']), DajaxiceFunction)
def test__is_callable(self):
self.dajaxice.register(self.function, 'foo')
self.dajaxice.register(self.function, 'bar', method='GET')
self.assertTrue(self.dajaxice.is_callable('foo', 'POST'))
self.assertTrue(self.dajaxice.is_callable('bar', 'GET'))
self.assertFalse(self.dajaxice.is_callable('foo', 'GET'))
self.assertFalse(self.dajaxice.is_callable('bar', 'POST'))
self.assertFalse(self.dajaxice.is_callable('test', 'POST'))
self.assertFalse(self.dajaxice.is_callable('test', 'GET'))
def test_clean_method(self):
self.assertEqual(self.dajaxice.clean_method('post'), 'POST')
self.assertEqual(self.dajaxice.clean_method('get'), 'GET')
self.assertEqual(self.dajaxice.clean_method('POST'), 'POST')
self.assertEqual(self.dajaxice.clean_method('GET'), 'GET')
self.assertEqual(self.dajaxice.clean_method('other'), 'POST')
def test_modules(self):
self.dajaxice.register(self.function, 'foo')
self.dajaxice.register(self.function, 'bar')
self.assertEqual(type(self.dajaxice.modules), DajaxiceModule)
self.assertEqual(self.dajaxice.modules.functions.keys(), ['foo', 'bar'])
class DajaxiceConfigTest(TestCase):
def setUp(self):
self.config = DajaxiceConfig()
def test_defaults(self):
self.assertTrue(self.config.DAJAXICE_XMLHTTPREQUEST_JS_IMPORT)
self.assertTrue(self.config.DAJAXICE_JSON2_JS_IMPORT)
self.assertEqual(self.config.DAJAXICE_EXCEPTION, 'DAJAXICE_EXCEPTION')
self.assertEqual(self.config.DAJAXICE_MEDIA_PREFIX, 'dajaxice')
dajaxice_url = r'^%s/' % self.config.DAJAXICE_MEDIA_PREFIX
self.assertEqual(self.config.dajaxice_url, dajaxice_url)
self.assertEqual(type(self.config.modules), DajaxiceModule)
class DjangoIntegrationTest(TestCase):
urls = 'dajaxice.tests.urls'
def setUp(self):
settings.INSTALLED_APPS += ('dajaxice.tests',)
def test_calling_not_registered_function(self):
self.failUnlessRaises(FunctionNotCallableError, self.client.post, '/dajaxice/dajaxice.tests.this_function_not_exist/')
def test_calling_registered_function(self):
response = self.client.post('/dajaxice/dajaxice.tests.test_foo/')
self.failUnlessEqual(response.status_code, 200)
self.failUnlessEqual(response.content, '{"foo": "bar"}')
def test_calling_registered_function_with_params(self):
response = self.client.post('/dajaxice/dajaxice.tests.test_foo_with_params/', {'argv': '{"param1":"value1"}'})
self.failUnlessEqual(response.status_code, 200)
self.failUnlessEqual(response.content, '{"param1": "value1"}')
def test_bad_function(self):
response = self.client.post('/dajaxice/dajaxice.tests.test_ajax_exception/')
self.failUnlessEqual(response.status_code, 200)
self.failUnlessEqual(response.content, "DAJAXICE_EXCEPTION")
def test_get_register(self):
response = self.client.get('/dajaxice/dajaxice.tests.test_get_register/')
self.failUnlessEqual(response.status_code, 200)
self.failUnlessEqual(response.content, '{"foo": "user"}')
def test_get_custom_name_register(self):
response = self.client.get('/dajaxice/get_user_data/')
self.failUnlessEqual(response.status_code, 200)
self.failUnlessEqual(response.content, '{"bar": "user"}')
def test_multi_register(self):
response = self.client.get('/dajaxice/get_multi/')
self.failUnlessEqual(response.status_code, 200)
self.failUnlessEqual(response.content, '{"foo": "multi"}')
response = self.client.post('/dajaxice/post_multi/')
self.failUnlessEqual(response.status_code, 200)
self.failUnlessEqual(response.content, '{"foo": "multi"}')

View file

@ -1,43 +0,0 @@
import json
from dajaxice.decorators import dajaxice_register
@dajaxice_register
def test_registered_function(request):
return ""
@dajaxice_register
def test_string(request):
return json.dumps({'string': 'hello world'})
@dajaxice_register
def test_ajax_exception(request):
raise Exception()
@dajaxice_register
def test_foo(request):
return json.dumps({'foo': 'bar'})
@dajaxice_register
def test_foo_with_params(request, param1):
return json.dumps({'param1': param1})
@dajaxice_register(method='GET')
def test_get_register(request):
return json.dumps({'foo': 'user'})
@dajaxice_register(method='GET', name="get_user_data")
def test_get_with_name_register(request):
return json.dumps({'bar': 'user'})
@dajaxice_register(method='GET', name="get_multi")
@dajaxice_register(name="post_multi")
def test_multi_register(request):
return json.dumps({'foo': 'multi'})

View file

@ -1 +0,0 @@
Django

View file

@ -1,10 +0,0 @@
from django.conf.urls.defaults import *
from dajaxice.core import dajaxice_autodiscover, dajaxice_config
dajaxice_autodiscover()
urlpatterns = patterns('',
#Dajaxice URLS
url(dajaxice_config.dajaxice_url, include('dajaxice.urls')),
)

View file

@ -1,7 +0,0 @@
from django.conf.urls import *
from .views import DajaxiceRequest
urlpatterns = patterns('dajaxice.views',
url(r'^(.+)/$', DajaxiceRequest.as_view(), name='dajaxice-call-endpoint'),
url(r'', DajaxiceRequest.as_view(), name='dajaxice-endpoint'),
)

View file

@ -1,8 +0,0 @@
from django.http import QueryDict
def deserialize_form(data):
"""
Create a new QueryDict from a serialized form.
"""
return QueryDict(query_string=unicode(data).encode('utf-8'))

View file

@ -1,60 +0,0 @@
import logging, json
from django.conf import settings
from django.views.generic.base import View
from django.http import HttpResponse, Http404
from dajaxice.exceptions import FunctionNotCallableError
from dajaxice.core import dajaxice_functions, dajaxice_config
log = logging.getLogger('dajaxice')
def safe_dict(d):
"""
Recursively clone json structure with UTF-8 dictionary keys
http://www.gossamer-threads.com/lists/python/bugs/684379
"""
if isinstance(d, dict):
return dict([(k.encode('utf-8'), safe_dict(v)) for k, v in d.iteritems()])
elif isinstance(d, list):
return [safe_dict(x) for x in d]
else:
return d
class DajaxiceRequest(View):
""" Handle all the dajaxice xhr requests. """
def dispatch(self, request, name=None):
if not name:
raise Http404
# Check if the function is callable
if dajaxice_functions.is_callable(name, request.method):
function = dajaxice_functions.get(name)
data = getattr(request, function.method).get('argv', '')
# Clean the argv
if data != 'undefined':
try:
data = safe_dict(json.loads(data))
except Exception:
data = {}
else:
data = {}
# Call the function. If something goes wrong, handle the Exception
try:
response = function.call(request, **data)
except Exception:
raise # always give us a backtrace
if settings.DEBUG:
raise
response = dajaxice_config.DAJAXICE_EXCEPTION
return HttpResponse(response, mimetype="application/x-json")
else:
raise FunctionNotCallableError(name)