Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """Reddit clone using web.py
- """
- import csv
- import datetime
- import io
- import logging
- import requests
- import time
- import web
- urls = (
- "/", "index",
- "/new", "post",
- "/(\d+)/vote", "vote",
- )
- app = web.application(urls, globals())
- render = web.template.render("templates/")
- class index:
- def GET(self):
- db = web.database(dbn="sqlite", db="reddit.db")
- index.import_time = 0
- try:
- with open('schema.sql') as fin:
- db.query(fin.read())
- except:
- pass
- if time.time() > index.import_time + 86400: # time to refresh data
- main()
- index.import_time = time.time()
- posts = db.select('posts', what='id, url, title', group='url', order='creation_time desc, votes desc')
- string = '<!DOCTYPE html><html><body>'
- for p in list(posts):
- logging.debug('post: {}'.format(p))
- 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)
- string = string + '</body></html>'
- logging.debug(string)
- return string
- class vote:
- def POST(self, pid):
- db = web.database(dbn="sqlite", db="reddit.db")
- i = web.input(action="up")
- if i.action == "up":
- db.query(
- "UPDATE posts SET votes=votes+1 WHERE id=$id",
- {"id": pid})
- else:
- db.query(
- "UPDATE posts SET votes=votes-1 WHERE id=$id",
- {"id": pid})
- raise web.seeother("/")
- def main():
- db = web.database(dbn='sqlite', db='reddit.db')
- links_ = requests.get('http://hasan.d8u.us/links.py.cgi?format=csv').content
- with db.transaction() as txn:
- db.query('delete from posts')
- with io.BytesIO(bytes(links_)) as fin:
- reader = csv.DictReader(fin, fieldnames=["Recipient","Link","Timestamp"])
- for row in list(reader)[1:]:
- link = row['Link']
- add = int(row['Timestamp'])
- logging.debug('Examining {}'.format(row))
- try:
- db.insert('posts',title=link, url=link, creation_time=add)
- except Exception, e:
- logging.warn('Failed to insert {0} -- reason: {1}'.format(link, str(e)))
- txn.commit()
- if __name__ == "__main__":
- logging.basicConfig(level=logging.INFO, format='%(asctime)s, %(levelname)s, %(message)s')
- app.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement