fork download
  1. import hashlib
  2. import urllib
  3. import falcon
  4. import sqlite3
  5. import platform
  6. import base64
  7. import requests
  8. import dateutil.parser
  9. from datetime import datetime
  10. from waitress import serve
  11.  
  12.  
  13. class GravatarCachedResource:
  14. def __init__(self):
  15. self.isCached = False
  16. self.connection = sqlite3.connect('database.db')
  17. self.cursor = self.connection.cursor()
  18. self.cursor.execute('''
  19. CREATE TABLE IF NOT EXISTS "cache" (
  20. "id" TEXT NOT NULL,
  21. "created_at" TEXT NOT NULL,
  22. "data" BLOB,
  23. PRIMARY KEY("id")
  24. );
  25. ''')
  26.  
  27. self.cursor.execute('''
  28. CREATE TABLE IF NOT EXISTS "history" (
  29. "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  30. "date" TEXT NOT NULL,
  31. "url" TEXT NOT NULL
  32. );
  33. ''')
  34.  
  35. def get_username_hash(self, username):
  36. return hashlib.md5(username.encode('utf-8')).hexdigest()
  37.  
  38. def get_gravatar_url(self, username):
  39. gravatar_url = 'https://r...content-available-to-author-only...r.com/avatar/' + self.get_username_hash(username) + '?'
  40. gravatar_url += urllib.parse.urlencode({'s': str(300)})
  41. return gravatar_url
  42.  
  43. def get_gravatar_image(self, username):
  44. url = self.get_gravatar_url(username)
  45. return requests.get(url).content
  46.  
  47. def get_current_datetime(self):
  48. return datetime.now().isoformat()
  49.  
  50. def parse_datetime(self, date):
  51. return dateutil.parser.parse(date)
  52.  
  53. def save_image_to_database(self, username):
  54. username_hash = self.get_username_hash(username)
  55. image = self.get_gravatar_image(username)
  56. current_datetime = self.get_current_datetime()
  57.  
  58. if self.get_image_from_database(username) is None:
  59. self.cursor.execute("INSERT INTO `cache` VALUES (?, ?, ?);", (username_hash, current_datetime, image))
  60. else:
  61. self.cursor.execute("UPDATE `cache` SET `created_at` = ?, `data` = ? WHERE `id` = ?;", (current_datetime, image, username_hash))
  62.  
  63. self.connection.commit()
  64.  
  65. def get_image_from_database(self, username):
  66. username_hash = self.get_username_hash(username)
  67. self.cursor.execute("SELECT * FROM `cache` WHERE `cache`.`id` = '{}'".format(username_hash))
  68. return self.cursor.fetchone()
  69.  
  70. def get_image_from_cache_of_download(self, username):
  71. data = self.get_image_from_database(username)
  72.  
  73. if (data):
  74. now = datetime.now()
  75. created_at = self.parse_datetime(data[1])
  76. delta_in_seconds = (now - created_at).total_seconds()
  77.  
  78. if delta_in_seconds < 15:
  79. self.isCached = True
  80. return data[2]
  81.  
  82. self.isCached = False
  83. self.save_image_to_database(username)
  84. return self.get_gravatar_image(username)
  85.  
  86. def save_action_to_history(self, req, ):
  87. current_datetime = self.get_current_datetime()
  88.  
  89. self.cursor.execute("INSERT INTO `history` (date, url) VALUES (?, ?);", (current_datetime, req.url))
  90.  
  91. def on_get(self, req, resp, username):
  92. self.connection = sqlite3.connect('database.db')
  93. self.cursor = self.connection.cursor()
  94.  
  95. self.save_action_to_history(req)
  96.  
  97. image = self.get_image_from_cache_of_download(username)
  98. encoded = base64.b64encode(image).decode('utf-8')
  99.  
  100. resp.content_type = 'text/html'
  101. resp.body = '<h3>From {0}</h3><img src="data:image/png;base64, {1}">'.format('cache' if self.isCached else 'site' , encoded)
  102. resp.status = falcon.HTTP_200
  103.  
  104. class Info:
  105. def on_get(self, req, resp):
  106. self.connection = sqlite3.connect('database.db')
  107.  
  108. self.save_action_to_history(req)
  109. resp.content_type = 'text/html'
  110. resp.body = f'''
  111. <h3>System information</h3>
  112. <ul style="border: 2px solid black">
  113. <li>Architecture: {platform.architecture()[0]}</li>
  114. <li>CP: {platform.machine()}</li>
  115. <li>Name: {platform.node()}</li>
  116. <li>OS: {platform.system()}</li>
  117. </ul>
  118. '''
  119.  
  120. resp.status = falcon.HTTP_200
  121.  
  122. class History:
  123. def on_get(self, req, resp):
  124. self.connection = sqlite3.connect('database.db')
  125. self.cursor = self.connection.cursor()
  126. self.cursor.execute("SELECT * FROM `history`")
  127.  
  128. data = self.cursor.fetchall()
  129. table_data = ''
  130.  
  131. for row in data:
  132. table_data += f'<tr><td>{row[1]}</td><td>{row[2]}</td></tr>'
  133.  
  134. resp.content_type = 'text/html'
  135. resp.body = '<h3>History</h3><table><tr><td>date</td><td>url</td></tr>{}</table>'.format(table_data)
  136. resp.status = falcon.HTTP_200
  137.  
  138.  
  139. api = falcon.API()
  140.  
  141. api.add_route('/api/info', Info())
  142. api.add_route('/api/history', History())
  143. api.add_route('/api/avatar/{username}', GravatarCachedResource())
  144.  
  145. serve(api, host = '127.0.0.1', port = 8000)
Runtime error #stdin #stdout #stderr 0.11s 23504KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Traceback (most recent call last):
  File "./prog.py", line 3, in <module>
ModuleNotFoundError: No module named 'falcon'