Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #! /usr/bin/python
- # -*- coding: utf-8 -*-
- """
- @apiDefine Logged
- """
- import json
- import requests
- import mysql.connector
- from functools import wraps
- from flask import Flask, request, Response, session
- from lxml import etree
- app = Flask(__name__)
- key = "GOCpRtmegQpOq48OAwpo"
- db = mysql.connector.connect(host="localhost",user="root",password="", database="db_tpg")
- app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
- def check_auth(username, password):
- cursor = db.cursor()
- query = ("SELECT id_Users, password FROM Users WHERE login LIKE '"+username+"'")
- cursor.execute(query)
- ori_Pwd = cursor.fetchone()
- db.close()
- if ori_Pwd[1] == password:
- session['id'] = ori_Pwd[0]
- session['username'] = username
- return True
- else:
- return False
- def authenticate():
- """Sends a 401 response that enables basic auth"""
- return Response(
- 'Could not verify your access level for that URL.\n'
- 'You have to login with proper credentials', 401,
- {'WWW-Authenticate': 'Basic realm="Login Required"'})
- def requires_auth(f):
- @wraps(f)
- def decorated(*args, **kwargs):
- auth = request.authorization
- if not auth or not check_auth(auth.username, auth.password):
- return authenticate()
- return f(*args, **kwargs)
- return decorated
- def getAllStops(key, format):
- url = "http://prod.ivtr-od.tpg.ch/v1/GetStops."+format+"?key=" + key
- if format == 'xml':
- response = etree.parse(url)
- return response
- elif format == 'json':
- response = requests.get(url)
- return response.content
- else:
- print('Bad Format')
- def modifyTPG(tpg, format="json"):
- if format == 'xml':
- hepia = etree.Element("stops")
- timestamp = etree.SubElement(hepia, "timestamp")
- timestamp.text = tpg.find('timestamp').text
- stops = etree.SubElement(hepia, "stops")
- for s in tpg.find('stops').findall('stop'):
- stop = etree.SubElement(stops, "stop")
- stopCode = etree.SubElement(stop, "stopCode")
- stopCode.text = s.find('stopCode').text
- stopName = etree.SubElement(stop, "stopName")
- stopName.text = s.find('stopName').text
- return hepia
- elif format == 'json':
- hepia = {}
- hepia['timestamp'] = tpg.get('timestamp')
- stops = []
- for s in tpg.get('stops'):
- stop = {}
- stop['stopCode'] = s['stopCode']
- stop['stopName'] = s['stopName']
- stops.append(stop)
- hepia['stops'] = stops
- return hepia
- else:
- print('Bad Format')
- def getDepartures(key, stops, format):
- cursor = db.cursor()
- query = ("SELECT stopCode FROM Subscribes WHERE id_Users LIKE '" + session['id'] + "'")
- cursor.execute(query)
- favoriteStops = cursor.fetchall()
- for stop in stops:
- if stop not in favoriteStops:
- return "Arrêt n'est pas dans vos favoris";
- db.close()
- for stop in stops:
- url = "http://prod.ivtr-od.tpg.ch/v1/GetNextDepartures." + format + "?stopCode=" + stop + "&key=" + key
- if format == 'xml':
- if response == None:
- response = etree.parse(url)
- else:
- response.append(etree.parse(url))
- elif format == 'json':
- if response == None:
- response = requests.get(url)
- else:
- #TODO concat le fichier
- response
- else:
- print('Bad Format')
- if format == 'xml':
- return response
- elif format == 'json':
- return response.content
- else:
- print('Bad Format')
- def getPMR(key,stop,format):
- url = "http://prod.ivtr-od.tpg.ch/v1/GetNextDepartures." + format + "?stopCode=" + stop + "&key=" + key
- if format == 'xml':
- response = etree.parse(url)
- return response
- elif format == 'json':
- response = requests.get(url)
- return response.content
- else:
- print('Bad Format')
- def modifyPMR(tpg, format):
- if format == 'xml':
- hepia = etree.Element("nextDepartures")
- timestamp = etree.SubElement(hepia, "timestamp")
- timestamp.text = tpg.find('timestamp').text
- stop = etree.SubElement(hepia, "stop")
- stopCode = etree.SubElement(stop, "stopCode")
- stopCode.text = tpg.find('stop').find('stopCode').text
- stopName = etree.SubElement(stop, "stopName")
- stopName.text = tpg.find('stop').find('stopName').text
- departures = etree.SubElement(hepia, "departures")
- for s in tpg.find('departures').findall('departure'):
- if s.find('characteristics').text != 'PMR':
- continue
- departure = etree.SubElement(departures, "departure")
- waitingTime = etree.SubElement(departure, "waitingTime")
- waitingTime.text = s.find('waitingTime').text
- destinationName = etree.SubElement(departure, "destinationName")
- destinationName.text = s.find('connection').find('destinationName').text
- lineCode = etree.SubElement(departure, "lineCode")
- lineCode.text = s.find('connection').find('lineCode').text
- return hepia
- elif format == 'json':
- hepia = {}
- hepia['timestamp'] = tpg.get('timestamp')
- hepia['stop'] = {'stopCode': tpg.get('stop').get('stopCode'),'stopName': tpg.get('stop').get('stopName')}
- departures = []
- for s in tpg.get('departures'):
- if not s.has_key('characteristics'):
- continue
- departure = {}
- departure['waitingTime'] = s['waitingTime']
- departure['destinationName'] = s.get('line').get('destinationName')
- departure['lineCode'] = s.get('line').get('lineCode')
- departures.append(departure)
- hepia['departures'] = departures
- return hepia
- else:
- print('Bad Format')
- def getAllStopsWithCoord(key, latitude, longitude, format):
- url = "http://prod.ivtr-od.tpg.ch/v1/GetStops."+format+"?latitude="+latitude+"&longitude="+longitude+"&key=" + key
- if format == 'xml':
- response = etree.parse(url)
- return response
- elif format == 'json':
- response = requests.get(url)
- return response.content
- else:
- print('Bad Format')
- def modifyTPGWithCoord(tpg, format):
- if format == 'xml':
- hepia = etree.Element("stops")
- timestamp = etree.SubElement(hepia, "timestamp")
- timestamp.text = tpg.find('timestamp').text
- stops = etree.SubElement(hepia, "stops")
- for s in tpg.find('stops').findall('stop'):
- stop = etree.SubElement(stops, "stop")
- stopCode = etree.SubElement(stop, "stopCode")
- stopCode.text = s.find('stopCode').text
- stopName = etree.SubElement(stop, "stopName")
- stopName.text = s.find('stopName').text
- distance = etree.SubElement(stop, "distance")
- distance.text = s.find('distance').text
- return hepia
- elif format == 'json':
- hepia = {}
- hepia['timestamp'] = tpg.get('timestamp')
- stops = []
- for s in tpg.get('stops'):
- stop = {}
- stop['stopCode'] = s['stopCode']
- stop['stopName'] = s['stopName']
- stop['distance'] = s['distance']
- stops.append(stop)
- hepia['stops'] = stops
- return hepia
- else:
- print('Bad Format')
- @app.route('/')
- @requires_auth
- def index():
- return str(session['id'])+" "+session['username']
- """
- @api {post} /createuser User creation
- @apiPermission Logged
- @apiVersion 0.1.0
- @apiName CreateUser
- @apiGroup User
- @apiParam {string} login User unique login.
- @apiParam {string} password User password.
- """
- @app.route('/createuser', methods=['POST'])
- def createuser():
- login = request.form['login']
- pwd = request.form['password']
- cursor = db.cursor()
- querySelect = ("SELECT login FROM Users WHERE login LIKE '" + login + "'")
- cursor.execute(querySelect)
- ori_User = cursor.fetchone()
- if ori_User == None:
- query = ("INSERT INTO Users(login, password) VALUES('" + login + "','" + pwd + "')")
- cursor.execute(query)
- db.commit()
- else:
- print("Username déjà présent")
- db.close()
- return ""
- """
- @api {get} /stoplist/:format List all stop
- @apiVersion 0.1.0
- @apiName StopList
- @apiGroup Stop
- @apiParam {string} format Specify format: XML or JSON
- @apiSuccess {XML/JSON} stoplist Stop list.
- """
- @app.route('/stoplist/<format>')
- def stoplist(format):
- if format == 'xml':
- treeTPG = getAllStops(key,format)
- newTreeTPG = modifyTPG(treeTPG, format)
- return etree.tostring(newTreeTPG, encoding='UTF-8', xml_declaration=True)
- elif format == 'json':
- dec = json.JSONDecoder().decode(getAllStops(key, format))
- g = modifyTPG(dec, format)
- h = json.JSONEncoder(ensure_ascii=False).encode(g)
- return h
- else:
- print('Bad Format')
- """
- @api {post} /subscribe Subscribe stop
- @apiPermission Logged
- @apiVersion 0.1.0
- @apiName Subscribe
- @apiGroup Subscribe
- @apiParam {string} stopCode Stop to subscribe.
- """
- @app.route('/subscribe', methods=['POST'])
- @requires_auth
- def subscribe():
- stopCode = request.form['stopCode']
- cursor = db.cursor()
- query = ("INSERT INTO Subscribes(stopCode, id_Users) VALUES('" + stopCode + "','" + session['id'] + "')")
- cursor.execute(query)
- db.commit()
- db.close()
- return ""
- """
- @api {delete} /unsubscribe Unsubscribe stop
- @apiPermission Logged
- @apiVersion 0.1.0
- @apiName Unsubscribe
- @apiGroup Subscribe
- @apiParam {string} stopCode Stop to unsubscribe.
- """
- @app.route('/unsubscribe', methods=['DELETE'])
- @requires_auth
- def unsubscribe():
- stopCode = request.form['stopCode']
- cursor = db.cursor()
- query = ("DELETE FROM Subscribes WHERE stopCode LIKE '"+stopCode+"' AND id_Users LIKE '"+session['id']+"'")
- cursor.execute(query)
- db.commit()
- return ""
- """
- @api {get} /departures/:format/:stops List all custom departures
- @apiPermission Logged
- @apiVersion 0.1.0
- @apiName getAllDepartures
- @apiGroup Stop
- @apiParam {string} format Specify format: XML or JSON
- @apiParam {string[]} stops Specify stops to display
- @apiSuccess {XML/JSON} departureList All custom departures.
- """
- @app.route('/departures/<format>/<stops>')
- @requires_auth
- def departures(format, stops):
- #TODO ERROR avec le cursor..
- if stops == None:
- cursor = db.cursor()
- query = ("SELECT stopCode FROM Subscribes WHERE id_Users LIKE '" + session['id'] + "'")
- cursor.execute(query)
- stops = cursor.fetchall()
- db.close
- if format == 'xml':
- treeTPG = getDepartures(key, stops, format)
- print(treeTPG)
- elif format == 'json':
- print('JSON')
- else:
- print('Bad Format')
- """
- @api {get} /pmrstop/:stopCode/:format List all bus with pmr support at a specified stop.
- @apiVersion 0.1.0
- @apiName getPMR
- @apiGroup Stop
- @apiParam {string} stopCode Specified stop.
- @apiParam {string} format Specify format: XML or JSON
- @apiSuccess {XML/JSON} BusList All bus with pmr support.
- """
- @app.route('/pmrstop/<stopCode>/<format>')
- def pmrstop(stopCode, format):
- if format == 'xml':
- treeTPG = getPMR(key,stopCode,format)
- newTreeTPG = modifyPMR(treeTPG, format)
- return etree.tostring(newTreeTPG, encoding='UTF-8', xml_declaration=True)
- elif format == 'json':
- dec = json.JSONDecoder().decode(getPMR(key,stopCode,format))
- g = modifyPMR(dec, format)
- h = json.JSONEncoder(ensure_ascii=False).encode(g)
- return h
- else:
- print('Bad Format')
- """
- @api {get} /coordstop/:latitude/:longitude/:format List all stop near 500m by a latitude and longitude
- @apiVersion 0.1.0
- @apiName getPositionByLatitudeLongitude
- @apiGroup Stop
- @apiParam {Double} Latitude Specify a latitude
- @apiParam {Double} Longitude Specify a longitude
- @apiParam {string} format Specify format: XML or JSON
- @apiSuccess {XML/JSON} Stops All stops near of 500 meter
- """
- @app.route('/coordstop/<latitude>/<longitude>/<format>')
- def coordstop(latitude, longitude, format):
- if format == 'xml':
- treeTPG = getAllStopsWithCoord(key, latitude, longitude, format)
- newTreeTPG = modifyTPGCoord(treeTPG, format)
- return etree.tostring(newTreeTPG, encoding='UTF-8', xml_declaration=True)
- elif format == 'json':
- dec = json.JSONDecoder().decode(getAllStopsWithCoord(key, latitude, longitude, format))
- g = modifyTPGWithCoord(dec, format)
- h = json.JSONEncoder(ensure_ascii=False).encode(g)
- return h
- else:
- print('Bad Format')
- if __name__ == '__main__':
- app.run(debug=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement