From 750083c8fd4ecbe9ee1a3804dcf8f53e17a956e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20P=C3=A9ters?= Date: Sat, 24 Jun 2017 19:56:26 +0200 Subject: [PATCH] general: switch to json-api/wrap_response:False as endpoint default (#17175) --- passerelle/apps/base_adresse/models.py | 6 +-- passerelle/apps/clicrdv/models.py | 8 ++-- passerelle/apps/cmis/models.py | 4 +- passerelle/apps/csvdatasource/models.py | 12 +++--- passerelle/apps/family/models.py | 48 +++++++++++------------ passerelle/apps/okina/models.py | 67 +++++++++++++++------------------ passerelle/contrib/arcgis/models.py | 6 +-- passerelle/contrib/greco/models.py | 20 +++++----- passerelle/contrib/iparapheur/models.py | 34 ++++++++--------- passerelle/contrib/mdel/models.py | 24 ++++++------ passerelle/contrib/nancypoll/models.py | 6 +-- passerelle/sms/__init__.py | 6 +-- passerelle/utils/api.py | 4 +- passerelle/utils/jsonresponse.py | 2 + tests/test_jsondatastore.py | 4 +- tests/test_jsonresponse.py | 2 +- 16 files changed, 124 insertions(+), 129 deletions(-) diff --git a/passerelle/apps/base_adresse/models.py b/passerelle/apps/base_adresse/models.py index 95095e2..5df58ac 100644 --- a/passerelle/apps/base_adresse/models.py +++ b/passerelle/apps/base_adresse/models.py @@ -33,7 +33,7 @@ class BaseAdresse(BaseResource): def get_icon_class(cls): return 'gis' - @endpoint(pattern='(?P.+)?$') + @endpoint(serializer_type='json', pattern='(?P.+)?$') def search(self, request, q, zipcode='', **kwargs): if kwargs.get('format', 'json') != 'json': raise NotImplementedError() @@ -97,7 +97,7 @@ class BaseAdresse(BaseResource): result['address']['road'] = value return result - @endpoint(serializer_type='json-api') + @endpoint() def streets(self, request, zipcode=None, q=None, page_limit=None): result = [] streets = StreetModel.objects.all() @@ -119,7 +119,7 @@ class BaseAdresse(BaseResource): 'citycode': street.citycode, 'zipcode': street.zipcode}) - return result + return {'data': result} def daily(self): super(BaseAdresse, self).daily() diff --git a/passerelle/apps/clicrdv/models.py b/passerelle/apps/clicrdv/models.py index cd06449..017cd66 100644 --- a/passerelle/apps/clicrdv/models.py +++ b/passerelle/apps/clicrdv/models.py @@ -66,7 +66,7 @@ class ClicRdv(BaseResource): req = self.get_request(uri) return json.load(urllib2.urlopen(req)) - @endpoint(name='interventionsets', serializer_type='json-api') + @endpoint(name='interventionsets') def get_interventionsets(self, request, **kwargs): records = self.get_json('interventionsets').get('records') records.sort(lambda x,y: cmp(x['sort'], y['sort'])) @@ -74,9 +74,9 @@ class ClicRdv(BaseResource): for record in records: if record.get('publicname'): ret.append({'id': record['id'], 'text': record['publicname'], 'details': record}) - return ret + return {'data': ret} - @endpoint(name='interventionsets', pattern='(?P\d+)/', serializer_type='json-api') + @endpoint(name='interventionsets', pattern='(?P\d+)/') def get_interventions(self, request, set, **kwargs): ret = [] records = self.get_json('interventions?interventionset_id=%s' % set).get('records') @@ -84,7 +84,7 @@ class ClicRdv(BaseResource): for record in records: if record.get('publicname'): ret.append({'id': record['id'], 'text': record['publicname'], 'details': record}) - return ret + return {'data': ret} def get_available_timeslots(self, intervention, date_start=None, date_end=None): timeslots = [] diff --git a/passerelle/apps/cmis/models.py b/passerelle/apps/cmis/models.py index 7d248dd..eccc26c 100644 --- a/passerelle/apps/cmis/models.py +++ b/passerelle/apps/cmis/models.py @@ -48,7 +48,7 @@ class CmisConnector(BaseResource): fields = super(CmisConnector, self).get_description_fields() return [(x[0], x[1]) for x in fields if x[0].name != 'password'] - @endpoint(serializer_type='json-api', methods=['post'], perm='can_upload_file') + @endpoint(methods=['post'], perm='can_upload_file') def upload_file(self, request, **kwargs): try: data = json.loads(request.body) @@ -82,7 +82,7 @@ class CmisConnector(BaseResource): except UpdateConflictException: raise CMISError('the document already exists on platform.') - return doc.properties + return {'data': doc.properties} def cmis_connection_repository(self, repo_name): try: diff --git a/passerelle/apps/csvdatasource/models.py b/passerelle/apps/csvdatasource/models.py index 675c122..45312e8 100644 --- a/passerelle/apps/csvdatasource/models.py +++ b/passerelle/apps/csvdatasource/models.py @@ -248,7 +248,7 @@ class CsvDataSource(BaseResource): def titles(self): return [smart_text(t.strip()) for t in self.columns_keynames.split(',')] - @endpoint('json-api', perm='can_access', methods=['get'], + @endpoint(perm='can_access', methods=['get'], name='query', pattern='^(?P[\w-]+)/$') def select(self, request, query_name, **kwargs): try: @@ -358,21 +358,21 @@ class CsvDataSource(BaseResource): if new_row[0]] if query.structure == 'array': - return [[row[t] for t in titles] for row in data] + return {'data': [[row[t] for t in titles] for row in data]} elif query.structure == 'dict': - return data + return {'data': data} elif query.structure == 'tuples': - return [[[t, row[t]] for t in titles] for row in data] + return {'data': [[[t, row[t]] for t in titles] for row in data]} elif query.structure == 'onerow': if len(data) != 1: raise APIError('more or less than one row', data=data) - return data[0] + return {'data': data[0]} elif query.structure == 'one': if len(data) != 1: raise APIError('more or less than one row', data=data) if len(data[0]) != 1: raise APIError('more or less than one column', data=data) - return data[0].values()[0] + return {'data': data[0].values()[0]} def export_json(self): d = super(CsvDataSource, self).export_json() diff --git a/passerelle/apps/family/models.py b/passerelle/apps/family/models.py index 6f1fb03..723d218 100644 --- a/passerelle/apps/family/models.py +++ b/passerelle/apps/family/models.py @@ -244,7 +244,7 @@ class GenericFamily(BaseResource): except FamilyLink.DoesNotExist: return None - @endpoint(serializer_type='json-api', name='family', perm='can_access', pattern='^link/$') + @endpoint(name='family', perm='can_access', pattern='^link/$') def family_link(self, request, NameID=None, login=None, password=None, **kwargs): """ Links a NameID to a person @@ -252,11 +252,11 @@ class GenericFamily(BaseResource): try: f = Family.objects.get(login=login, password=password, resource=self) except Family.DoesNotExist: - return False + return {'data': False} FamilyLink.objects.get_or_create(resource=self, name_id=NameID, family=f) - return True + return {'data': True} - @endpoint(serializer_type='json-api', name='family', perm='can_access', pattern='^unlink/$') + @endpoint(name='family', perm='can_access', pattern='^unlink/$') def family_unlink(self, request, NameID=None, **kwargs): """ Unlinks a NameID from a person @@ -264,35 +264,35 @@ class GenericFamily(BaseResource): print "Unlink" try: FamilyLink.objects.get(resource=self, name_id=NameID).delete() - return True + return {'data': True} except FamilyLink.DoesNotExist: - return False + return {'data': False} - @endpoint(serializer_type='json-api', perm='can_access', name='family') + @endpoint(perm='can_access', name='family') def family_infos(self, request, NameID, **kwargs): """ Displays the information of person's family """ family = self.get_family_by_nameid(NameID) if not family: - return + return {'data': None} data = {'id': family.get_display_id(), 'adults': [], 'children': []} for adult in family.adult_set.all(): data['adults'].append(format_person(adult)) for child in family.child_set.all(): data['children'].append(format_person(child)) - return data + return {'data': data} - @endpoint(serializer_type='json-api', name='family', perm='can_access', pattern='^adults/$') + @endpoint(name='family', perm='can_access', pattern='^adults/$') def adults_infos(self, request, NameID): data = self.family_infos(request, NameID) - return data['adults'] + return {'data': data['data']['adults']} - @endpoint(serializer_type='json-api', name='family', perm='can_access', pattern='^children/$') + @endpoint(name='family', perm='can_access', pattern='^children/$') def children_infos(self, request, NameID, **kwargs): data = self.family_infos(request, NameID) - return data['children'] + return {'data': data['data']['children']} def get_invoices(self, NameID, paid=False): family = self.get_family_by_nameid(NameID) @@ -303,13 +303,13 @@ class GenericFamily(BaseResource): invoices.append(format_invoice(i)) return invoices - @endpoint(serializer_type='json-api', name='regie', pattern='^invoices/$') + @endpoint(name='regie', pattern='^invoices/$') def active_invoices(self, request, NameID): - return self.get_invoices(NameID) + return {'data': self.get_invoices(NameID)} - @endpoint(serializer_type='json-api', name='regie', perm='can_access', pattern='^invoices/history/$') + @endpoint(name='regie', perm='can_access', pattern='^invoices/history/$') def invoices_history(self, request, NameID, **kwargs): - return self.get_invoices(NameID, paid=True) + return {'data': self.get_invoices(NameID, paid=True)} def get_invoice(self, invoice_id): try: @@ -317,15 +317,15 @@ class GenericFamily(BaseResource): except Invoice.DoesNotExist: return None - @endpoint(serializer_type='json-api', name='regie', perm='can_access', + @endpoint(name='regie', perm='can_access', pattern='^invoice/(?P\w+)/$') def get_invoice_details(self, request, invoice_id, NameID=None, email=None, **kwargs): invoice = self.get_invoice(invoice_id) if not invoice: - return - return format_invoice(invoice) + return {'data': None} + return {'data': format_invoice(invoice)} - @endpoint(serializer_type='json-api', name='regie', perm='can_access', + @endpoint(name='regie', perm='can_access', pattern='^invoice/(?P\w+)/pdf/$') def get_invoice_pdf(self, request, invoice_id, **kwargs): invoice = self.get_invoice(invoice_id) @@ -333,20 +333,20 @@ class GenericFamily(BaseResource): raise FileNotFoundError return invoice.get_pdf() - @endpoint(serializer_type='json-api', name='regie', methods=['post'], + @endpoint(name='regie', methods=['post'], perm='can_access', pattern='^invoice/(?P\w+)/pay/$') def pay_invoice(self, request, invoice_id, **kwargs): data = json.loads(request.body) invoice = self.get_invoice(invoice_id) if not invoice: - return False + return {'data': False} transaction_date = get_datetime(data['transaction_date']) invoice.paid = True invoice.payment_date = transaction_date invoice.amount = 0 invoice.payment_transaction_id = data['transaction_id'] invoice.save() - return True + return {'data': True} class FamilyLink(models.Model): diff --git a/passerelle/apps/okina/models.py b/passerelle/apps/okina/models.py index fb001aa..511ae3e 100644 --- a/passerelle/apps/okina/models.py +++ b/passerelle/apps/okina/models.py @@ -53,7 +53,7 @@ class Okina(BaseResource): else: return result - @endpoint(serializer_type='json-api') + @endpoint() def cities(self, request): okina_cities = self.request('cities') cities = [] @@ -63,14 +63,14 @@ class Okina(BaseResource): city['text'] = '%(nameCity)s (%(zipCode)s)' % city cities.append(city) cities.sort(lambda x,y: cmp(x['text'], y['text'])) - return cities + return {'data': cities} - @endpoint(serializer_type='json-api') + @endpoint() def classes(self, request): - return [{ + return {'data': [{ 'id': '%s' % item['id'], 'text': item['label'] - } for item in self.request('classes')] + } for item in self.request('classes')]} def get_institutions(self, endpoint=''): okina_institutions = self.request('institutions' + endpoint) @@ -84,25 +84,23 @@ class Okina(BaseResource): institutions.sort(lambda x,y: cmp(x['text'], y['text'])) return institutions - @endpoint(serializer_type='json-api') + @endpoint() def institutions(self, request): - return self.get_institutions() + return {'data': self.get_institutions()} - @endpoint(name='institutions', pattern='^from-city/(?P\d+)/*$', - serializer_type='json-api') + @endpoint(name='institutions', pattern='^from-city/(?P\d+)/*$') def institutions_from_city(self, request, city_insee_code): - return self.get_institutions('/subscriberCity/%s' % city_insee_code) + return {'data': self.get_institutions('/subscriberCity/%s' % city_insee_code)} @endpoint(name='stop-areas', - pattern='^from-city/(?P\d+)/to-institution/(?P\d+)/*$', - serializer_type='json-api') + pattern='^from-city/(?P\d+)/to-institution/(?P\d+)/*$') def stop_areas(self, request, city_insee_code, institution_id): stops = self.request('stop-areas/subscriberCity/%s/institution/%s' % (city_insee_code, institution_id)) for stop in stops: stop['id'] = '%s' % stop['id'] stop['text'] = stop['commercial_name'] - return stops + return {'data': stops} def get_ods(self, endpoint=''): # ods = origin/destinations @@ -124,21 +122,19 @@ class Okina(BaseResource): 'object_id': journey['okinaVehicleJourney']['objectId'], 'identifier': identifier }) - return ods + return {'data': ods} - @endpoint(name='origin-destinations', serializer_type='json-api') + @endpoint(name='origin-destinations') def origin_destinations(self, request): return self.get_ods() @endpoint(name='origin-destinations', - pattern='^to-institution/(?P\d+)/*$', - serializer_type='json-api') + pattern='^to-institution/(?P\d+)/*$') def origin_destinations_to_institution(self, request, institution_id): return self.get_ods('/institution/%s' % institution_id) @endpoint(name='origin-destinations', - pattern='^from-stop-area/(?P\d+)/to-institution/(?P\d+)/*$', - serializer_type='json-api') + pattern='^from-stop-area/(?P\d+)/to-institution/(?P\d+)/*$') def origin_destinations_from_stop_to_institution(self, request, stop_area_id, institution_id): endpoint = 'ods/institution/%s/stop-area/%s' % (institution_id, stop_area_id) okina_journeys = self.request(endpoint) @@ -153,29 +149,26 @@ class Okina(BaseResource): } for line in okina_journey], } journeys.append(journey) - return journeys + return {'data': journeys} @endpoint(name='origin-destinations', - pattern='^from-city/(?P\d+)/to-institution/(?P\d+)/*$', - serializer_type='json-api') + pattern='^from-city/(?P\d+)/to-institution/(?P\d+)/*$') def origin_destinations_from_city_to_institution(self, request, city_insee_code, institution_id): return self.get_ods('/institution/%s/subscriberCity/%s' % (institution_id, city_insee_code)) @endpoint(name='origin-destinations', - pattern='^from-city/(?P\d+)/*$', - serializer_type='json-api') + pattern='^from-city/(?P\d+)/*$') def origin_destinations_from_city(self, request, city_insee_code): return self.get_ods('/subscriberCity/%s' % city_insee_code) - @endpoint(name='topology', pattern='^(?P(lines|networks|vehicle-journeys))/*$', - serializer_type='json-api') + @endpoint(name='topology', pattern='^(?P(lines|networks|vehicle-journeys))/*$') def topology(self, request, kind): - return [{ + return {'data': [{ 'id': '%s' % item['id'], 'text': item['name'] - } for item in self.request('topology/%s' % kind)] + } for item in self.request('topology/%s' % kind)]} - @endpoint(name='subscriber', serializer_type='json-api', methods=['post'], perm='can_access') + @endpoint(name='subscriber', methods=['post'], perm='can_access') def create_subscriber(self, request): try: payload = json.loads(request.body) @@ -183,15 +176,15 @@ class Okina(BaseResource): raise APIError('payload must be a JSON object', http_status=400) if not isinstance(payload, dict): raise APIError('payload must be a dict', http_status=400) - return self.request('subscribers', payload) + return {'data': self.request('subscribers', payload)} @endpoint(name='subscriber', pattern='^(?P\d+)/*$', - serializer_type='json-api', methods=['get'], perm='can_access') + methods=['get'], perm='can_access') def get_subscriber(self, request, subscriber_id): - return self.request('subscribers/%s' % subscriber_id) + return {'data': self.request('subscribers/%s' % subscriber_id)} @endpoint(name='subscriber', pattern='^(?P\d+)/qrcode/*$', - serializer_type='json-api', perm='can_access') + perm='can_access') def get_subscriber_qrcode(self, request, subscriber_id): qrcode = self.request('subscribers/%s/qrcode' % subscriber_id, result_is_json=False) content_type = qrcode.headers.get('Content-Type') @@ -202,7 +195,7 @@ class Okina(BaseResource): err=response['code']) return HttpResponse(qrcode.content, content_type=content_type) - @endpoint(name='subscription', serializer_type='json-api', methods=['post'], perm='can_access') + @endpoint(name='subscription', methods=['post'], perm='can_access') def create_subscription(self, request): try: payload = json.loads(request.body) @@ -210,9 +203,9 @@ class Okina(BaseResource): raise APIError('payload must be a JSON object', http_status=400) if not isinstance(payload, dict): raise APIError('payload must be a dict', http_status=400) - return self.request('subscriptions', payload) + return {'data': self.request('subscriptions', payload)} @endpoint(name='subscription', pattern='^(?P\d+)/*$', - serializer_type='json-api', methods=['get'], perm='can_access') + methods=['get'], perm='can_access') def get_subscription(self, request, subscription_id): - return self.request('subscriptions/%s' % subscription_id) + return {'data': self.request('subscriptions/%s' % subscription_id)} diff --git a/passerelle/contrib/arcgis/models.py b/passerelle/contrib/arcgis/models.py index 9f86d0e..4141725 100644 --- a/passerelle/contrib/arcgis/models.py +++ b/passerelle/contrib/arcgis/models.py @@ -37,7 +37,7 @@ class Arcgis(BaseResource): def get_icon_class(cls): return 'gis' - @endpoint(serializer_type='json-api') + @endpoint() def district(self, request, lon=None, lat=None): if lon and lat: try: @@ -79,5 +79,5 @@ class Arcgis(BaseResource): {'id': feature['attributes'].get('NUMERO'), 'text': feature['attributes'].get('NOM')} for feature in features] if len(data) == 1: - return data[0] - return data + return {'data': data[0]} + return {'data': data} diff --git a/passerelle/contrib/greco/models.py b/passerelle/contrib/greco/models.py index 6865656..9e3204d 100644 --- a/passerelle/contrib/greco/models.py +++ b/passerelle/contrib/greco/models.py @@ -118,11 +118,11 @@ class Greco(BaseResource): return Client(url=self.wsdl_url, transport=Transport(self)) - @endpoint(serializer_type='json-api', perm='can_access') + @endpoint(perm='can_access') def ping(self, request): - return self.get_client().service.communicationTest('ping') + return {'data': self.get_client().service.communicationTest('ping')} - @endpoint(serializer_type='json-api', perm='can_access', methods=['post']) + @endpoint(perm='can_access', methods=['post']) def create(self, request): # get creation fields from payload try: @@ -136,22 +136,22 @@ class Greco(BaseResource): fill_sudsobject_with_dict(creation, formdata.fields) # send it to "creer" resp = client.service.creer(creation) - return sudsobject_to_dict(resp) + return {'data': sudsobject_to_dict(resp)} @classmethod def creation_fields(cls): '''used in greco_detail.html template''' return list_schema_fields(CREATION_SCHEMA) - @endpoint(serializer_type='json-api', perm='can_access') + @endpoint(perm='can_access') def status(self, request, iddemande, idgreco): resp = self.get_client().service.consulter({ 'idgreco': idgreco, 'iddemande': iddemande, }) - return sudsobject_to_dict(resp) + return {'data': sudsobject_to_dict(resp)} - @endpoint(name='add-information', serializer_type='json-api', perm='can_access', + @endpoint(name='add-information', perm='can_access', methods=['get', 'post', 'put', 'patch']) def add_information(self, request, iddemande=None, idgreco=None, information=None): if request.body: @@ -166,9 +166,9 @@ class Greco(BaseResource): 'iddemande': iddemande, 'complementInfo': information, }) - return sudsobject_to_dict(resp) + return {'data': sudsobject_to_dict(resp)} - @endpoint(serializer_type='json-api', perm='can_access', + @endpoint(perm='can_access', methods=['get', 'post', 'put', 'patch']) def update(self, request, iddemande=None, idgreco=None, comment=None): if request.body: @@ -183,4 +183,4 @@ class Greco(BaseResource): 'iddemande': iddemande, 'commentaire': comment, }) - return sudsobject_to_dict(resp) + return {'data': sudsobject_to_dict(resp)} diff --git a/passerelle/contrib/iparapheur/models.py b/passerelle/contrib/iparapheur/models.py index 1d9998a..6dd6a84 100644 --- a/passerelle/contrib/iparapheur/models.py +++ b/passerelle/contrib/iparapheur/models.py @@ -75,31 +75,31 @@ class IParapheur(BaseResource): def get_verbose_name(cls): return cls._meta.verbose_name - @endpoint(serializer_type='json-api', perm='can_access') + @endpoint(perm='can_access') def types(self, request): c = get_client(self) - return [format_type(t) for t in c.service.GetListeTypes()] + return {'data': [format_type(t) for t in c.service.GetListeTypes()]} - @endpoint(serializer_type='json-api', perm='can_access') + @endpoint(perm='can_access') def ping(self, request): c = get_client(self) - return c.service.echo('ping') + return {'data': c.service.echo('ping')} - @endpoint(serializer_type='json-api', perm='can_access') + @endpoint(perm='can_access') def subtypes(self, request, type=None): c = get_client(self) if type: - return [format_type(t) for t in c.service.GetListeSousTypes(type)] - return [format_type(t) for t in c.service.GetListeSousTypes()] + return {'data': [format_type(t) for t in c.service.GetListeSousTypes(type)]} + return {'data': [format_type(t) for t in c.service.GetListeSousTypes()]} - @endpoint(serializer_type='json-api', perm='can_access') + @endpoint(perm='can_access') def files(self, request, status=None): c = get_client(self) if status: - return [format_file(f) for f in c.service.RechercherDossiers(Status=status)] - return [format_file(f) for f in c.service.RechercherDossiers()] + return {'data': [format_file(f) for f in c.service.RechercherDossiers(Status=status)]} + return {'data': [format_file(f) for f in c.service.RechercherDossiers()]} - @endpoint(serializer_type='json-api', perm='can_access', name='create-file', methods=['post']) + @endpoint(perm='can_access', name='create-file', methods=['post']) def create_file(self, request, email=None): data = json.loads(request.body) title = data['title'] @@ -130,10 +130,9 @@ class IParapheur(BaseResource): r = c.service.CreerDossier(**d) if r.MessageRetour.codeRetour == 'KO': raise FileError(r.MessageRetour.message) - return {'RecordId': r.DossierID, - 'message': r.MessageRetour.message} + return {'data': {'RecordId': r.DossierID, 'message': r.MessageRetour.message}} - @endpoint(serializer_type='json-api', perm='can_access', name='get-file', pattern='(?P[\w-]+)') + @endpoint(perm='can_access', name='get-file', pattern='(?P[\w-]+)') def get_file(self, request, file_id): client = get_client(self) resp = client.service.GetDossier(file_id) @@ -146,7 +145,7 @@ class IParapheur(BaseResource): return HttpResponse(base64.b64decode(fichier['value']), content_type=fichier['_contentType']) - @endpoint(serializer_type='json-api', perm='can_access', name='get-file-status', pattern='(?P[\w-]+)') + @endpoint(perm='can_access', name='get-file-status', pattern='(?P[\w-]+)') def get_file_status(self, request, file_id): c = get_client(self) resp = c.service.GetHistoDossier(file_id) @@ -155,6 +154,7 @@ class IParapheur(BaseResource): raise Http404(resp.MessageRetour.message) raise FileError(resp.MessageRetour.message) last = resp.LogDossier[-1] - return {'annotation': last.annotation, 'nom': last.nom, + return {'data': { + 'annotation': last.annotation, 'nom': last.nom, 'status': last.status, 'timestamp': last.timestamp - } + }} diff --git a/passerelle/contrib/mdel/models.py b/passerelle/contrib/mdel/models.py index 3152465..c3f00c7 100644 --- a/passerelle/contrib/mdel/models.py +++ b/passerelle/contrib/mdel/models.py @@ -84,7 +84,7 @@ class MDEL(BaseResource): def get_verbose_name(cls): return cls._meta.verbose_name - @endpoint(serializer_type='json-api', perm='can_access', methods=['post']) + @endpoint(perm='can_access', methods=['post']) def create(self, request, *args, **kwargs): """Create a demand """ @@ -121,9 +121,9 @@ class MDEL(BaseResource): demand.save() - return {'demand_id': demand.demand_id} + return {'data': {'demand_id': demand.demand_id}} - @endpoint(serializer_type='json-api', perm='can_access') + @endpoint(perm='can_access') def status(self, request, *args, **kwargs): """Return demand's statutes """ @@ -136,21 +136,21 @@ class MDEL(BaseResource): status = demand.get_status() demand.save() - return status + return {'data': status} - @endpoint(serializer_type='json-api', perm='can_access') + @endpoint(perm='can_access') def applicants(self, request, without=''): - return [item for item in APPLICANTS - if item.get('id') not in without.split(',')] + return {'data': [item for item in APPLICANTS + if item.get('id') not in without.split(',')]} - @endpoint(serializer_type='json-api', perm='can_access') + @endpoint(perm='can_access') def certificates(self, request): - return CERTIFICATES + return {'data': CERTIFICATES} - @endpoint(name='certificate-types', serializer_type='json-api', perm='can_access') + @endpoint(name='certificate-types', perm='can_access') def certificate_types(self, request, without=''): - return [item for item in CERTIFICATE_TYPES - if item.get('id') not in without.split(',')] + return {'data': [item for item in CERTIFICATE_TYPES + if item.get('id') not in without.split(',')]} class Demand(models.Model): diff --git a/passerelle/contrib/nancypoll/models.py b/passerelle/contrib/nancypoll/models.py index 09a12af..6e5325e 100644 --- a/passerelle/contrib/nancypoll/models.py +++ b/passerelle/contrib/nancypoll/models.py @@ -31,7 +31,7 @@ class NancyPoll(BaseResource): def get_icon_class(cls): return 'grid' - @endpoint(serializer_type='json-api') + @endpoint() def data(self, request, *args, **kwargs): street_no = request.GET.get('street_no') street_name = request.GET.get('street_name') @@ -71,13 +71,13 @@ class NancyPoll(BaseResource): if row[idx_side] == 'P' and int(street_no) % 2 == 1: continue - return { + return {'data': { 'id': row[titles.index('id')], 'text': row[titles.index('text')], 'code': row[titles.index('code')], 'address': row[titles.index('address')], 'canton': row[titles.index('canton')], - } + }} raise APIError('Polling Station Not Found') diff --git a/passerelle/sms/__init__.py b/passerelle/sms/__init__.py index f43a52e..4fc3d3b 100644 --- a/passerelle/sms/__init__.py +++ b/passerelle/sms/__init__.py @@ -33,7 +33,7 @@ class SMSGatewayMixin(object): numbers.append(number) return numbers - @endpoint('json-api', perm='can_send_messages', methods=['post']) + @endpoint(perm='can_send_messages', methods=['post']) def send(self, request, *args, **kwargs): try: data = json.loads(request.body) @@ -50,5 +50,5 @@ class SMSGatewayMixin(object): logging.info('sending message %r to %r with sending number %r', data['message'], data['to'], data['from']) if 'nostop' in request.GET: - return self.send_msg(data['message'], data['from'], data['to'], stop=False) - return self.send_msg(data['message'], data['from'], data['to'], stop=True) + return {'data': self.send_msg(data['message'], data['from'], data['to'], stop=False)} + return {'data': self.send_msg(data['message'], data['from'], data['to'], stop=True)} diff --git a/passerelle/utils/api.py b/passerelle/utils/api.py index 84ed373..5ef5f60 100644 --- a/passerelle/utils/api.py +++ b/passerelle/utils/api.py @@ -16,8 +16,8 @@ class endpoint(object): - def __init__(self, serializer_type='json', perm=None, methods=['get'], name=None, pattern=None, - wrap_response=True): + def __init__(self, serializer_type='json-api', perm=None, methods=['get'], name=None, pattern=None, + wrap_response=False): self.perm = perm self.methods = methods self.serializer_type = serializer_type diff --git a/passerelle/utils/jsonresponse.py b/passerelle/utils/jsonresponse.py index 6e2dcb1..a4126f6 100644 --- a/passerelle/utils/jsonresponse.py +++ b/passerelle/utils/jsonresponse.py @@ -309,6 +309,8 @@ class to_json(object): d.update({"data": obj}) return d else: + if isinstance(obj, dict) and not 'err' in obj: + obj['err'] = 0 return obj def err_to_response(self, err): diff --git a/tests/test_jsondatastore.py b/tests/test_jsondatastore.py index 2a89cd6..683ff9b 100644 --- a/tests/test_jsondatastore.py +++ b/tests/test_jsondatastore.py @@ -27,7 +27,7 @@ def jsondatastore2(db): def test_jsondatastore(app, jsondatastore, jsondatastore2): resp = app.get('/jsondatastore/foobar/data/') - assert resp.json == {'data': []} + assert resp.json == {'data': [], 'err': 0} resp = app.post_json('/jsondatastore/foobar/data/create', params={'foo': 'bar'}) uuid = resp.json['id'] @@ -62,7 +62,7 @@ def test_jsondatastore(app, jsondatastore, jsondatastore2): def test_jsondatastore_name_id(app, jsondatastore): resp = app.get('/jsondatastore/foobar/data/') - assert resp.json == {'data': []} + assert resp.json == {'data': [], 'err': 0} resp = app.post_json('/jsondatastore/foobar/data/create?name_id=xxx', params={'foo': 'bar'}) uuid = resp.json['id'] diff --git a/tests/test_jsonresponse.py b/tests/test_jsonresponse.py index fadcdd9..759bfa7 100644 --- a/tests/test_jsonresponse.py +++ b/tests/test_jsonresponse.py @@ -170,7 +170,7 @@ def test_jsonresponse_without_wrapping(): return {"foo": "bar"} result = test_func(req) data = json.loads(result.content) - assert data == {"foo": "bar"} + assert data == {"foo": "bar", "err": 0} def test_jsonresponse_with_callback(): request = RequestFactory() -- 2.13.1