Advertisement
Guest User

Untitled

a guest
Dec 19th, 2016
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import psycopg2 as psql
  4. from sys import argv
  5. import configparser
  6. import os
  7. from urllib.parse import urlparse
  8. from tqdm import tqdm
  9. import csv
  10.  
  11. APP_ROOT = os.path.realpath(os.path.dirname(__file__))
  12.  
  13. DEFAULT_CONFIGURATION = {
  14. "port": 5000,
  15. "host": "::1",
  16. "debug": False,
  17. "live_scrape": True,
  18. "database_uri": "postgres:///park_api",
  19. }
  20.  
  21. if __name__ == "__main__":
  22.  
  23. if len(argv) < 3:
  24. print("Usage: {0} <City> <year>".format(argv[0]))
  25. exit(1)
  26.  
  27. print("loading config...")
  28.  
  29. config_path = os.path.join(APP_ROOT, "config.ini")
  30. try:
  31. config_file = open(config_path)
  32. except (OSError, FileNotFoundError) as e:
  33. print("Failed load configuration: %s" % e)
  34. exit(1)
  35. config = configparser.ConfigParser(DEFAULT_CONFIGURATION, strict=False)
  36. config.read_file(config_file)
  37. db_conf = urlparse(config["production"].get("database_uri"))
  38.  
  39. print("connecting to database...")
  40.  
  41. with psql.connect(database=db_conf.path[1:],
  42. user=db_conf.username,
  43. password=db_conf.password,
  44. host=db_conf.hostname,
  45. port=db_conf.port) as db:
  46.  
  47. cursor = db.cursor()
  48.  
  49. print("precalculating...")
  50.  
  51. cursor.execute("select count(city) from parkapi where city = '{0}' and extract(year from timestamp_downloaded) = '{1}'".format(argv[1], argv[2]))
  52. rowcount = cursor.fetchone()[0]
  53.  
  54. print("fetching from database...")
  55.  
  56. cursor.execute("select timestamp_downloaded, city, data from parkapi where city = '{0}' and extract(year from timestamp_downloaded) = '{1}'".format(argv[1], argv[2]))
  57.  
  58. table = []
  59. for i in tqdm(range(rowcount)):
  60. table.append(cursor.fetchone())
  61.  
  62. print("refining data...")
  63.  
  64. data = {}
  65. for row in tqdm(table):
  66. for lot in row[2]['lots']:
  67. try:
  68. data[lot['id']].append((row[2]['last_downloaded'], lot['free']))
  69. except KeyError:
  70. data[lot['id']] = [(row[2]['last_downloaded'], lot['free'])]
  71.  
  72. print("writing data...")
  73.  
  74. for city in tqdm(data.keys()):
  75. with open("{0}-{1}.csv".format(city, argv[2], "w") as outfile:
  76. writer = csv.writer(outfile)
  77. writer.writerows(data[city])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement