main.py 3.3 KB

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