diff options
-rw-r--r-- | db.py | 19 | ||||
-rw-r--r-- | pastepy.py | 33 |
2 files changed, 40 insertions, 12 deletions
@@ -1,4 +1,4 @@ -from sqlalchemy import create_engine, Column, Integer, String, DateTime, Text, Index +from sqlalchemy import create_engine, Column, Integer, String, DateTime, Text, Index, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, relation, backref import settings @@ -29,5 +29,22 @@ class Paste(Base): def __repr__(self): return '<Paste(%d, "%s", "%s", "%s", "%s")>' % (self.id, self.hash, self.nick, self.date.ctime(), self.title) +class Cache(Base): + __tablename__ = 'cache' + + id = Column(Integer, primary_key = True) + paste_hash = Column(String, ForeignKey('paste.hash'), index = True) + paste = relation(Paste, primaryjoin = paste_hash == Paste.hash, lazy = False) + syntax_name = Column(String) + text = Column(Text) + + def __init__(self, hash, syntax_name, text): + self.paste_hash = hash + self.syntax_name = syntax_name + self.text = text + + def __repr__(self): + return '<Cache(%d, "%s")>' % (self.id, self.paste_hash) + Base.metadata.create_all() Session = sessionmaker(bind = engine, autoflush = True, autocommit = False) @@ -89,22 +89,33 @@ class Paste(object): return [] def view(self): + def get_formatted(syntax, text): + try: + lex = get_lexer_by_name(syntax) + lexername = lex.name + text = highlight(text, lex, self.formatter) + except: + lexername = 'Plain text' + return (lexername, text) + hash = self.path[1] try: session = db.Session() - paste = session.query(db.Paste).filter_by(hash = hash).one() + try: + cache = session.query(db.Cache).filter_by(paste_hash = hash).one() + paste = cache.paste + except: # No cache found, generate it. + paste = session.query(db.Paste).filter_by(hash = hash).one() + lexername, text = get_formatted(paste.syntax, paste.text) + cache = db.Cache(hash, lexername, text) + session.add(cache) + session.commit() + # Workaround for attribute refresh. + paste = cache.paste finally: session.close() - try: - lex = get_lexer_by_name(paste.syntax) - lexername = lex.name - text = highlight(paste.text, lex, self.formatter) - except: - lexername = 'Plain text' - text = paste.text - self.start_response('200 OK', [('Content-Type', 'text/html')]) return [str(templates.view(searchList = { 'title': '%s – View paste – %s' % (settings.pastebin_name, paste.title), @@ -112,9 +123,9 @@ class Paste(object): 'hash': hash, 'date': paste.date.ctime(), 'nick': paste.nick or 'Anonymous', - 'syntax': lexername, + 'syntax': cache.syntax_name, 'pastetitle': paste.title or 'Untitled', - 'text': text, + 'text': cache.text, }))] def raw(self): |