# original code: http://trac.pyworks.org/pyjamas/wiki/DjangoWithPyJamas
# also from: http://www.pimentech.fr/technologies/outils
from __future__ import absolute_import
from django.core.serializers import serialize
from svgui.pyjs.jsonrpc.jsonrpc import JSONRPCServiceBase
# JSONRPCService and jsonremote are used in combination to drastically
# simplify the provision of JSONRPC services. use as follows:
# jsonservice = JSONRPCService()
# @jsonremote(jsonservice)
# def test(request, echo_param):
# return "echoing the param back: %s" % echo_param
# dump jsonservice into urlpatterns:
# (r'^service1/$', 'djangoapp.views.jsonservice'),
class JSONRPCService(JSONRPCServiceBase):
def __call__(self, request, extra=None):
return self.process(request.raw_post_data)
"""Make JSONRPCService a decorator so that you can write :
from jsonrpc import JSONRPCService
chatservice = JSONRPCService()
def login(request, user_name):
if isinstance(service, JSONRPCService):
service.add_method(func.__name__, func)
emsg = 'Service "%s" not found' % str(service.__name__)
raise NotImplementedError(emsg)
# FormProcessor provides a mechanism for turning Django Forms into JSONRPC
# Services. If you have an existing Django app which makes prevalent
# use of Django Forms it will save you rewriting the app.
# use as follows. in djangoapp/views.py :
# class SimpleForm(forms.Form):
# testfield = forms.CharField(max_length=100)
# class SimpleForm2(forms.Form):
# testfield = forms.CharField(max_length=20)
# processor = FormProcessor({'processsimpleform': SimpleForm,
# 'processsimpleform2': SimpleForm2})
# this will result in a JSONRPC service being created with two
# RPC functions. dump "processor" into urlpatterns to make it
# (r'^formsservice/$', 'djangoapp.views.processor'),
for error in form.errors.keys():
for errorval in form.errors[error]:
d[error].append(unicode(errorval))
# contains the list of arguments in each field
'CharField': ['max_length', 'min_length'],
'IntegerField': ['max_value', 'min_value'],
'FloatField': ['max_value', 'min_value'],
'DecimalField': ['max_value', 'min_value', 'max_digits', 'decimal_places'],
'DateField': ['input_formats'],
'DateTimeField': ['input_formats'],
'TimeField': ['input_formats'],
'RegexField': ['max_length', 'min_length'], # sadly we can't get the expr
'EmailField': ['max_length', 'min_length'],
'URLField': ['max_length', 'min_length', 'verify_exists', 'user_agent'],
'ChoiceField': ['choices'],
'FilePathField': ['path', 'match', 'recursive', 'choices'],
'IPAddressField': ['max_length', 'min_length'],
def describe_field_errors(field):
field_type = field.__class__.__name__
for n, m in field.error_messages.items():
res['error_messages'] = msgs
if field_type in ['ComboField', 'MultiValueField', 'SplitDateTimeField']:
res['fields'] = map(describe_field, field.fields)
def describe_fields_errors(fields, field_names):
field_names = fields.keys()
res[name] = describe_field_errors(field)
def describe_field(field):
field_type = field.__class__.__name__
for fname in (field_names.get(field_type, []) +
['help_text', 'label', 'initial', 'required']):
res[fname] = getattr(field, fname)
if field_type in ['ComboField', 'MultiValueField', 'SplitDateTimeField']:
res['fields'] = map(describe_field, field.fields)
def describe_fields(fields, field_names):
field_names = fields.keys()
res[name] = describe_field(field)
class FormProcessor(JSONRPCService):
def __init__(self, forms, _formcls=None):
JSONRPCService.__init__(self)
s = FormProcessor({}, forms[k])
self.add_method(k, s.__process)
JSONRPCService.__init__(self, forms)
def __process(self, request, params, command=None):
if command is None: # just validate
return {'success': False, 'errors': builderrors(f)}
elif 'describe_errors' in command:
field_names = command['describe_errors']
return describe_fields_errors(f.fields, field_names)
elif 'describe' in command:
field_names = command['describe']
return describe_fields(f.fields, field_names)
return {'success': False, 'errors': builderrors(f)}
instance = f.save() # XXX: if you want more, over-ride save.
return {'success': True, 'instance': json_convert(instance)}
return {'success': True, 'html': f.as_table()}
return "unrecognised command"
# The following is incredibly convenient for saving vast amounts of
# coding, avoiding doing silly things like this:
# jsonresult = {'field1': djangoobject.field1,
# 'field2': djangoobject.date.strftime('%Y.%M'),
# The date/time flatten function is there because JSONRPC doesn't
# support date/time objects or formats, so conversion to a string
# is the most logical choice. pyjamas, being python, can easily
# be used to parse the string result at the other end.
# jsonservice = JSONRPCService()
# @jsonremote(jsonservice)
# def list_some_model(request, start=0, count=10):
# l = SomeDjangoModelClass.objects.filter()
# res = json_convert(l[start:end])
# @jsonremote(jsonservice)
# def list_another_model(request, start=0, count=10):
# l = AnotherDjangoModelClass.objects.filter()
# res = json_convert(l[start:end])
# dump jsonservice into urlpatterns to make the two RPC functions,
# list_some_model and list_another_model part of the django app:
# (r'^service1/$', 'djangoapp.views.jsonservice'),
def dict_datetimeflatten(item):
for k, v in item.items():
if isinstance(v, datetime.date):
elif isinstance(v, dict):
d[k] = dict_datetimeflatten(v)
def json_convert(l, fields=None):
for item in serialize('python', l, fields=fields):
res.append(dict_datetimeflatten(item))