1- import datetime , aiohttp , asyncio , garages_amsterdam , os , pymysql , time
1+ """Scrape tool for parking garage into NIPKaart system."""
2+ import cities .amsterdam as amsterdam
23
4+ import asyncio , datetime , time , os
35from dotenv import load_dotenv
46from pathlib import Path
57
68load_dotenv ()
79env_path = Path ('.' )/ '.env'
810load_dotenv (dotenv_path = env_path )
911
10- # MYSQL credentials
11- DB_SERVER = os .getenv ("DB_SERVER" )
12- DB_PORT = int (os .getenv ("DB_PORT" ))
13- DATABASE = os .getenv ("DATABASE" )
14- DB_USERNAME = os .getenv ("DB_USERNAME" )
15- DB_PASSWORD = os .getenv ("DB_PASSWORD" )
16-
1712CITY = os .getenv ("CITY" )
1813WAIT_TIME = int (os .getenv ("WAIT_TIME" ))
1914
20- SLEEP_TIME = (60 * WAIT_TIME ) # gelijk aan 10 minuten
21-
22- # Connect to MySQL
23- connection = pymysql .connect (host = DB_SERVER , port = DB_PORT , user = DB_USERNAME , password = DB_PASSWORD , database = DATABASE )
24- cursor = connection .cursor ()
25-
26- async def async_get_garages ():
27- """Get garage data from API."""
28- async with aiohttp .ClientSession () as client :
29- return await garages_amsterdam .get_garages (client )
30-
31- def check_value (value ):
32- """Check on null values."""
33- if value == "" :
34- return 0
35- else :
36- return value
37-
38- def purge_database (city ):
39- """Purge the database tabel."""
40- print (f'{ TIME } - START met leeggooien van de database' )
41- try :
42- sql = "DELETE FROM `garages_amsterdam` WHERE `city`=%s"
43- cursor .execute (sql , city )
44- connection .commit ()
45- except Exception as e :
46- print (f'MySQL error: { e } ' )
47- finally :
48- print (f'{ TIME } - Klaar met leegmaken van de database' )
49-
50- def update_database (data_set ):
51- """Update the database with new data."""
52- # purge_database(CITY)
53- print (f'{ TIME } - START bijwerken van database met nieuwe data' )
54- count = 1
55- try :
56- for item in data_set :
57- sql = """INSERT INTO `garages_amsterdam` (id, name, city, state, free_space_short, free_space_long, short_capacity, long_capacity, longitude, latitude, visibility, created_at, updated_at)
58- VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) ON DUPLICATE KEY
59- UPDATE id=values(id),
60- name=values(name),
61- state=values(state),
62- free_space_short=values(free_space_short),
63- free_space_long=values(free_space_long),
64- short_capacity=values(short_capacity),
65- long_capacity=values(long_capacity),
66- longitude=values(longitude),
67- latitude=values(latitude),
68- updated_at=values(updated_at)"""
69- val = (count , str (item .garage_name ), str (CITY ) ,str (item .state ), check_value (item .free_space_short ), check_value (item .free_space_long ), check_value (item .short_capacity ), check_value (item .long_capacity ), float (item .longitude ), float (item .latitude ), bool (True ), (datetime .datetime .now ()), (datetime .datetime .now ()))
70- cursor .execute (sql , val )
71- count += 1
72- connection .commit ()
73-
74- except Exception as e :
75- print (f'MySQL error: { e } ' )
76- finally :
77- print (f'{ TIME } - KLAAR met updaten van database' )
78-
79- def test_connection ():
80- """Test the connection with MySQL Database."""
81- try :
82- cursor .execute ('SELECT VERSION()' )
83- version = cursor .fetchone ()
84- print (f'Database version: { version [0 ]} ' )
85- except Exception as e :
86- print (f'MySQL error: { e } ' )
87- finally :
88- cursor .close ()
89- connection .close ()
15+ testing = False
9016
9117if __name__ == '__main__' :
92- print ("start scrape program" )
93- # data_set = asyncio.run(async_get_garages())
94- # test_connection()
95- while True :
96- TIME = datetime .datetime .now ().strftime ('%H:%M:%S' )
97- print (f'----------START----------' )
98- update_database (asyncio .run (async_get_garages ()))
99- print (f'----------DONE----------' )
100- time .sleep (SLEEP_TIME )
18+ print ("--- Start scraping program ---" )
19+ if testing :
20+ if CITY == "Amsterdam" :
21+ data_set = asyncio .run (amsterdam .async_get_garages ())
22+ print (data_set )
23+ amsterdam .test_connection ()
24+ else :
25+ while True :
26+ TIME = datetime .datetime .now ().strftime ('%H:%M:%S' )
27+ print (f'-------- START-{ CITY } ---------' )
28+ if CITY == "Amsterdam" :
29+ data_set = asyncio .run (amsterdam .async_get_garages ())
30+ amsterdam .update_database (data_set , CITY , TIME )
31+ print (f'--------- DONE-{ CITY } ---------' )
32+ time .sleep (60 * WAIT_TIME )
0 commit comments