| 1 | # -*- encoding: utf-8 -* |
| 2 | from django.http import HttpResponse |
| 3 | from django.core import serializers |
| 4 | from chercheurs.models import Chercheur |
| 5 | |
| 6 | STATUS_OK = 200 |
| 7 | STATUS_ERROR = 400 |
| 8 | STATUS_ERROR_PERMISSIONS = 403 |
| 9 | STATUS_ERROR_NOT_FOUND = 404 |
| 10 | STATUS_ERROR_BADMETHOD = 405 |
| 11 | |
| 12 | def api(request, pays=None, region_id=None, *args, **kwargs): |
| 13 | api = API(request) |
| 14 | # if not hasattr(api, 'api_%s' % method): |
| 15 | # return api_return(STATUS_ERROR) |
| 16 | # if pays is not None: |
| 17 | return api.api_chercheurs_liste(pays=pays, region_id=region_id) |
| 18 | #elif region_id is not None: |
| 19 | # return api.api_chercheurs_liste(region_id=region_id) |
| 20 | |
| 21 | def 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 | |
| 44 | class API: |
| 45 | def __init__(self, request): |
| 46 | self.request = request |
| 47 | |
| 48 | def api_chercheurs_liste(self, pays=None, region_id=None): |
| 49 | import pdb;pdb.set_trace() |
| 50 | if pays is not None: |
| 51 | chercheurs = Chercheur.objects.filter_pays(pays) |
| 52 | elif region_id is not None: |
| 53 | chercheurs = Chercheur.objects.filter_region(region_id) |
| 54 | else: |
| 55 | return api_return(STATUS_ERROR, "Erreur dans la requete de recherche de chercheurs") |
| 56 | |
| 57 | data = serializers.serialize('json', chercheurs) |
| 58 | return api_return(STATUS_OK, data) |