예제 #1
0
파일: sessions.py 프로젝트: ZiTAL/zpy
	def remove(self):
		count = Session.get('count')
		if count > 0:
			count = count - 1
		else:
			count = 0

		Session.set('count', count)
		raise web.seeother('/session/get/')
예제 #2
0
파일: public.py 프로젝트: lujinda/pylot
class PublicHandler(RequestHandler):
    def initialize(self):
        self.session = Session(self.application.session_manager, self)
        self.init_data()

    def init_data(self):
        pass

    @authenticated # tornado会在prepare()后检查一下_finished值,而redirect后会把_finished设置成True
    def prepare(self):
        self.method_before()
        
    def method_before(self):
        """在执行任何method前都会执行的"""
        pass

    @property
    def UA(self):
        return self.request.headers.get('User-Agent', '')

    def is_authenticated(self):
        return self.current_user

    @property
    def current_user(self):
        return self.session.get('user', None)

    @property
    def client_ip(self):
        return self.request.remote_ip

    @property
    def full_host(self):
        return self.request.protocol + '://' + self.request.host

    @property
    def redis_db(self):
        return self.application.redis_db
예제 #3
0
class PublicHandler(RequestHandler):
    def initialize(self):
        self.session = Session(self.application.session_manager, self)
        self.init_data()

    def init_data(self):
        pass

    @authenticated  # tornado会在prepare()后检查一下_finished值,而redirect后会把_finished设置成True
    def prepare(self):
        self.method_before()

    def method_before(self):
        """在执行任何method前都会执行的"""
        pass

    @property
    def UA(self):
        return self.request.headers.get('User-Agent', '')

    def is_authenticated(self):
        return self.current_user

    @property
    def current_user(self):
        return self.session.get('user', None)

    @property
    def client_ip(self):
        return self.request.remote_ip

    @property
    def full_host(self):
        return self.request.protocol + '://' + self.request.host

    @property
    def redis_db(self):
        return self.application.redis_db
예제 #4
0
파일: sessions.py 프로젝트: ZiTAL/zpy
	def add(self):
		count = Session.get('count')
		count = count + 1
		Session.set('count', count)
		raise web.seeother('/session/get/')
예제 #5
0
파일: sessions.py 프로젝트: ZiTAL/zpy
	def get(self):
		params = {}
		params['key'] = 'count'
		params['value'] = Session.get('count')

		return View.load('/session/get.tpl', params)
예제 #6
0
파일: base.py 프로젝트: kyleslight/wutong
class BaseHandler(RequestHandler):
    def __init__(self, *args, **kwargs):
        super(BaseHandler, self).__init__(*args, **kwargs)
        self.session = Session(self)
        self.db = self.application.db
        if not isinstance(self, WebSocketHandler):
            # record last view url
            self.set_cookie('last_view', self.request.uri)
            # 一天后过期, 防盗链
            self.set_cookie('uuid', self.uuid, expires_days=1)

    def on_finish(self):
        self.session.save()

    def non_block_call(self, func, *args, **kwargs):
        return IOLoop.instance().add_callback(func, *args, **kwargs)

    @property
    def uuid(self):
        """
        unique user identification
        """
        return uuid.uuid3(uuid.NAMESPACE_DNS, self.ip).hex

    def is_human(self):
        return self.uuid == self.get_cookie('uuid')

    def get_current_user(self, user_id=None):
        """
        if you want a cached version of `get_current_user`, you can use
        `current_user`
        """
        return self.muser.get_user(user_id or self.user_id)

    def get_pure_user(self, user=None):
        """
        被客户端接收的用户信息, 不包含权限等客户端无关信息
        """
        user = user or self.current_user
        return {
            'nickname': user['nickname'],
            'avatar': user['avatar'],
            'intro': user['intro'],
            'motto': user['motto'],
        }

    @property
    def user_id(self):
        return self.session.get("uid")

    @property
    def muser(self):
        """
        model of user
        """
        if not hasattr(self, "_user_model"):
            self._user_model = user.UserModel(self.db)
        return self._user_model

    @property
    def mgroup(self):
        if not hasattr(self, "_group_model"):
            self._group_model = group.GroupModel(self.db)
        return self._group_model

    @property
    def marticle(self):
        if not hasattr(self, "_article_model"):
            self._article_model = article.ArticleModel(self.db)
        return self._article_model

    def get_argument(self, name, default=None):
        return super(BaseHandler, self).get_argument(name, default)

    def has_argument(self, name):
        return name in self.request.arguments

    @property
    def args(self):
        if not hasattr(self, '_args'):
            self._args = {}
        return self._args

    def get_args(self, *args, **newnames):
        for name in args:
            newname = newnames.get(name, name)
            self.get_arg(name, newname=newname)
        return self.args

    def get_arg(self, name, default=None, newname=None):
        value = self.get_argument(name, default)
        name = newname or name
        self.args[name] = value
        return value

    def set_arg(self, name, value):
        if self.has_arg(name) is None:
            return None
        self.args[name] = value
        return value

    def has_arg(self, name):
        return self.args.get(name)

    def check_arg(self, name, func, result=True, errmsg=None):
        """
        调用`func`检查指定参数. 若参数不存在, 则返回`default`, 否则返回`func`返回值
        """
        value = self.args.get(name)
        if value and func(value) != result:
            if not errmsg:
                errmsg = 'invalid ' + name
            raise Exception(errmsg)

    @property
    def ip(self):
        return self.request.remote_ip

    def get_module_path(self):
        module_path = os.path.join(self.get_template_path(), "modules")
        return module_path

    def render_module_string(self, module_name, **kwargs):
        module_path = self.get_module_path()
        return self.render_string(os.path.join(module_path, module_name),
                                  **kwargs)

    def render_404_page(self):
        self.render('404.html')

    def get(self):
        self.render_404_page()

    def post(self):
        self.write_error(403)

    def message2json(self, msg, errno=0):
        return json_encode({"msg": msg, "errno": errno})

    def write_result(self, msg='', errno=0):
        """
        :errno 错误码, 0=正常, 0<出错, 0>出错但未设置错误码
        """
        self.write(self.message2json(msg, errno))

    def write_errmsg(self, msg='', errno=-1):
        self.write_result(str(msg), errno)

    def write_json(self, data, errmsg='unknown error'):
        """
        若data为空值, 发送err指定的错误信息
        """
        if data is None or data == '':
            self.write_errmsg(errmsg)
        elif isinstance(data, (basestring, str, unicode)):
            self.write(data)
        else:
            self.write(json_encode(data))
예제 #7
0
class BaseHandler(RequestHandler):
    def initialize(self, method=''):

        #初始化Sesion

        self._session = Session(self, config.setting['session']['time_out'],
                                config.setting['session']['expires_days'])

        self._method = method

        self._cur_entity = None

        #self._passport = Passport(self)

    def get_current_user(self):

        token_str = self.get_argument('token', '')

        if len(token_str) > 0:

            self._session.set_sessionid_by_token(token_str)

        return self._session.get('user')

    def check_user_login(self):

        if self._session.get('user') is None:

            return False

        else:

            return True

    def generate_token(self):

        token_str = self._session.generate_uuid()

        if Mem.set(token_str, 'token',
                   config.setting['session']['token_time_out']) == False:

            return None

        else:

            return token_str

    def get_current_uid(self):

        user = self._session.get('user')

        if user is None:

            return 0

        else:

            return user['uid']

    def get_num(self, param, default=0):

        num = self.get_argument(param, default)

        if num is None and default is None:

            return None

        else:

            try:

                num = int(num)

                return num

            except Exception, e:

                return default
