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