9b368c744cc38a05318863db2272c7c4bec386b9
[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 class API:
23 def __init__(self, request, env):
24 self.request = request
25 self.env = env
26
27 def offre_emploi_liste(self,):
28 url = settings.RECRUTEMENT_URLS[self.env] + "offre_emploi_liste/"
29 r = req(url)
30 data = r.body_string()
31 offres = [offre.object for offre in serializers.deserialize("json", data)]
32 return offres
33
34 def offre_emploi(self, offre_id, env):
35 url = settings.RECRUTEMENT_URLS[self.env] + "offre_emploi/?id=%s"
36 r = req(url % offre_id)
37 offre_json = r.body_string()
38 data = r.body_string()
39 offres = [o.object for o in serializers.deserialize("json", data)]
40 if len(offres) == 0:
41 return offres[0]
42 else:
43 return offres
44
45 def candidat_add(self, offre_id,):
46 url = settings.RECRUTEMENT_URLS[self.env] + "candidat_add/%s/" % offre_id
47 r = Resource(url)
48 params = self.request.POST
49 for k, up_file in self.request.FILES.items():
50 params[k] = up_file
51 opener = poster.streaminghttp.register_openers()
52 datagen, headers = poster.encode.multipart_encode(params)
53 request = urllib2.Request(url, datagen, headers)
54 resp = urllib2.urlopen(request)
55 if resp.code == STATUS_OK:
56 candidats = [c.object for c in serializers.deserialize("json", resp.read())]
57 if len(candidats) == 1:
58 return candidats[0]
59 return None