Advertisement
hdiwan

hd1/comments

Mar 2nd, 2015
418
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.58 KB | None | 0 0
  1. """Reddit clone using web.py
  2. """
  3. import csv
  4. import datetime
  5. import io
  6. import logging
  7. import requests
  8. import time
  9. import web
  10.  
  11. urls = (
  12.     "/", "index",
  13.     "/new", "post",
  14.     "/(\d+)/vote", "vote",
  15. )
  16. app = web.application(urls, globals())
  17. render = web.template.render("templates/")
  18. class index:
  19.     def GET(self):
  20.         db = web.database(dbn="sqlite", db="reddit.db")
  21.         index.import_time = 0
  22.         try:
  23.             with open('schema.sql') as fin:
  24.                 db.query(fin.read())
  25.         except:
  26.             pass
  27.        
  28.         if time.time() > index.import_time + 86400: # time to refresh data
  29.             main()
  30.         index.import_time = time.time()
  31.  
  32.         posts = db.select('posts', what='id, url, title', group='url', order='creation_time desc, votes desc')
  33.  
  34.         string = '<!DOCTYPE html><html><body>'
  35.         for p in list(posts):
  36.             logging.debug('post: {}'.format(p))
  37.             string = string + '<div class="post"><form method="post" action="/{0}/vote" style="display:inline"><button type="submit" name="action" value="up">+</button><button type="submit" name="action" value="down">-</button></form><a href="{1}">{2}</a></div></div>'.format(p.id, p.url, p.title)
  38.         string = string + '</body></html>'
  39.         logging.debug(string)
  40.         return string
  41.  
  42. class vote:
  43.     def POST(self, pid):
  44.         db = web.database(dbn="sqlite", db="reddit.db")
  45.         i = web.input(action="up")
  46.         if i.action == "up":
  47.             db.query(
  48.                 "UPDATE posts SET votes=votes+1 WHERE id=$id",
  49.                 {"id": pid})
  50.         else:
  51.             db.query(
  52.                 "UPDATE posts SET votes=votes-1 WHERE id=$id",
  53.                 {"id": pid})
  54.         raise web.seeother("/")
  55.  
  56. def main():
  57.   db = web.database(dbn='sqlite', db='reddit.db')
  58.   links_ = requests.get('http://hasan.d8u.us/links.py.cgi?format=csv').content
  59.   with db.transaction() as txn:
  60.     db.query('delete from posts')
  61.     with io.BytesIO(bytes(links_)) as fin:
  62.       reader = csv.DictReader(fin, fieldnames=["Recipient","Link","Timestamp"])
  63.       for row in list(reader)[1:]:
  64.         link = row['Link']
  65.         add = int(row['Timestamp'])
  66.         logging.debug('Examining {}'.format(row))
  67.         try:
  68.           db.insert('posts',title=link, url=link, creation_time=add)
  69.         except Exception, e:
  70.           logging.warn('Failed to insert {0} -- reason: {1}'.format(link, str(e)))
  71.   txn.commit()
  72.  
  73. if __name__ == "__main__":
  74.     logging.basicConfig(level=logging.INFO, format='%(asctime)s, %(levelname)s, %(message)s')
  75.    
  76.     app.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement