main.py 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import psycopg2.extras
  2. import model
  3. from pprint import pprint
  4. import time
  5. import database
  6. if __name__ == '__main__':
  7. start = time.time()
  8. db = database.db
  9. race_days_global = model.scrape_main_page()
  10. interim = time.time()
  11. print('interim 1 {}'.format(interim - start))
  12. # pprint(race_days_global)
  13. race_days = []
  14. raw_data_dict = {}
  15. for race_day in race_days_global:
  16. raw_data = model.get_raw_scratchings(race_day)
  17. race_day_details = model.process_raw_data(raw_data, race_day)
  18. race_days.append(race_day_details)
  19. raw_data_dict[race_day.name] = raw_data
  20. interim = time.time()
  21. print('interim 2 {}'.format(interim - start))
  22. pprint(race_days)
  23. cursor = db.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
  24. for race_day in race_days:
  25. if not raw_data_dict or not race_day:
  26. # raw_data_dict may be empty when there is no data available (yet)
  27. continue
  28. raw_data = raw_data_dict[race_day.name]
  29. scratchings = model.get_scratching_details(raw_data, race_day)
  30. if not scratchings:
  31. # model.get_scratchings_details may return empty
  32. continue
  33. # retrieve previous stored scratching for this venue / day
  34. query = "SELECT * FROM horses WHERE venue = %s AND race_date = %s;"
  35. cursor.execute(query, (race_day.name, race_day.date))
  36. db_data = cursor.fetchall()
  37. # compare retrieved scratchings with new data
  38. match = False
  39. for scratching in scratchings:
  40. for row in db_data:
  41. # print(row)
  42. if (
  43. scratching.date == row.race_date and
  44. scratching.venue == row.venue and
  45. scratching.race == row.race and
  46. scratching.horse == row.horse
  47. ):
  48. message = 'Horse found: date = {}, venue = {}, race = {}, horse = {}'.format(scratching.date,
  49. scratching.venue,
  50. scratching.race,
  51. scratching.horse)
  52. print(message)
  53. match = True
  54. if not match:
  55. # report new scratching
  56. message = 'New scratching: {} {} race {} horse {}'.format(scratching.date, scratching.venue,
  57. scratching.race, scratching.horse)
  58. print(message)
  59. # store new scratching
  60. query = "INSERT INTO horses(venue, race_date, race, horse) VALUES(%s, %s, %s, %s)"
  61. cursor.execute(query, (scratching.venue, scratching.date,
  62. scratching.race, scratching.horse))
  63. db.commit()
  64. match = False
  65. cursor.close()
  66. db.close()
  67. interim = time.time()
  68. print('interim 3 {}'.format(interim - start))