コード例 #1
0
ファイル: base.py プロジェクト: LamCiuLoeng/BookStore
class BaseHandler(tornado.web.RequestHandler):

    _lookup = mako.lookup.TemplateLookup(directories = [app_setting["tornado_setting"]["template_path"], ],
                                          module_directory = app_setting["addition_setting"]["template_path_cache"],
                                          input_encoding = 'utf-8',
                                          output_encoding = 'utf-8')



    def initialize(self, **kw):
        self.session = TornadoSession(self.application.session_manager, self)

    def render_string(self, template_name, **kwargs):
        mytemplate = self._lookup.get_template(template_name)
        args = dict(
            handler = self,
            request = self.request,
            current_user = self.current_user,
            locale = self.locale,
            _ = self.locale.translate,
            static_url = self.static_url,
            xsrf_form_html = self.xsrf_form_html,
            reverse_url = self.application.reverse_url,
            get_any_permissions = self.get_any_permissions,
            get_all_permissions = self.get_all_permissions,
            in_all_groups = self.in_all_groups,
            in_any_groups = self.in_any_groups,
        )
#        args.update(self.ui)
        args.update(kwargs)
        return mytemplate.render(**args)

    def render(self, template_name, **kwargs):
        self.finish(self.render_string(template_name, **kwargs))


    def flash(self, msg = None, status = "OK"):
        if msg:
            self.session["message"] = msg
            self.session.save()
        else:
            tmp = self.session.pop("message")
            self.session.save()
            return tmp

    def need_flash(self):
        return bool(self.session.get("message", False))


    def getOr404(self, obj, id, redirect_url = "/index", message = "The record deosn't exist!"):
        try:
            return DBSession.query(obj).filter(obj.id == id).one()
        except:
            self.flash(message)
            self.redirect(redirect_url)

    def upload(self, file_name):
        try:
            f = self.request.files[file_name][0]
            original_fname = f['filename']
            extension = os.path.splitext(original_fname)[1].lower()
            fname = Date2Text(dateTimeFormat = "%Y%m%d%H%M%S", defaultNow = True) + ''.join(random.choice(string.ascii_lowercase + string.digits) for x in range(6))
            final_filename = fname + extension

            d = os.path.join(self.application.settings.get("static_path"),
                             self.application.settings.get("upload_relative_path"))
            if not os.path.exists(d):
                os.makedirs(d)
            full_path = os.path.join(d, final_filename)
            output_file = open(full_path, 'wb')
            output_file.write(f['body'])
            output_file.close()

            DBSession.add(Attachment(name = final_filename, path = full_path, original_name = original_fname,
                                     url = self.static_url("/".join([self.application.settings.get("upload_relative_path"), final_filename]))))
            DBSession.commit()
            return (0, original_fname, final_filename, full_path)
        except:
            DBSession.rollback()
            logging.error(traceback.print_exc())
            return (1, None, None, None)


    def is_user_login(self):
        return self.session.get("is_user_login", False)

    def get_any_permissions(self, *permissions):
        user_permissions = self.session.get("permissions", [])
        for permission in permissions:
            if permission in user_permissions: return True
        return False

    def get_all_permissions(self, *permissions):
        user_permissions = self.session.get("permissions", [])
        for permission in permissions:
            if permission not in user_permissions: return False
        return True

    def in_any_groups(self, *groups):
        user_groups = self.session.get("groups", [])
        for group in groups:
            if group in user_groups : return True
        return False

    def in_all_groups(self, *groups):
        user_groups = self.session.get("groups", [])
        for group in groups:
            if group not in user_groups : return False
        return True

    def get_current_user(self):
        return self.session.get("user", None)

    def get_user_locale(self):
        try:
            logging.info(self.session["user"].locale)
            return tornado.locale.get(self.session["user"].locale)
        except:
            logging.info("*" * 20)
            logging.info(traceback.print_exc())
            return None
コード例 #2
0
class MethodDispatcher(tornado.web.RequestHandler):
    """
    Subclasss this to have all of your class's methods exposed to the web
    for both GET and POST requests.  Class methods that start with an
    underscore (_) will be ignored.
    """

    def initialize(self, **kw):
        self.session = TornadoSession(self.application.session_manager, self)

    def _dispatch(self):
        """
        Load up the requested URL if it matches one of our own methods.
        Skip methods that start with an underscore (_).
        """
        args = None
        # Sanitize argument lists:
        if self.request.arguments:
            args = delist_arguments(self.request.arguments)
        # Special index method handler:
        if self.request.uri.endswith('/'):
            func = getattr(self, 'index', None)
            if args:
                return func(**args)
            else:
                return func()
        path = self.request.uri.split('?')[0]
        method = path.split('/')[-1]
        if not method.startswith('_'):
            func = getattr(self, method, None)
            if func:
                if args:
                    return func(**args)
                else:
                    return func()
            else:
                raise tornado.web.HTTPError(404)
        else:
            raise tornado.web.HTTPError(404)

    def get(self):
        """Returns self._dispatch()"""
        return self._dispatch()

    def post(self):
        """Returns self._dispatch()"""
        return self._dispatch()

    #===========================================================================
    # add the login function
    #===========================================================================
    def get_current_user(self):
        return self.get_secure_cookie("user")

    def set_current_user(self, name):
        self.set_secure_cookie("user", name)

    def clear_current_user(self):
        self.clear_cookie("user")

    #===========================================================================
    # add the flash function
    #===========================================================================

    def flash(self, msg = None, status = "OK"):
        if msg:
            self.session["message"] = msg
            self.session.save()
        else:
            tmp = self.session.pop("message")
            self.session.save()
            return tmp

    def need_flash(self):
        return bool(self.session.get("message", False))