Source

find-gift / controllers / __init__.py

Full commit
import cPickle
import settings
import urllib
import logging
import simplejson
import memcache

from models import User
from tornado.web import RequestHandler
from sqlalchemy import orm, create_engine

engine = create_engine(settings.DATABASE_DSN)
Session = orm.sessionmaker(bind=engine)()

Memcached = memcache.Client(
    settings.MEMCACHED_SERVERS,
    debug=settings.MEMCACHED_DEBUG
)


class BaseHandler(RequestHandler):

    def __init__(self, *args, **kwargs):
        super(BaseHandler, self).__init__(*args, **kwargs)

    @property
    def user_data_facebook(self):

        cookie = self.get_secure_cookie('user')

        if not cookie:
            return None
        else:
            return cPickle.loads(cookie)

    def get_current_user(self):

        cookie = self.get_secure_cookie('user')

        if not cookie:
            return None
        else:

            cookie_user = cPickle.loads(cookie)

            user = Session.query(User).filter_by(
                fbid=cookie_user.get('user_id')).first()

            return user

    def render_string(self, template, **kwargs):

        kwargs.update({'handler': self})

        return self.settings.get('template_env')\
            .get_template(template).render(**kwargs)

    def render(self, template, **kwargs):

        self.finish(self.render_string(template, **kwargs))

    def load_data_url(self, url, params, json=True):

        try:
            data = urllib.urlopen('%s?%s' % (
                url, urllib.urlencode(params))).read()

            if json:
                data = simplejson.loads(data)

        except Exception as exc:
            logging.error(exc)
            data = None

        return data

    def pagination(self, limit, page):

        if not page.isdigit():
            page = int(page)
        else:
            page = 1

        offset = ((page - 1) * limit)

        return (limit, offset)