예제 #8
0
class WebBaseHandler(tornado.web.RequestHandler):
    user = None

    def __init__(self, *argc, **argkw):
        super(WebBaseHandler, self).__init__(*argc, **argkw)
        self.session = Session(self.application.session_manager, self)

    def get_current_user(self):
        user = {}
        user['UserNick'] = self.session.get('UserNick')
        user['UserNo'] = self.session.get('UserNo')
        user['UserType'] = self.session.get('UserType')
        user['UserTypeName'] = self.session.get('UserTypeName')
        user['uid'] = self.session.get('uid')
        return user

    def get_user_id(self):
        #return self.get_secure_cookie('uid', 0)
        return self.session.get('uid')

    def get_login_url(self):
        return '/login'

    def check_login(self):
        #if not login, redirect to login page
        self.user = None
        #try use session API
        self.user = self.get_current_user()
        if self.user['uid']:
            return True
        else:
            self.redirect("/login")
            return False

        #uid = self.get_secure_cookie('uid')
        uid = self.get_user_id()
        logger.error('check_login:  uid=%s' % uid)
        #uid = self.get_cookie('userid')
        if uid == None or uid == '':
            self.top_redirect('/login')
        else:
            u = self.get_cache(self.get_session_key(uid));
            logger.error("session value: %s" % u)
            if u and not u == '':
                user = json.loads(u)
                if isinstance(user, dict):
                    self.user = user
                    #print self.user
                    #{u'UserNick': u'', u'UserType': 0, u'UserNo': u'8'}
                    return True
            else:
                logger.error("session timeouted: uid=%s" % uid)
                self.top_redirect('/login')
        return False

    def top_redirect(self, url):
        self.redirect(url)
        #html = "<html><head/><script>alert(window.top.location.toString())</script></html>"
        #self.send_html(html)
        return

    def send_json(self, result, code=200):
        self.set_header("Content-Type", "application/json")
        self.set_header('Access-Control-Allow-Origin', '*')
        self.set_status(code)
        #import codecs
        #with codecs.open('tmp.txt','w','utf-8') as fp:
               #json.dump(a,fp,ensure_ascii=False,indent=4)
        #_json = json.dumps(result, ensure_ascii=False, indent=4)
        _json = json.dumps(result, cls=MyEncoder, ensure_ascii=False, indent=4)
        #_json = json.dumps(result)
        self.write(_json)
        self.finish()

    def send_xml(self, result, code=200):
        self.set_header("Content-Type", "application/xml")
        if len(result) == 1:
            xml = xmltodict.unparse(result) #dict_to_xml(result)
        else:
            xml = xmltodict.unparse({'root':result})#dict_to_xml({'root': result})
        self.set_status(code)
        self.write(xml)
        self.finish()

    def send_string(self, result, code=200):
        self.set_header("Content-Type", "text/plain")
        self.set_header('Access-Control-Allow-Origin', '*')
        self.set_status(code)
        self.write(result)
        self.finish()

    def send_html(self, result, code=200):
        self.set_header("Content-Type", "text/html; charset=UTF-8")
        self.set_status(code)
        self.write(result)
        self.finish()
        
    def send_text(self, result, code=200):
        self.set_header("Content-Type", "text/event-stream")
        self.set_header('Access-Control-Allow-Origin', '*')
        self.set_status(code)
        _json = json.dumps(result, cls=MyEncoder, ensure_ascii=False, indent=4)
        self.write('data: '+_json.replace("\n","").replace("\r","")+'\r\n\r\n')
        self.finish()
    def send_img(self, result, code=200):
        self.set_header("Content-Type", "image/bmp")
        self.set_header('Access-Control-Allow-Origin', '*')
        self.set_status(code)
        self.write(result)
        self.finish()


    def get_session_key(self, userid):
        return 'session:%s' % userid

    def get_user_cache_key(self, userid):
        return '%s:login' % userid

    def short_desc(self, desc, lenth=10):
        if not desc:
            return ''
        if len(desc) > lenth:
            return desc[0:lenth] + '...'
        else:
            return desc

    def page_info(self, path, total, psize, cur_page):
        '''
        generage a page number information in dict format.

        @params:
            @path: string, the url path which would be refert to
            @total:  total count for items
            @psize:  pagesize, how many items for each page
            @cur_page: page number for current page

        Retuens:
            dict, 

        '''
        pageinfo = {}
        if total % psize:
            pageinfo['totalpage'] = total / psize + 1
        else:
            pageinfo['totalpage'] = total / psize
        pageinfo['currentpage'] = cur_page
        pageinfo['pagesize'] = psize
        pageinfo['path'] = path

        return pageinfo