Advertisement
HittingSmoke

Untitled

May 20th, 2014
1,026
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.32 KB | None | 0 0
  1. import itertools
  2. import requests
  3. import xml.etree.ElementTree as ET
  4. import sqlite3
  5. import json
  6. import sys
  7. import traceback
  8.  
  9. # Open save file and get UID of last saved user
  10. f = open('lastid.txt', 'r')
  11. lastcount = int(f.read())
  12. f.close()
  13.  
  14. # Create database connection database tables
  15. dbconn = sqlite3.connect('roster.db', check_same_thread=False)
  16. db = dbconn.cursor()
  17. db.execute('''CREATE TABLE IF NOT EXISTS members(userid int, handle text, joindate text, gender text, roles text)''')
  18.  
  19. # Start session to preserve across future requests
  20. s = requests.Session()
  21. s.post('https://example.com/api/account/signin', data={'username':'username', 'password' : 'password', 'remember' : '1'})
  22.  
  23. # Main function for collecting, parsing, and formatting XML data
  24. def dataget(count):
  25.     try:
  26.         xml = s.get('http://example.com/api/users/get.ext', params={'user' : count}, timeout=5)
  27.     # If any connection related exceptions occur retry until connection restored
  28.     except requests.exceptions.RequestException as e:
  29.         print('Connection Error:', e)
  30.         print('Retrying #'+count)
  31.         dataget(count)
  32.         return
  33.  
  34.     if xml.status_code == 200: # 200 = Successful load of XML data
  35.         userdata = ET.fromstring(xml.content) # Full XML data
  36.  
  37.         # Get just the data we want to save from the XML data
  38.         userid = userdata.find('Profile/UserID').text
  39.         handle = userdata.find('Profile/Name').text
  40.         joindate = userdata.find('Profile/DateFirstVisit').text
  41.         gender = userdata.find('Profile/Gender').text
  42.         roles = [elem.text for elem in userdata.findall('UserRoles/Item')]
  43.         rolelist = json.dumps(roles)
  44.  
  45.         # List to be inserted into the database
  46.         userinsert = [userid, handle, joindate, gender, rolelist]
  47.         # Run function to write data into database
  48.         datawrite(count,userid, handle, userinsert)
  49.     # Gracefully handle missing user entries
  50.     elif xml.status_code == 410 or 404:
  51.         print('404: User', count, 'not found')
  52.     # Catch any other unexpected responses and halt script
  53.     else:
  54.         print('Unexpected response for user', count+'. Halting')
  55.         sys.exit()
  56.        
  57.     return
  58.  
  59. # Write data from dataget function to SQLite database
  60. def datawrite(count, userid, handle, userinsert):
  61.     print('Writing', '#'+userid+":", handle, 'to the database...\t\t', end='')
  62.    
  63.     db.execute("INSERT INTO members VALUES (?,?,?,?,?)", userinsert) # "?" placeholder is REQUIRED for SQL-safe data
  64.     dbconn.commit()
  65.     print('DONE')
  66.  
  67. # Main loop that counts up from lastcount integer infinitely running dataget function on each count
  68. for i in itertools.count(lastcount):
  69.     try:
  70.         count = str(i)
  71.         dataget(count)
  72.  
  73.     # Capture keyboard interrupt, update UID save file, and exit for graceful closes
  74.     except KeyboardInterrupt as e:
  75.         f = open('lastid.txt', 'w')
  76.         print('Saving last user ID')
  77.         f.write(count)
  78.         f.close
  79.         print('Exiting')
  80.         sys.exit()
  81.    
  82.     # Capture all other possible exceptions, save last UID if possible, log exception, then allow failure
  83.     except Exception as e:
  84.         f = open('lastid.txt', 'w')
  85.         f.write(count)
  86.         f.close
  87.         ef = open('lastexception.txt', 'w')
  88.         traceback.print_exc(file = ef)
  89.         ef.close()
  90.         raise e
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement