--- /dev/null
+#!/usr/bin/python3
+# -*- coding: utf-8 -*-
+"""
+export4kaboom - Outil d'export des référentiels adapté pour Kaboom
+
+Copyright : Agence universitaire de la Francophonie — www.auf.org
+Licence : GNU General Public Licence, version 3
+Auteur : Jean Christophe André
+Création : 20 octobre 2017
+
+Debian-Depends:
+
+Mise en place dans Apache :
+ ScriptAlias /export4kaboom /usr/local/lib/export4kaboom
+Usage :
+ http://references.auf.org/export4kaboom/implantations.json
+ http://references.auf.org/export4kaboom/etablissements.json
+"""
+import os
+import sys
+import json
+import urllib.request
+
+def http_reply(data, mime_type=None, charset=None, headers={}, outfile=sys.stdout):
+ if data is None:
+ data = ''
+ # préparation des champs MIME
+ if mime_type is None:
+ mime_type = 'text/plain'
+ if charset is None:
+ charset = getattr(outfile, 'encoding', None)
+ if charset:
+ charset_spec = '; charset={}'.format(charset)
+ else:
+ charset_spec = ''
+ # préparation des en-têtes de la réponse
+ _headers = {
+ 'Content-Type': '{}{}'.format(mime_type, charset_spec),
+ 'Content-Length': len(data) if data else 0,
+ 'Status': '200 OK',
+ 'Pragma': 'no-cache',
+ 'Expires': '0',
+ #'Vary': 'Content-Encoding',
+ }
+ if headers:
+ _headers.update(headers)
+ # envoi de la réponse
+ _headers = ''.join(("{}: {}\r\n".format(k, v) for k,v in _headers.items()))
+ outfile.write(_headers + "\r\n")
+ outfile.write(data)
+ outfile.flush()
+
+def http_redirect(location):
+ data = """If you see this, it means the automatic redirection has \
+ failed.\r\nPlease go to {}\r\n""".format(location)
+ headers = {'Status': '302 Redirection', 'Location': location}
+ http_reply(data, headers=headers)
+
+def country_code_to_name(data, fields=[]):
+ res = urllib.request.urlopen('http://references.auf.org/export/pays.json')
+ country = json.loads(res.read().decode('utf-8'))
+ country = {x['code']: x for x in country}
+ for x in data:
+ for f in fields:
+ x.update({f+'_nom': country[x[f]]['nom']})
+
+if __name__ == '__main__':
+ # initialisation
+ path_info = os.environ.get('PATH_INFO', '')
+ path_prefix = os.environ.get('REQUEST_URI', '')
+ if len(path_info) > 0:
+ path_prefix = path_prefix[:-len(path_info)]
+ # routage
+ if path_info == '':
+ http_redirect(path_prefix + '/')
+ elif path_info == '/':
+ l = [
+ '/export/pays.json',
+ '/export4kaboom/implantations.json',
+ '/export4kaboom/etablissements.json',
+ ]
+ l = ['<li><a href="%s">%s</a></li>' % (f, f) for f in sorted(l)]
+ title = '<p>Liste des exports disponibles :</p>\n'
+ data = '<html>\n' + title + '<ul>\n' + '\n'.join(l) + '\n</ul>\n</html>'
+ http_reply(data, headers={'Content-Type': 'text/html'})
+ elif path_info == '/etablissements.json':
+ res = urllib.request.urlopen('http://references.auf.org/export/etablissements.json')
+ data = json.loads(res.read().decode('utf-8'))
+ data = [x for x in data if x['membre'] is True] # juste les membres
+ country_code_to_name(data, ['pays'])
+ data = json.dumps(data, indent=' ')
+ http_reply(data, mime_type='application/json')
+ elif path_info == '/implantations.json':
+ res = urllib.request.urlopen('http://references.auf.org/export/implantations.json')
+ data = json.loads(res.read().decode('utf-8'))
+ data = [x for x in data if x['statut'] == 1] # juste les ouvertes
+ country_code_to_name(data, ['adresse_physique_pays', 'adresse_postale_pays'])
+ data = json.dumps(data, indent=' ')
+ http_reply(data, mime_type='application/json')
+ else: # réponse par défaut
+ http_reply("Requête '{}' non gérée.".format(path_info))
+ sys.exit(0)