Advertisement
Guest User

Untitled

a guest
Jun 30th, 2017
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.68 KB | None | 0 0
  1. import psycopg2
  2. import datetime
  3.  
  4. try:
  5. conn = psycopg2.connect("dbname='news' user='postgres' host='localhost' password='pass'")
  6. except:
  7. print "Cannot connect to 'news' database"
  8.  
  9. def top_articles(limit):
  10. """ Top news articles sorted by popularity """
  11. cursor = conn.cursor()
  12.  
  13. print "Top {0} articles sorted by popularity: ".format(limit)
  14. print
  15. cursor.execute("SELECT COUNT(id), path FROM log WHERE status = '200 OK' AND NOT path = '/' GROUP BY path ORDER BY COUNT(id) DESC LIMIT {0};".format(limit))
  16.  
  17. articles = cursor.fetchall()
  18. for article in articles:
  19. cursor.execute("SELECT title FROM articles WHERE ('/article/' || slug) ='" + article[1] + "';")
  20. title = cursor.fetchone()
  21. print '"{0}" - {1} views'.format(title[0], article[0])
  22.  
  23. def top_authors(limit):
  24. """ Top authors sorted by total article views """
  25. cursor = conn.cursor()
  26.  
  27. print "Top {0} authors sorted by page views: ".format(limit)
  28. print
  29. cursor.execute("SELECT name, id FROM authors LIMIT {0};".format(limit))
  30.  
  31. authors = cursor.fetchall()
  32. for author in authors:
  33. cursor.execute("SELECT slug FROM articles WHERE author ='{0}';".format(author[1]))
  34. slugs = cursor.fetchall()
  35. total = 0
  36. for slug in slugs:
  37. cursor.execute("SELECT COUNT(id) FROM log WHERE status = '200 OK' AND substring(path, 10) = '{0}';".format(slug[0]))
  38. artcount = cursor.fetchone()
  39. total += artcount[0]
  40. print "{0} - {1} views".format(author[0], total)
  41.  
  42. def bad_request_days():
  43. """ Days where there were bad requests over 1% """
  44. cursor = conn.cursor()
  45.  
  46. cursor.execute("SELECT COUNT(id), time, status FROM log GROUP BY time, status ORDER BY time;")
  47.  
  48. last_row = None
  49.  
  50. total_bad = 0.0
  51. total_good = 0.0
  52. print "Days with more than 1% errors:"
  53. print
  54. for row in cursor:
  55. if last_row == None:
  56. last_row = row[1]
  57.  
  58. if last_row.month == row[1].month and last_row.day == row[1].day:
  59. if row[2] == "404 NOT FOUND":
  60. total_bad += row[0]
  61. elif row[2] == "200 OK":
  62. total_good += row[0]
  63. else:
  64. result = float(total_bad / (total_bad + total_good) * 100)
  65. if result > 1.0:
  66. print "{0}/{1}/{2} - {3:.2f}%".format(last_row.month, last_row.day, last_row.year, result)
  67.  
  68. last_row = None
  69. total_bad = 0.0
  70. total_good = 0.0
  71.  
  72. def main():
  73. top_articles(3)
  74. print
  75. top_authors(4)
  76. print
  77. bad_request_days()
  78.  
  79. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement