2564: API fournir le détail des données d'un chercheur - Partie 1
[auf_savoirs_en_partage_django.git] / auf_savoirs_en_partage / chercheurs / api.py
CommitLineData
bf563475
NBV
1# -*- encoding: utf-8 -*
2from django.http import HttpResponse
3from django.core import serializers
5b3ac131
NBV
4from django.shortcuts import get_object_or_404
5
bf563475
NBV
6from chercheurs.models import Chercheur
7
8STATUS_OK = 200
9STATUS_ERROR = 400
10STATUS_ERROR_PERMISSIONS = 403
11STATUS_ERROR_NOT_FOUND = 404
12STATUS_ERROR_BADMETHOD = 405
13
5b3ac131 14def api(request, pays=None, region=None, id=None):
bf563475 15 api = API(request)
5b3ac131
NBV
16 if id is not None:
17 return api.api_chercheur(id)
18 else:
19 return api.api_chercheurs_liste(pays=pays, region=region, id=id)
bf563475
NBV
20
21def api_return(status, text='', json=False):
22 content_type = 'text/html'
23 if status == STATUS_OK and json:
24 content_type = 'text/json'
25 if text is None:
26 if status == STATUS_ERROR:
27 text = 'Error'
28 elif status == STATUS_ERROR_NOT_FOUND:
29 text = 'Resource Not Found'
30 elif status == STATUS_ERROR_PERMISSIONS:
31 text = 'Invalid username or password'
32 elif status == STATUS_ERROR_BADMETHOD:
33 text = 'Invalid request method'
34 elif status == STATUS_OK:
35 text = 'OK'
36
37 r = HttpResponse(status=status, content=text, content_type=content_type)
38
39 if status == STATUS_ERROR_BADMETHOD:
40 r.Allow = 'POST'
41
42 return r
43
44class API:
45 def __init__(self, request):
46 self.request = request
47
5b3ac131
NBV
48 def api_chercheur(self, id):
49 chercheur = get_object_or_404(Chercheur, id=id)
50 data = serializers.serialize('json', [chercheur])
51 return api_return(STATUS_OK, data, True)
52
53 def api_chercheurs_liste(self, pays=None, region=None, id=None):
bf563475
NBV
54 if pays is not None:
55 chercheurs = Chercheur.objects.filter_pays(pays)
87567c72 56 elif region is not None:
ebde48e0 57 chercheurs = Chercheur.objects.filter_region(region)
bf563475
NBV
58 else:
59 return api_return(STATUS_ERROR, "Erreur dans la requete de recherche de chercheurs")
60
61 data = serializers.serialize('json', chercheurs)
5b3ac131 62 return api_return(STATUS_OK, data, True)