From d6337a93a34836fd479839697d9d82c045b01da2 Mon Sep 17 00:00:00 2001 From: Jon Bergli Heier Date: Tue, 26 Jan 2010 19:45:27 +0100 Subject: Cache formatted text. --- db.py | 19 ++++++++++++++++++- pastepy.py | 33 ++++++++++++++++++++++----------- 2 files changed, 40 insertions(+), 12 deletions(-) diff --git a/db.py b/db.py index 8d96b4d..b5c5a3f 100644 --- a/db.py +++ b/db.py @@ -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 '' % (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 '' % (self.id, self.paste_hash) + Base.metadata.create_all() Session = sessionmaker(bind = engine, autoflush = True, autocommit = False) diff --git a/pastepy.py b/pastepy.py index 3229eb4..570aef6 100644 --- a/pastepy.py +++ b/pastepy.py @@ -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): -- cgit v1.2.3