e4facaf78a01aa5ca8a95b7c1e63d2947277373f
[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
23 def read_response(request):
24 """
25 La prod en Python2.5 avec restkit 3.3.2 en mode SSL
26 semble capricieuse.
27 """
28 data = request._body.raw.readall()
29 if data == '':
30 data = request._body.raw.read()
31 return data
32
33
34 class API:
35 def __init__(self, request, env):
36 self.request = request
37 self.env = env
38
39 def offre_emploi_liste(self,):
40 url = settings.RECRUTEMENT_URLS[self.env] + "offre_emploi_liste/"
41 r = req(url)
42 data = read_response(r)
43 offres = [offre.object for offre in serializers.deserialize("json", data)]
44 return offres
45
46 def offre_emploi(self, offre_id):
47 url = settings.RECRUTEMENT_URLS[self.env] + "offre_emploi/?id=%s"
48 r = req(url % offre_id)
49 data = read_response(r)
50 offres = [o.object for o in serializers.deserialize("json", data)]
51 if len(offres) == 0:
52 return offres[0]
53 else:
54 return offres
55
56 def candidat_add(self, offre_id,):
57 url = settings.RECRUTEMENT_URLS[self.env] + "candidat_add/%s/" % offre_id
58 r = Resource(url)
59 params = self.request.POST
60 for k, up_file in self.request.FILES.items():
61 params[k] = up_file
62 opener = poster.streaminghttp.register_openers()
63 datagen, headers = poster.encode.multipart_encode(params)
64 request = urllib2.Request(url, datagen, headers)
65 resp = urllib2.urlopen(request)
66 if resp.code == STATUS_OK:
67 candidats = [c.object for c in serializers.deserialize("json", resp.read())]
68 if len(candidats) == 1:
69 return candidats[0]
70 return None