Skip to content

Commit 4ffc462

Browse files
committed
Add support for DiviaVélodi + bump version n° to 2.0
1 parent 02857ce commit 4ffc462

5 files changed

Lines changed: 115 additions & 7 deletions

File tree

README.md

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# « API » Divia  Python
22

3-
Ce module servant d’« API » vous permet d’accéder aux horaires des prochains bus et tram du réseau dijonnais *Divia*, en temps réel, grâce au service *TOTEM*, et ce directement depuis un script Python !
4-
Cette bibliothèque est très largement inspirée (aussi bien sur le principe que dans la logique et les techniques utilisées) de [**divia-api** par **@gauthier-th**](https://github.com/gauthier-th/divia-api) (en JavaScript).
3+
Ce module servant d’« API » vous permet d’accéder aux horaires des prochains bus et tram du réseau dijonnais *Divia*, en temps réel, grâce au service *TOTEM*, ainsi qu’aux dispobilités en temps réels des vélos et emplacements sur les stations *DiviaVélodi*, et ce directement depuis un script Python !
4+
La partie « bus et tram » de cette bibliothèque est très largement inspirée (aussi bien sur le principe que dans la logique et les techniques utilisées) de [**divia-api** par **@gauthier-th**](https://github.com/gauthier-th/divia-api) (en JavaScript).
55

66
## Démo
77

@@ -21,7 +21,7 @@ $ pip install divia-api
2121
$ python setup.py install
2222
```
2323

24-
## Exemple d’utilisation
24+
## Exemple d’utilisation de l’API bus et tram
2525

2626
```python
2727
from divia_api import DiviaAPI
@@ -41,6 +41,22 @@ totem_result = stop.totem() # Interrogation du service TOTEM et récupération
4141
print(totem_result) # Affichage du résultat.
4242
```
4343

44+
## Exemple de l’utilisation de l’API Vélodi
45+
46+
```python
47+
from divia_api import DiviaAPI
48+
49+
velodi_api = DiviaAPI().velodi
50+
51+
station = velodi_api.find_station("Lycée Carnot") # Récupération de la station DiviaVélodi « Lycée Carnot ».
52+
53+
station = velodi_api.get_station("34") # Récupération d’une station par son identifiant. Ici, l’identifiant « 34 » correspond à la station « Lycée Carnot ».
54+
55+
realtime = station.check() # Requête de données à jour sur la disponibilité des vélos et des emplacements dans cette station.
56+
57+
print(realtime.bikes, " ", realtime.docks) # Affichage du résultat (nombre de vélos disponibles et nombre de places disponibles sur la station).
58+
```
59+
4460
## __________
4561

4662
*Divia* est une marque déposée de *Keolis Dijon*. Nous ne sommes en aucun cas affiliés à *Keolis* ou à ses filiales et succursales.

divia_api/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,6 @@
2525
__author__ = 'Firmin Launay'
2626
__license__ = 'LGPL-3.0'
2727
__copyright__ = 'divia_api Copyright (C) 2021 Firmin Launay'
28-
__version__ = '1.4'
28+
__version__ = '2.0'
2929

3030
from .api import DiviaAPI

divia_api/api.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323

2424
from requests import get
2525
from json import loads
26+
from .velodi import Velodi
2627
from .line import Line
2728
from .stop import Stop
2829
from .exceptions import InvalidWay
@@ -37,6 +38,7 @@ def __init__(self):
3738
self.network = loads(raw_network)
3839
self.lines = self.network["lignes"].values()
3940
self.stops = self.network["arrets"].values()
41+
self.velodi = Velodi()
4042

4143
def get_line(self, line_id: str) -> Line:
4244
"""Find a line by specifying its unique identifier."""

divia_api/velodi.py

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
# coding=utf-8
2+
3+
"""
4+
velodi.py
5+
6+
divia_api is a Python library that allows to retrieve the timetable
7+
of Divia’s bus and tramways straight from a Python script.
8+
Copyright (C) 2021 Firmin Launay
9+
10+
This program is free software: you can redistribute it and/or modify
11+
it under the terms of the GNU General Public License as published by
12+
the Free Software Foundation, either version 3 of the License, or
13+
(at your option) any later version.
14+
15+
This program is distributed in the hope that it will be useful,
16+
but WITHOUT ANY WARRANTY; without even the implied warranty of
17+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18+
GNU General Public License for more details.
19+
20+
You should have received a copy of the GNU General Public License
21+
along with this program. If not, see <https://www.gnu.org/licenses/>.
22+
"""
23+
24+
from requests import get
25+
from json import loads
26+
from .normalize_characters import normalize
27+
# from normalize_characters import normalize
28+
29+
30+
def update_source() -> list:
31+
raw_response = get(
32+
"https://www.divia.fr/velo/diviavelodi/ou-trouver-les-stations-diviavelodi").content.decode("utf-8")
33+
data = raw_response.split("var datas = ")[1].split(";")[0]
34+
return loads(data)["diviavelodi"]
35+
36+
37+
class FreeVelodi:
38+
def __init__(self, bikes: int, docks: int):
39+
self.bikes = bikes
40+
self.docks = docks
41+
42+
def __str__(self):
43+
return f"{self.bikes} free bikes & {self.docks} free docks."
44+
45+
46+
class VelodiStation:
47+
def __init__(self, code: str, raw_name: str, friendly_name: str):
48+
self.code = code
49+
self.raw_name = raw_name
50+
self.friendly_name = friendly_name
51+
52+
def check(self):
53+
velodi_data = update_source()
54+
query_result = list(item for item in velodi_data if (item["infos"]["code_cykleo"] == self.code))
55+
try:
56+
free = query_result[0]["infos"]["qucit"]["realtime"]
57+
return FreeVelodi(free["bikes"], free["docks"])
58+
except IndexError:
59+
raise Exception("Data not found.")
60+
61+
62+
class Velodi:
63+
def __init__(self):
64+
self.data = update_source()
65+
self.stations = []
66+
67+
for station in self.data:
68+
station_name = station["infos"]["nom"]
69+
if " - n°" in station_name.replace(" ", ' ').lower():
70+
friendly_name = " - ".join(station_name.replace(" ", ' ').split(" - ")[:-1])
71+
else:
72+
friendly_name = station_name.split(" n°")[0].split(" N°")[0]
73+
self.stations.append(VelodiStation(station["infos"]["code_cykleo"], station_name, friendly_name))
74+
75+
def find_station(self, station_name: str) -> VelodiStation:
76+
corresponding_stations = list(
77+
item for item in self.stations if (item.friendly_name == station_name) or (item.raw_name == station_name))
78+
if len(corresponding_stations) > 0:
79+
return corresponding_stations[0]
80+
corresponding_stations = list(item for item in self.stations
81+
if normalize(
82+
item.friendly_name.lower()) == normalize(station_name.lower()) or normalize(
83+
item.raw_name.lower()) == normalize(station_name.lower()))
84+
if len(corresponding_stations) > 0:
85+
return corresponding_stations[0]
86+
87+
def get_station(self, station_code: str) -> VelodiStation:
88+
corresponding_stations = list(item for item in self.stations if item.code == station_code)
89+
if len(corresponding_stations > 0):
90+
return corresponding_stations[0]

setup.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,15 +31,15 @@
3131
setup(
3232
name='divia_api',
3333
packages=['divia_api'],
34-
version='1.4',
34+
version='2.0',
3535
license='LGPL-3.0',
36-
description='divia_api is a Python library that allows to retrieve the timetable of Divia’s bus and tramways straight from a Python script.',
36+
description='divia_api is a Python library that allows to retrieve the timetable of Divia’s bus and tramways, along with some infos about DiviaVélodi bikes, straight from a Python script.',
3737
long_description=long_description,
3838
long_description_content_type='text/markdown',
3939
author='Firmin Launay',
4040
author_email='hey@firminlaunay.me',
4141
url='https://github.com/filau/python_divia_api',
42-
download_url='https://github.com/filau/python_divia_api/archive/refs/tags/1.4.tar.gz',
42+
download_url='https://github.com/filau/python_divia_api/archive/refs/tags/2.0.tar.gz',
4343
keywords=['divia', 'api', 'firmin', 'launay', 'dijon', 'bus', 'tram'],
4444
install_requires=[
4545
'requests'

0 commit comments

Comments
 (0)