Advertisement
Guest User

Script.py

a guest
Oct 18th, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.70 KB | None | 0 0
  1. from time import sleep
  2. from os.path import getmtime
  3. import json
  4. import mysql.connector
  5. import glob
  6. import sys
  7. import re
  8. from pathlib import Path  
  9.  
  10. # prepare stuff
  11. JSON_FILES="C:/dayzserver/ServerProfiles/Leaderboard/*.json" # file to be watched
  12. POLLINNG_TIME = 60   # how often to look for changes (seconds)
  13. FIELDS_TO_INSERT = ["id", "animalsKilled", "name", "deathsToZCount", "deathsToNaturalCauseCount", "deathsToAnimalCount", "suicideCount"
  14. , "longestShot", "zKilled", "timeSurvived", "distTrav"]
  15.  
  16. sql_insert = "REPLACE INTO stats ("+ (','.join(FIELDS_TO_INSERT)) +") VALUES ("+ ','.join("%s" for _ in FIELDS_TO_INSERT) +")"
  17.  
  18.  
  19. def update_db(file, cursor):
  20.     fname = Path(file).name
  21.     with open(file) as f:
  22.         data = json.load(f)
  23.     data["id"] = re.match("Stats-(\\d*)\\.json", fname).group(1)
  24.     data["animalsKilled"] = len(data["animalsKilled"])
  25.     values = tuple([data[x] for x in FIELDS_TO_INSERT])
  26.     cursor.execute(sql_insert, values)
  27.  
  28. last_modified_map = {}
  29. db = None
  30. try:
  31.     db = mysql.connector.connect(
  32.         host="xxxx",
  33.         user="xxxx",
  34.         passwd="xxxx",
  35.         database = "xxxx"
  36.     )
  37.     cursor = db.cursor()
  38.  
  39.     while True:
  40.         needs_to_commit = False
  41.  
  42.         for file in glob.glob(JSON_FILES):
  43.             new_lm = getmtime(file)
  44.             last_modified = last_modified_map.get(file)
  45.             if new_lm != last_modified:
  46.                 needs_to_commit = True
  47.                 update_db(file, cursor)
  48.            
  49.             last_modified_map[file] = new_lm
  50.  
  51.        
  52.         if needs_to_commit:
  53.             db.commit()
  54.        
  55.         sleep(POLLINNG_TIME)
  56. finally:
  57.     if db is not None:
  58.         cursor.close()
  59.         db.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement