Commits

Ronny Pfannschmidt committed f289aeb

reshape the app a bit we now can render pastes again

Comments (0)

Files changed (8)

lodgeit/__init__.py

     :license: BSD
 """
 
-from lodgeit.application import make_app
+from lodgeit.application import app

lodgeit/application.py

     :copyright: 2007-2009 by Armin Ronacher, Christopher Grebs.
     :license: BSD
 """
-import os
 import flask
+from flask.ext.babel import Babel
+
+app = flask.Flask('lodgeit')
+
 from .i18n import list_languages
+app.jinja_env.globals.update({'i18n_languages': list_languages()})
 
 
-def make_app(dburi, secret_key, debug=False):
-    """Apply the used middlewares and create the application."""
-    static_path = os.path.join(os.path.dirname(__file__), 'static')
-    app = flask.Flask('lodgeit', static_path=static_path)
-    from flask.ext.babel import Babel
-    app.config['SQLALCHEMY_DATABASE_URI'] = dburi
-    app.jinja_env.globals.update({'i18n_languages': list_languages()})
-    app.babel = Babel(app)
-    app.debug = debug
+babel = Babel(app)
 
-    @app.errorhandler(404)
-    def not_found(e):
-        return flask.render_template('not_found.html')
+@app.errorhandler(404)
+def not_found(e):
+    return flask.render_template('not_found.html')
 
-    from lodgeit import controllers
-    for blueprint in controllers.all:
-        app.register_blueprint(blueprint)
-    return app
+
+from lodgeit import controllers
+for blueprint in controllers.all:
+    app.register_blueprint(blueprint)

lodgeit/controllers/pastes.py

 """
 from werkzeug import redirect, Response
 from werkzeug.exceptions import NotFound
+from hashlib import sha1
+from random import random
+import time
 
 from flask import request, session, render_template, url_for
 from lodgeit.lib import antispam
 from lodgeit.lib.highlighting import list_languages, STYLES
 from lodgeit.lib.pagination import generate_pagination
 from lodgeit.lib.captcha import check_hashed_solution, Captcha
-
 from flask.ext.babel import gettext as _
 
 
 from flask import Blueprint
+pastes = Blueprint('pastes', __name__)
 
 
-pastes = Blueprint('pastes', __name__)
+def generate_user_hash():
+    """Generates an more or less unique SHA1 hash."""
+    return sha1('%s|%s' % (random(), time.time())).hexdigest()
+
+
+@pastes.before_request
+def add_userhash():
+    if 'user_hash' not in session:
+        session['user_hash'] = generate_user_hash()
+
+
 
 @pastes.route('/', methods=['GET', 'POST'])
 @pastes.route('/+<language>', methods=['GET', 'POST'])
                               'CAPTCHA solution was incorrect')
             show_captcha = True
         if code and language and not error:
-            paste = Paste(code, language, parent, session.user_hash,
+            paste = Paste(code, language, parent, session['user_hash'],
                           'private' in request.form)
             db.session.add(paste)
             db.session.commit()
             session['language'] = language
-            return redirect(url_for('show_paste', identifier=paste.identifier))
+            return redirect(url_for('.show_paste', identifier=paste.identifier))
 
     else:
         parent_id = request.values.get('reply_to')

lodgeit/lib/highlighting.py

 import re
 import pygments
 import csv
+import flask
 from operator import itemgetter
 from pygments.util import ClassNotFound
 from pygments.lexers import get_lexer_by_name, get_lexer_for_filename, \
 
 def get_style(request=None, name_only=False):
     """Style for a given request or style name."""
-    request = request or local.request
+    request = request or flask.request
     if not request:
         style_name = DEFAULT_STYLE
     elif isinstance(request, basestring):

lodgeit/models.py

 from datetime import datetime
 from werkzeug import cached_property
 
+from flask import request
 from flask_sqlalchemy import SQLAlchemy
 
 from lodgeit.utils import generate_paste_hash
 from lodgeit.lib.highlighting import highlight, preview_highlight, LANGUAGES
 from lodgeit.lib.diff import prepare_udiff
 
+from lodgeit.application import app
 
-db = SQLAlchemy()
+db = SQLAlchemy(app)
 
 class Paste(db.Model):
     __tablename__ = 'pastes'
         as handled.
         """
         ids = db.session.query(Paste.paste_id) \
-                        .filter(Paste.user_hash == local.request.user_hash)
+                        .filter(Paste.user_hash == request.user_hash)
 
         paste_list = db.session.query(Paste.paste_id).filter(db.and_(
             Paste.parent_id.in_(ids),
             Paste.handled == False,
-            Paste.user_hash != local.request.user_hash,
+            Paste.user_hash != request.user_hash,
         )).order_by(Paste.paste_id.desc()).all()
 
         to_mark = [p.paste_id for p in paste_list]
     @cached_property
     def parsed_code(self):
         """The paste as rendered code."""
-        linenos = local.request.args.get('linenos') != 'no'
+        linenos = request.args.get('linenos') != 'no'
         high = highlight(self.code, self.language, _linenos=linenos)
         return high
 

lodgeit/templates/show_paste.html

   <div class="related">
     <h3><a href="javascript:LodgeIt.toggleRelatedBox()">{% trans %}Paste Details{% endtrans %}</a></h3>
     <div class="quick">
-      <p><a href="{{ url('pastes/new_paste', reply_to=paste.identifier) }}">{% trans %}reply{% endtrans %}</a> |
-         <a href="{{ url('pastes/raw_paste', identifier=paste.identifier) }}">{% trans %}raw{% endtrans %}</a></p>
+      <p><a href="{{ url_for('pastes.new_paste', reply_to=paste.identifier) }}">{% trans %}reply{% endtrans %}</a> |
+         <a href="{{ url_for('pastes.raw_paste', identifier=paste.identifier) }}">{% trans %}raw{% endtrans %}</a></p>
     </div>
     <div class="content">
       <p>{% trans pub_date=paste.pub_date|datetimeformat %}posted on {{ pub_date }}{% endtrans %}</p>
       <ul>
-        <li><a class="autoclose" href="{{ url('pastes/new_paste', reply_to=paste.identifier) }}">{% trans %}reply to this paste{% endtrans %}</a></li>
+        <li><a class="autoclose" href="{{ url_for('pastes.new_paste', reply_to=paste.identifier) }}">{% trans %}reply to this paste{% endtrans %}</a></li>
         {% if paste.parent %}
-          <li><a class="autoclose" href="{{ url('pastes/compare_paste', new_id=paste.identifier, old_id=paste.parent.identifier) }}">{% trans %}compare it with the parent paste{% endtrans %}</a></li>
-          <li><a class="autoclose" href="{{ url('pastes/show_paste', identifier=paste.parent.identifier) }}">{% trans %}look at the parent paste{% endtrans %}</a></li>
+          <li><a class="autoclose" href="{{ url_for('pastes.compare_paste', new_id=paste.identifier, old_id=paste.parent.identifier) }}">{% trans %}compare it with the parent paste{% endtrans %}</a></li>
+          <li><a class="autoclose" href="{{ url_for('pastes.show_paste', identifier=paste.parent.identifier) }}">{% trans %}look at the parent paste{% endtrans %}</a></li>
         {% endif %}
         {% if paste.children %}
           <li>{% trans %}the following pastes replied to this paste:{% endtrans %}
           {% for child in paste.children %}
-            <a class="autoclose" href="{{ url('pastes/show_paste', identifier=child.identifier) }}">#{{ child.identifier }}</a>
+            <a class="autoclose" href="{{ url_for('pastes.show_paste', identifier=child.identifier) }}">#{{ child.identifier }}</a>
             {%- if not loop.last %},{% endif -%}
           {% endfor %}
           </li>
         {% endif %}
         {% if paste.parent or paste.children %}
-          <li><a href="{{ url('pastes/show_tree', identifier=paste.identifier) }}">{% trans %}show paste tree{% endtrans %}</a></li>
+          <li><a href="{{ url_for('pastes.show_tree', identifier=paste.identifier) }}">{% trans %}show paste tree{% endtrans %}</a></li>
         {% endif %}
-        <li><a href="{{ url('pastes/raw_paste', identifier=paste.identifier) }}">{% trans %}download paste{% endtrans %}</a></li>
-        <li>{% trans %}compare with paste{% endtrans %} <form action="{{ url('pastes/compare_paste') }}" method="post">
+        <li><a href="{{ url_for('pastes.raw_paste', identifier=paste.identifier) }}">{% trans %}download paste{% endtrans %}</a></li>
+        <li>{% trans %}compare with paste{% endtrans %} <form action="{{ url_for('pastes.compare_paste') }}" method="post">
           <input type="hidden" name="old" value="{{ paste.identifier }}">
           <input type="text" name="new" value="#">
           <input type="submit" value="{% trans %}compare{% endtrans %}">
         </form></li>
-        <li>{% trans %}select different colorscheme{% endtrans %} <form action="{{ url('pastes/set_colorscheme') }}" method="post">
+        <li>{% trans %}select different colorscheme{% endtrans %} <form action="{{ url_for('pastes.set_colorscheme') }}" method="post">
           <select name="style">
           {%- for key, caption in styles|dictsort %}
             <option value="{{ key }}"{% if key == style
     </div>
   </div>
   <div id="paste" class="lang-{{ paste.language }} code{% if not linenos %} nolinenos{% endif %}">
-    {{ paste.parsed_code }}
+    {{ paste.parsed_code|safe }}
   </div>
 {% endblock %}
 except:
     from sha import new as sha1
 
-#: Jinja2 Environment for our template handling
-jinja_environment = Environment(loader=FileSystemLoader(
-    path.join(path.dirname(__file__), 'views')),
-    extensions=['jinja2.ext.i18n'])
-
 #: constants
 _word_only = partial(re.compile(r'[^a-zA-Z0-9]').sub, '')
 COOKIE_NAME = u'lodgeit_session'
 
 
-def generate_user_hash():
-    """Generates an more or less unique SHA1 hash."""
-    return sha1('%s|%s' % (random(), time.time())).hexdigest()
-
 
 def generate_paste_hash():
     """Generates a more or less unique-truncated SHA1 hash."""
     def set_language(self, lang):
         self.session['locale'] = lang
 
-    @property
-    def translations(self):
-        return get_translations(self.locale)
-
-    def bind_to_context(self):
-        local.request = self
-
-    def get_url(self, view, method='GET', **params):
-        return self.urls.build(view, params, method=method)
 
 
 def render_template(template_name, **context):
 
 from werkzeug import script, create_environ, run_wsgi_app
 
-from lodgeit.application import make_app
+from lodgeit.application import app
 from lodgeit.models import db
 
 dburi = 'sqlite:////tmp/lodgeit.db'
 SECRET_KEY = 'no secret key'
 
 
+def make_app(db, secret, debug):
+    app.config['SECRET_KEY'] = secret
+    app.debug = debug
+    app.config['SQLALCHEMY_DATABASE_URI'] = db
+    return app
+
+
 def run_app(app, path='/'):
     env = create_environ(path, SECRET_KEY)
     return run_wsgi_app(app, env)
 
 action_shell = script.make_shell(
     lambda: {
-        'app': make_app(dburi, SECRET_KEY, False, True),
+        'app': make_app(dburi, SECRET_KEY, True),
         'db': db,
         'run_app': run_app
     },