Advertisement
Guest User

Untitled

a guest
Mar 30th, 2017
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. from mysite.models import WikiPopularity #it might be another pass to a model
  4. import glob, csv
  5. from django.db import connection
  6.  
  7.  
  8. def stringed_chunk(chunk):
  9. str_chunk = ["('{0}', {1})".format(row[0], row[1]) for row in chunk]
  10. return ", ".join(str_chunk)
  11.  
  12.  
  13. def model_upsertion(chunk):
  14. chunk = stringed_chunk(chunk)
  15. with connection.cursor() as cursor:
  16. try:
  17. cursor.execute(
  18. """INSERT INTO mysite_wikipopularity (wiki_id, popularity)
  19. VALUES {}
  20. ON CONFLICT (wiki_id)
  21. DO UPDATE SET popularity = excluded.popularity;""".format(chunk)
  22. )
  23. except:
  24. return
  25.  
  26. def quantity_of_thousands_of_lines(file_name):
  27. with open(file_name) as f:
  28. quantity_of_lines = sum(1 for line in f)
  29. quantaty_of_thousands_of_lines = quantity_of_lines//1000
  30. rest_of_lines = quantity_of_lines%1000
  31. return quantaty_of_thousands_of_lines, rest_of_lines
  32.  
  33.  
  34. def upsertion_with_thousands_of_lines(reader, quantaty_of_thousands):
  35. for i in xrange(quantaty_of_thousands):
  36. chunk_of_rows = [reader.next() for x in xrange(1000)]
  37. model_upsertion(chunk_of_rows)
  38.  
  39.  
  40. def upsertion_with_rest_of_lines(reader, rest_of_lines):
  41. chunk_of_rows = [reader.next() for i in xrange(rest_of_lines)]
  42. model_upsertion(chunk_of_rows)
  43.  
  44.  
  45. def model_upsertion_with_file(csv_file_name):
  46. quantaty_of_thousands, rest_of_lines = quantity_of_thousands_of_lines(csv_file_name)
  47. with open(csv_file_name) as f:
  48. reader = csv.reader(f)
  49. upsertion_with_thousands_of_lines(reader, quantaty_of_thousands)
  50. upsertion_with_rest_of_lines(reader, rest_of_lines)
  51.  
  52.  
  53. def upsert():
  54. csv_files = glob.glob('*.csv') #you may change path to your tmp dir
  55. for csv_file_name in csv_files:
  56. model_upsertion_with_file(csv_file_name)
  57. print u'success'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement