Advertisement
Guest User

Untitled

a guest
Sep 22nd, 2016
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.41 KB | None | 0 0
  1. import sys
  2. from logging import INFO, basicConfig, error, info  # ordem alfabética
  3. from os import environ
  4. from time import sleep  # imported but not used
  5.  
  6. import psycopg2
  7. import simplejson as json
  8. from tqdm import tqdm
  9. # 2 blank lines
  10.  
  11. basicConfig(format='%(levelname)s %(message)s', level=INFO)
  12. try:
  13.     table = sys.argv[1]
  14. except:
  15.     error('Usage: data_retrieval.py [table/view]')
  16.     sys.exit(1)
  17. # 2 blank lines
  18.  
  19. USER = environ.get('DB_USER')
  20. PASSWORD = environ.get('DB_PASSWORD')
  21. if not USER or not PASSWORD:
  22.     error('no USER or PASSWORD for connection found')
  23.     sys.exit(1)
  24. # 2 blank lines
  25.  
  26. info('Connecting to database...')
  27. conn = psycopg2.connect(database='twitter', user=USER, password=PASSWORD,
  28.                         host='143.107.137.90')
  29. cur = conn.cursor()
  30. sql = 'SELECT json FROM {};'.format(table)
  31. info('Executing SQL command...')
  32. cur.execute(sql)
  33. info('Fetching and writing data...')
  34.  
  35.  
  36. # filenames não me parece um bom nome, parece que você deveria passar uma
  37. # lista com nomes de arquivos, e na verdade é só um arquivo só
  38. # opção: file_options
  39. def fetch_and_save_data_to_file(db_cursor, filenames):
  40.     filenames['sampleresult'] = 'sample-' + filenames['result']
  41.     with open(filenames['result'], 'w') as result, \
  42.          open(filenames['sampleresult'], 'w') as sampleresult:
  43.         info('File: %s', filenames['result'])
  44.         i = 0
  45.         samples = []
  46.  
  47.         # achei confuso esse for, acho que tem um jeito melhor de fazer isso
  48.         for row in tqdm(db_cursor):
  49.             if i < filenames['opt']:
  50.                 i += 1
  51.                 samples.append(row[0])
  52.             result.write(json.dumps(row[0], result))
  53.             result.write('\n')
  54.         info('File: %s', filenames['sampleresult'])
  55.         for sample in tqdm(samples):
  56.             sampleresult.write(json.dumps(sample, sampleresult))
  57.             sampleresult.write('\n')
  58.     # blank line
  59.     # ao usar `with` pra abrir arquivos, o __exit__ dos arquivos é chamado no
  60.     # momento que se sai do `with`, e o __exit__ gera um close(), daí não
  61.     # precisa chamar o .close()
  62.     result.close()
  63.     sampleresult.close()
  64.     info('Closing conection...')
  65.     cur.close()
  66.     conn.close()
  67.  
  68. # 2 blank lines
  69. # identação desse dict passou né?
  70. files = {
  71.             'result':'tweets-json',  # result ou filename? :P
  72.             'opt': 50,
  73.         }
  74. fetch_and_save_data_to_file(cur, files)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement