Advertisement
Guest User

Serveur_TPG

a guest
Nov 13th, 2016
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 12.92 KB | None | 0 0
  1. #! /usr/bin/python
  2. # -*- coding: utf-8 -*-
  3.  
  4. """
  5. @apiDefine Logged
  6. """
  7. import json
  8. import requests
  9. import mysql.connector
  10. from functools import wraps
  11. from flask import Flask, request, Response, session
  12. from lxml import etree
  13. app = Flask(__name__)
  14.  
  15. key = "GOCpRtmegQpOq48OAwpo"
  16. db = mysql.connector.connect(host="localhost",user="root",password="", database="db_tpg")
  17. app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
  18.  
  19. def check_auth(username, password):
  20.     cursor = db.cursor()
  21.     query = ("SELECT id_Users, password FROM Users WHERE login LIKE '"+username+"'")
  22.     cursor.execute(query)
  23.     ori_Pwd = cursor.fetchone()
  24.  
  25.     db.close()
  26.  
  27.     if ori_Pwd[1] == password:
  28.         session['id'] = ori_Pwd[0]
  29.         session['username'] = username
  30.         return True
  31.     else:
  32.         return False
  33.  
  34.  
  35. def authenticate():
  36.     """Sends a 401 response that enables basic auth"""
  37.     return Response(
  38.         'Could not verify your access level for that URL.\n'
  39.         'You have to login with proper credentials', 401,
  40.         {'WWW-Authenticate': 'Basic realm="Login Required"'})
  41.  
  42. def requires_auth(f):
  43.     @wraps(f)
  44.     def decorated(*args, **kwargs):
  45.         auth = request.authorization
  46.         if not auth or not check_auth(auth.username, auth.password):
  47.             return authenticate()
  48.         return f(*args, **kwargs)
  49.     return decorated
  50.  
  51.  
  52. def getAllStops(key, format):
  53.     url = "http://prod.ivtr-od.tpg.ch/v1/GetStops."+format+"?key=" + key
  54.     if format == 'xml':
  55.         response = etree.parse(url)
  56.         return response
  57.     elif format == 'json':
  58.         response = requests.get(url)
  59.         return response.content
  60.     else:
  61.         print('Bad Format')
  62.  
  63. def modifyTPG(tpg, format="json"):
  64.     if format == 'xml':
  65.         hepia = etree.Element("stops")
  66.         timestamp = etree.SubElement(hepia, "timestamp")
  67.         timestamp.text = tpg.find('timestamp').text
  68.         stops = etree.SubElement(hepia, "stops")
  69.         for s in tpg.find('stops').findall('stop'):
  70.             stop = etree.SubElement(stops, "stop")
  71.             stopCode = etree.SubElement(stop, "stopCode")
  72.             stopCode.text = s.find('stopCode').text
  73.             stopName = etree.SubElement(stop, "stopName")
  74.             stopName.text = s.find('stopName').text
  75.         return hepia
  76.     elif format == 'json':
  77.         hepia = {}
  78.         hepia['timestamp'] = tpg.get('timestamp')
  79.         stops = []
  80.         for s in tpg.get('stops'):
  81.             stop = {}
  82.             stop['stopCode'] = s['stopCode']
  83.             stop['stopName'] = s['stopName']
  84.             stops.append(stop)
  85.         hepia['stops'] = stops
  86.         return hepia
  87.     else:
  88.         print('Bad Format')
  89.  
  90. def getDepartures(key, stops, format):
  91.     cursor = db.cursor()
  92.     query = ("SELECT stopCode FROM Subscribes WHERE id_Users LIKE '" + session['id'] + "'")
  93.     cursor.execute(query)
  94.     favoriteStops = cursor.fetchall()
  95.     for stop in stops:
  96.         if stop not in favoriteStops:
  97.             return "Arrêt n'est pas dans vos favoris";
  98.     db.close()
  99.  
  100.     for stop in stops:
  101.         url = "http://prod.ivtr-od.tpg.ch/v1/GetNextDepartures." + format + "?stopCode=" + stop + "&key=" + key
  102.         if format == 'xml':
  103.             if response == None:
  104.                 response = etree.parse(url)
  105.             else:
  106.                 response.append(etree.parse(url))
  107.         elif format == 'json':
  108.             if response == None:
  109.                 response = requests.get(url)
  110.             else:
  111.                 #TODO concat le fichier
  112.                 response
  113.         else:
  114.             print('Bad Format')
  115.  
  116.     if format == 'xml':
  117.         return response
  118.     elif format == 'json':
  119.         return response.content
  120.     else:
  121.         print('Bad Format')
  122.  
  123. def getPMR(key,stop,format):
  124.     url = "http://prod.ivtr-od.tpg.ch/v1/GetNextDepartures." + format + "?stopCode=" + stop + "&key=" + key
  125.     if format == 'xml':
  126.         response = etree.parse(url)
  127.         return response
  128.     elif format == 'json':
  129.         response = requests.get(url)
  130.         return response.content
  131.     else:
  132.         print('Bad Format')
  133.  
  134. def modifyPMR(tpg, format):
  135.  
  136.     if format == 'xml':
  137.         hepia = etree.Element("nextDepartures")
  138.         timestamp = etree.SubElement(hepia, "timestamp")
  139.         timestamp.text = tpg.find('timestamp').text
  140.         stop = etree.SubElement(hepia, "stop")
  141.         stopCode = etree.SubElement(stop, "stopCode")
  142.         stopCode.text = tpg.find('stop').find('stopCode').text
  143.         stopName = etree.SubElement(stop, "stopName")
  144.         stopName.text = tpg.find('stop').find('stopName').text
  145.  
  146.         departures = etree.SubElement(hepia, "departures")
  147.  
  148.         for s in tpg.find('departures').findall('departure'):
  149.             if s.find('characteristics').text != 'PMR':
  150.                continue
  151.  
  152.             departure = etree.SubElement(departures, "departure")
  153.             waitingTime = etree.SubElement(departure, "waitingTime")
  154.             waitingTime.text = s.find('waitingTime').text
  155.             destinationName = etree.SubElement(departure, "destinationName")
  156.             destinationName.text = s.find('connection').find('destinationName').text
  157.             lineCode = etree.SubElement(departure, "lineCode")
  158.             lineCode.text = s.find('connection').find('lineCode').text
  159.         return hepia
  160.     elif format == 'json':
  161.         hepia = {}
  162.         hepia['timestamp'] = tpg.get('timestamp')
  163.         hepia['stop'] = {'stopCode': tpg.get('stop').get('stopCode'),'stopName': tpg.get('stop').get('stopName')}
  164.  
  165.         departures = []
  166.         for s in tpg.get('departures'):
  167.             if not s.has_key('characteristics'):
  168.                 continue
  169.  
  170.             departure = {}
  171.             departure['waitingTime'] = s['waitingTime']
  172.             departure['destinationName'] = s.get('line').get('destinationName')
  173.             departure['lineCode'] = s.get('line').get('lineCode')
  174.             departures.append(departure)
  175.  
  176.         hepia['departures'] = departures
  177.         return hepia
  178.     else:
  179.         print('Bad Format')
  180.  
  181.                
  182. def getAllStopsWithCoord(key, latitude, longitude, format):
  183.     url = "http://prod.ivtr-od.tpg.ch/v1/GetStops."+format+"?latitude="+latitude+"&longitude="+longitude+"&key=" + key
  184.     if format == 'xml':
  185.         response = etree.parse(url)
  186.         return response
  187.     elif format == 'json':
  188.         response = requests.get(url)
  189.         return response.content
  190.     else:
  191.         print('Bad Format')            
  192.                
  193. def modifyTPGWithCoord(tpg, format):
  194.     if format == 'xml':
  195.         hepia = etree.Element("stops")
  196.         timestamp = etree.SubElement(hepia, "timestamp")
  197.         timestamp.text = tpg.find('timestamp').text
  198.         stops = etree.SubElement(hepia, "stops")
  199.         for s in tpg.find('stops').findall('stop'):
  200.             stop = etree.SubElement(stops, "stop")
  201.             stopCode = etree.SubElement(stop, "stopCode")
  202.             stopCode.text = s.find('stopCode').text
  203.             stopName = etree.SubElement(stop, "stopName")
  204.             stopName.text = s.find('stopName').text
  205.                         distance = etree.SubElement(stop, "distance")
  206.             distance.text = s.find('distance').text
  207.         return hepia
  208.     elif format == 'json':
  209.         hepia = {}
  210.         hepia['timestamp'] = tpg.get('timestamp')
  211.         stops = []
  212.         for s in tpg.get('stops'):
  213.             stop = {}
  214.             stop['stopCode'] = s['stopCode']
  215.             stop['stopName'] = s['stopName']
  216.                         stop['distance'] = s['distance']
  217.             stops.append(stop)
  218.         hepia['stops'] = stops
  219.         return hepia
  220.     else:
  221.         print('Bad Format')    
  222.  
  223. @app.route('/')
  224. @requires_auth
  225. def index():
  226.     return str(session['id'])+" "+session['username']
  227.  
  228.  
  229. """
  230. @api {post} /createuser User creation
  231. @apiPermission Logged
  232. @apiVersion 0.1.0
  233. @apiName CreateUser
  234. @apiGroup User
  235. @apiParam {string} login User unique login.
  236. @apiParam {string} password User password.
  237. """
  238. @app.route('/createuser', methods=['POST'])
  239. def createuser():
  240.     login = request.form['login']
  241.     pwd = request.form['password']
  242.  
  243.     cursor = db.cursor()
  244.  
  245.     querySelect = ("SELECT login FROM Users WHERE login LIKE '" + login + "'")
  246.     cursor.execute(querySelect)
  247.     ori_User = cursor.fetchone()
  248.  
  249.     if ori_User == None:
  250.         query = ("INSERT INTO Users(login, password) VALUES('" + login + "','" + pwd + "')")
  251.         cursor.execute(query)
  252.         db.commit()
  253.     else:
  254.         print("Username déjà présent")
  255.  
  256.     db.close()
  257.     return ""
  258.  
  259. """
  260. @api {get} /stoplist/:format List all stop
  261. @apiVersion 0.1.0
  262. @apiName StopList
  263. @apiGroup Stop
  264. @apiParam {string} format Specify format: XML or JSON
  265. @apiSuccess {XML/JSON} stoplist Stop list.
  266. """
  267. @app.route('/stoplist/<format>')
  268. def stoplist(format):
  269.     if format == 'xml':
  270.         treeTPG = getAllStops(key,format)
  271.         newTreeTPG = modifyTPG(treeTPG, format)
  272.         return etree.tostring(newTreeTPG, encoding='UTF-8', xml_declaration=True)
  273.     elif format == 'json':
  274.         dec = json.JSONDecoder().decode(getAllStops(key, format))
  275.         g = modifyTPG(dec, format)
  276.         h = json.JSONEncoder(ensure_ascii=False).encode(g)
  277.         return h
  278.     else:
  279.         print('Bad Format')
  280.  
  281.  
  282. """
  283. @api {post} /subscribe Subscribe stop
  284. @apiPermission Logged
  285. @apiVersion 0.1.0
  286. @apiName Subscribe
  287. @apiGroup Subscribe
  288. @apiParam {string} stopCode Stop to subscribe.
  289. """
  290. @app.route('/subscribe', methods=['POST'])
  291. @requires_auth
  292. def subscribe():
  293.     stopCode = request.form['stopCode']
  294.     cursor = db.cursor()
  295.  
  296.     query = ("INSERT INTO Subscribes(stopCode, id_Users) VALUES('" + stopCode + "','" + session['id'] + "')")
  297.     cursor.execute(query)
  298.     db.commit()
  299.     db.close()
  300.  
  301.     return ""
  302.  
  303.  
  304. """
  305. @api {delete} /unsubscribe Unsubscribe stop
  306. @apiPermission Logged
  307. @apiVersion 0.1.0
  308. @apiName Unsubscribe
  309. @apiGroup Subscribe
  310. @apiParam {string} stopCode Stop to unsubscribe.
  311. """
  312. @app.route('/unsubscribe', methods=['DELETE'])
  313. @requires_auth
  314. def unsubscribe():
  315.     stopCode = request.form['stopCode']
  316.     cursor = db.cursor()
  317.  
  318.     query = ("DELETE FROM Subscribes WHERE stopCode LIKE '"+stopCode+"' AND id_Users LIKE '"+session['id']+"'")
  319.     cursor.execute(query)
  320.     db.commit()
  321.  
  322.     return ""
  323.  
  324. """
  325. @api {get} /departures/:format/:stops List all custom departures
  326. @apiPermission Logged
  327. @apiVersion 0.1.0
  328. @apiName getAllDepartures
  329. @apiGroup Stop
  330. @apiParam {string} format Specify format: XML or JSON
  331. @apiParam {string[]} stops Specify stops to display
  332. @apiSuccess {XML/JSON} departureList All custom departures.
  333. """
  334. @app.route('/departures/<format>/<stops>')
  335. @requires_auth
  336. def departures(format, stops):
  337.     #TODO ERROR avec le cursor..
  338.     if stops == None:
  339.         cursor = db.cursor()
  340.         query = ("SELECT stopCode FROM Subscribes WHERE id_Users LIKE '" + session['id'] + "'")
  341.         cursor.execute(query)
  342.         stops = cursor.fetchall()
  343.         db.close
  344.  
  345.     if format == 'xml':
  346.         treeTPG = getDepartures(key, stops, format)
  347.         print(treeTPG)
  348.     elif format == 'json':
  349.         print('JSON')
  350.     else:
  351.         print('Bad Format')
  352.  
  353.  
  354.  
  355. """
  356. @api {get} /pmrstop/:stopCode/:format List all bus with pmr support at a specified stop.
  357. @apiVersion 0.1.0
  358. @apiName getPMR
  359. @apiGroup Stop
  360. @apiParam {string} stopCode Specified stop.
  361. @apiParam {string} format Specify format: XML or JSON
  362. @apiSuccess {XML/JSON} BusList All bus with pmr support.
  363. """
  364. @app.route('/pmrstop/<stopCode>/<format>')
  365. def pmrstop(stopCode, format):
  366.     if format == 'xml':
  367.         treeTPG = getPMR(key,stopCode,format)
  368.         newTreeTPG = modifyPMR(treeTPG, format)
  369.         return etree.tostring(newTreeTPG, encoding='UTF-8', xml_declaration=True)
  370.     elif format == 'json':
  371.         dec = json.JSONDecoder().decode(getPMR(key,stopCode,format))
  372.         g = modifyPMR(dec, format)
  373.         h = json.JSONEncoder(ensure_ascii=False).encode(g)
  374.         return h
  375.     else:
  376.         print('Bad Format')
  377.  
  378. """
  379. @api {get} /coordstop/:latitude/:longitude/:format List all stop near 500m by a latitude and longitude
  380. @apiVersion 0.1.0
  381. @apiName getPositionByLatitudeLongitude
  382. @apiGroup Stop
  383. @apiParam {Double} Latitude Specify a latitude
  384. @apiParam {Double} Longitude Specify a longitude
  385. @apiParam {string} format Specify format: XML or JSON
  386. @apiSuccess {XML/JSON} Stops All stops near of 500 meter
  387. """
  388. @app.route('/coordstop/<latitude>/<longitude>/<format>')
  389. def coordstop(latitude, longitude, format):
  390.     if format == 'xml':
  391.         treeTPG = getAllStopsWithCoord(key, latitude, longitude, format)
  392.         newTreeTPG = modifyTPGCoord(treeTPG, format)
  393.         return etree.tostring(newTreeTPG, encoding='UTF-8', xml_declaration=True)
  394.     elif format == 'json':
  395.         dec = json.JSONDecoder().decode(getAllStopsWithCoord(key, latitude, longitude, format))
  396.         g = modifyTPGWithCoord(dec, format)
  397.         h = json.JSONEncoder(ensure_ascii=False).encode(g)
  398.         return h
  399.     else:
  400.         print('Bad Format')        
  401.                
  402.  
  403.                
  404. if __name__ == '__main__':
  405.     app.run(debug=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement