6f4179cd9c20b1060bdd3f40d71408076405d6de
[auf_django_emploi.git] / auf / django / emploi / api.py
1 # -*- encoding: utf-8 -*
2 from django.core import serializers
3 from django.shortcuts import render_to_response, redirect, get_object_or_404
4 from django.template import Context, RequestContext
5 from django.utils import simplejson
6 from auf.django.emploi import models as emploi
7 from restkit import request, Resource
8 import datamaster_modeles.models as ref
9 import poster
10 import urllib2
11 from auf.django.emploi import settings
12
13
14 STATUS_OK = 200
15
16 def req(*args, **kwargs):
17 timeout = 10
18 if not kwargs.has_key('timeout'):
19 kwargs['timeout'] = timeout
20 return request(*args, **kwargs)
21
22 def read_response(request):
23 return request._body.raw.read()
24
25 class API:
26 def __init__(self, request, env):
27 self.request = request
28 self.env = env
29
30 def offre_emploi_liste(self,):
31 url = settings.RECRUTEMENT_URLS[self.env] + "offre_emploi_liste/"
32 r = req(url)
33 data = read_response(r)
34 offres = [offre.object for offre in serializers.deserialize("json", data)]
35 return offres
36
37 def offre_emploi(self, offre_id):
38 url = settings.RECRUTEMENT_URLS[self.env] + "offre_emploi/?id=%s"
39 r = req(url % offre_id)
40 data = read_response(r)
41 offres = [o.object for o in serializers.deserialize("json", data)]
42 if len(offres) == 0:
43 return offres[0]
44 else:
45 return offres
46
47 def candidat_add(self, offre_id,):
48 url = settings.RECRUTEMENT_URLS[self.env] + "candidat_add/%s/" % offre_id
49 r = Resource(url)
50 params = self.request.POST
51 for k, up_file in self.request.FILES.items():
52 params[k] = up_file
53 opener = poster.streaminghttp.register_openers()
54 datagen, headers = poster.encode.multipart_encode(params)
55 request = urllib2.Request(url, datagen, headers)
56 resp = urllib2.urlopen(request)
57 if resp.code == STATUS_OK:
58 candidats = [c.object for c in serializers.deserialize("json", resp.read())]
59 if len(candidats) == 1:
60 return candidats[0]
61 return None