예제 #1
0
    def render(self, *args, **kwargs):

        self.minfo = MInfor()
        tag_slug = args[0]
        current = int(args[1])
        # cat_slug 分类
        # current 当前页面

        cat_rec =  self.minfo.query_by_tagname(tag_slug)

        page_num = int(cat_rec.count() / config.page_num)

        kwd = {
            'page_home': False if current <= 1 else True,
            'page_end': False if current >= page_num else True,
            'page_pre': False if current <= 1 else True,
            'page_next': False if current >= page_num else True,
        }

        return self.render_string('modules/post/info_label_pager.html',
                                  kwd=kwd,
                                  cat_slug=tag_slug,
                                  pager_num=page_num,
                                  page_current=current,
                                  )
예제 #2
0
def build_whoosh_database():
    analyzer = ChineseAnalyzer()
    schema = Schema(title=TEXT(stored=True, analyzer=analyzer),
                    type=TEXT(stored=True),
                    link=ID(stored=True),
                    content=TEXT(stored=True, analyzer=analyzer))
    ix = create_in(whoosh_database, schema)

    writer = ix.writer()

    uu = MInfor()

    tt = uu.get_all()
    for rec in tt:
        text2 = html2text.html2text(tornado.escape.xhtml_unescape(
            rec.cnt_html))
        writer.add_document(
            title=rec.title,
            type='<span style="color:red;">[信息]</span>',
            link='/info/{0}'.format(rec.uid),
            content=text2,
        )

    mpost = MPost()
    recs = mpost.query_all()
    for rec in recs:
        text2 = html2text.html2text(tornado.escape.xhtml_unescape(
            rec.cnt_html))
        print(text2)
        writer.add_document(title=rec.title,
                            type='<span style="color:blue;">[文档]</span>',
                            link='/post/{0}.html'.format(rec.uid),
                            content=text2)

    writer.commit()
예제 #3
0
 def initialize(self, hinfo=''):
     self.init()
     self.mevaluation = MEvaluation()
     self.mapp2catalog = MInfor2Catalog()
     self.mapp2tag = MInfor2Label()
     self.minfo = MInfor()
     self.musage = MUsage()
     self.mcat = MCategory()
     self.mrel = MInforRel()
     # self.mreply = MInfor2Reply()
     self.kind = '2'
예제 #4
0
 def initialize(self, hinfo=''):
     self.init()
     self.mevaluation = MEvaluation()
     self.mpost2label = MInfor2Label()
     self.mpost2catalog = MInfor2Catalog()
     self.mpost = MInfor()
     self.musage = MUsage()
     self.mcat = MCategory()
     self.mrel = MInforRel()
     self.mreply = MReply()
     self.mpost_hist = MInfoHist()
예제 #5
0
    def initialize(self):

        self.init()
        self.mpost = MInfor()
        self.mcat = MCategory()
        self.cats = self.mcat.query_all()
        self.mpost_hist = MInfoHist()
        self.mpost2catalog = MInfor2Catalog()
        self.mpost2reply = MInfor2Reply()
        self.mpost2label = MInfor2Label()
        self.mrel = MInforRel()

        self.musage = MUsage()
        self.mevaluation = MEvaluation()
        self.kind = '2'
예제 #6
0
def do_for_app(writer, rand=True, kind='', doc_type=''):
    mpost = MApp()
    if rand:
        recs = mpost.query_random(50, kind=kind)
    else:
        recs = mpost.query_recent(50, kind=kind)

    print(recs.count())
    for rec in recs:
        # # sleep(0.1)
        text2 = rec.title + ',' + html2text.html2text(
            tornado.escape.xhtml_unescape(rec.cnt_html))
        writer.update_document(catid='00000',
                               title=rec.title,
                               type=doc_type[rec.kind],
                               link='/{0}/{1}'.format(router_post[rec.kind],
                                                      rec.uid),
                               content=text2)
예제 #7
0
def do_for_app(writer, rand=True):
    mpost = MApp()
    if rand:
        recs = mpost.query_random(50)
    else:
        recs = mpost.query_recent(50)
    doc_type = '<span style="color:blue;" class="glyphicon glyphicon-map-marker">[{0}]</span>'.format(
        '地图')
    print(recs.count())
    for rec in recs:
        # # sleep(0.1)
        text2 = rec.title + ',' + html2text.html2text(
            tornado.escape.xhtml_unescape(rec.cnt_html))
        # writer.update_document(path=u"/a",content="Replacement for the first document")
        writer.update_document(title=rec.title,
                               type=doc_type,
                               link='/map/{0}'.format(rec.uid),
                               content=text2)
예제 #8
0
    def render(
        self,
        uid,
        num,
    ):
        self.app = MInfor()
        self.relation = MRelPost2Infor()
        kwd = {
            'app_f': 'post',
            'app_t': 'info',
            'uid': uid,
        }
        rel_recs = self.relation.get_app_relations(uid, num, kind='2')

        rand_recs = self.app.query_random(num - rel_recs.count() + 2, kind='2')

        return self.render_string(
            'modules/info/relation_post2app.html',
            relations=rel_recs,
            rand_recs=rand_recs,
            kwd=kwd,
        )
예제 #9
0
class RelHandler(BaseHandler):
    def initialize(self):
        self.init()
        self.mapp = MInfor()
        self.mpost = MPost()
        self.rel_post2app = MRelPost2Infor()
        self.rel_app2post = MRelInfor2Post()

    def get(self, url_str=''):
        if len(url_str) > 0:
            ip_arr = url_str.split('/')
        else:
            return False
        if len(ip_arr) == 2:
            self.add_relation(ip_arr)

    def check_app(self, tt, uid):

        if tt == 'post':
            if False == self.mpost.get_by_id(uid):
                return False
        if tt == 'app':
            if False == self.mapp.get_by_uid(uid):
                return False
        return True

    def add_relation(self, url_arr):
        if self.check_app(url_arr[0], url_arr[1]):
            pass
        else:
            return False

        last_post_id = self.get_secure_cookie('last_post_uid')
        if last_post_id:
            last_post_id = last_post_id.decode('utf-8')

        last_app_id = self.get_secure_cookie('use_app_uid')
        if last_app_id:
            last_app_id = last_app_id.decode('utf-8')

        if url_arr[0] == 'info':
            if last_post_id:
                self.rel_post2app.add_relation(last_post_id, url_arr[1], 2)
                self.rel_app2post.add_relation(url_arr[1], last_post_id, 1)

        if url_arr[0] == 'post':
            if last_app_id:
                self.rel_app2post.add_relation(last_app_id, url_arr[1], 2)
                self.rel_post2app.add_relation(url_arr[1], last_app_id, 1)
예제 #10
0
def do_for_app2(writer, rand=True):
    mpost = MApp()
    if rand:
        recs = mpost.query_random(50)
    else:
        recs = mpost.query_recent(50)

    print(recs.count())
    for rec in recs:
        # # sleep(0.1)
        text2 = rec.title + ',' + html2text.html2text(
            tornado.escape.xhtml_unescape(rec.cnt_html))
        # writer.update_document(path=u"/a",content="Replacement for the first document")

        info = minfo2tag.get_entry_catalog(rec.uid)
        if info:
            print(info.uid)
            print(info.tag.uid)
            print(info.tag.kind)
            pass
        else:
            continue

        catid = info.tag.uid[:2] + '00'

        cat_name = ''
        if 'def_cat_uid' in rec.extinfo and rec.extinfo['def_cat_uid']:
            uu = mappcat.get_by_uid(rec.extinfo['def_cat_uid'][:2] + '00')
            if uu:
                cat_name = uu.name
        writer.update_document(
            title=rec.title,
            catid=catid,
            type='<span style="color:red;">[{0}]</span>'.format(cat_name),
            link='/{0}/{1}'.format(router_post[rec.kind], rec.uid),
            content=text2)
예제 #11
0
 def initialize(self):
     self.init()
     self.kind = 'm'
     self.mequa = MInfor()
     self.mcat = MCategory()
     self.mapp2tag = MInfor2Catalog()
예제 #12
0
# -*- coding:utf-8 -*-

from torcms.model.info_model import MInfor
from torcms.model.post2catalog_model import MPost2Catalog
from torcms.model.wiki_model import MWiki
from torcms.model.label_model import MLabel
from torcms.model.category_model import MCategory
from config import router_post

mcat = MCategory()
mlabel = MLabel()
mpost = MInfor()
mpost2tag = MPost2Catalog()
mwiki = MWiki()


def run_nocat():
    for key in router_post.keys():
        if key == 'i':
            continue
        post_recs = mpost.query_all(limit_num=50000, kind=key)
        for postinfo in post_recs:
            cat = mpost2tag.get_entry_catalog(postinfo.uid)
            if cat:
                pass
            else:
                print(postinfo.uid)
예제 #13
0
 def initialize(self):
     self.init()
     self.mapplication = MApp()
예제 #14
0
 def initialize(self):
     self.init()
     self.kind = constant['cate_info']
     self.mequa = MInfor()
     self.mcat = MCategory()
     self.mapp2tag = MInfor2Catalog()
예제 #15
0
 def initialize(self, hinfo=''):
     self.init()
     self.template_dir_name = 'infor'
     self.minfo = MInfor()
     self.mappcat = MCategory()
예제 #16
0
class MapOverlayHandler(BaseHandler):
    def initialize(self):
        self.init()
        self.mapplication = MApp()


    def get(self, url_str=''):
        if len(url_str) > 0:
            url_arr = url_str.split('/')
        else:
            url_arr = []
        if len(url_arr) > 1:
            self.show_overlay(url_arr)
        else:
            kwd = {
                'title': '',
                'info': '',
            }
            self.render('html/404.html', kwd=kwd,
                        userinfo = self.userinfo,)

    def show_overlay(self, app_arr):
        '''
        打开App.
        '''
        app_info_arr = []
        lon_arr = []
        lat_arr = []
        zoom_max_arr = []
        zoom_min_arr = []
        zoom_current_zrr = []

        # self.set_secure_cookie('over_kay', app_arr)

        for app_rr in app_arr:
            c_ap = self.mapplication.get_by_uid(app_rr)
            app_info_arr.append(c_ap)
            lon_arr.append(float(c_ap.extinfo['ext_lon']))
            lat_arr.append(float(c_ap.extinfo['ext_lat']))
            zoom_max_arr.append(int(c_ap.extinfo['ext_zoom_max']))
            zoom_min_arr.append(int(c_ap.extinfo['ext_zoom_min']))
            zoom_current_zrr.append(int(c_ap.extinfo['ext_zoom_current']))

        kwd = {'url': 1,
               "cookie_str": '',
               'lon': average(lon_arr),
               'lat': average(lat_arr),
               'zoom_max': max(zoom_max_arr),
               'zoom_min': min(zoom_min_arr),
               'zoom_current': int(average(zoom_current_zrr)),
               }
        if 'fullscreen' in self.request.arguments:
            tmpl = 'infor/overlay/overlay_full.html'
        else:
            tmpl = 'infor/overlay/overlay.html'
        self.render(tmpl,
                    topmenu='',
                    kwd=kwd,
                    userinfo=self.userinfo,
                    unescape=tornado.escape.xhtml_unescape,
                    app_arr=app_info_arr,
                    app_str='/'.join(app_arr),
                    wcs_svr=config.wcs_svr,
                    )
예제 #17
0
class InfoHandler(PostHandler):
    def initialize(self, hinfo=''):
        self.init()
        self.mevaluation = MEvaluation()
        self.mpost2label = MInfor2Label()
        self.mpost2catalog = MInfor2Catalog()
        self.mpost = MInfor()
        self.musage = MUsage()
        self.mcat = MCategory()
        self.mrel = MInforRel()
        self.mreply = MReply()
        self.mpost_hist = MInfoHist()
        self.kind = '2'
        self.sig = '2'  # '1' for maplet,  '2' for drr

    def get(self, url_str=''):
        url_arr = self.parse_url(url_str)

        if url_str == '':
            self.index()
        elif url_arr[0] in ['cat_add', '_cat_add']:
            self.to_add_with_category(url_arr[1])
        elif url_arr[0] in ['_add', 'add_document', 'add']:
            if len(url_arr) == 2:
                self.to_add(url_arr[1])
            else:
                self.to_add()
        elif len(url_arr) == 2:
            if url_arr[0] in ['edit', 'modify', '_edit']:
                self.to_edit(url_arr[1])

            elif url_arr[0] == 'delete':
                self.to_del_app(url_arr[1])
            else:
                '''
                从相关计算中过来的。
                '''
                pass

        elif len(url_arr) == 1:
            if len(url_str) in [4, 5]:
                self.view_info(url_str)

        else:
            kwd = {
                'title': '',
                'info': '',
            }
            self.set_status(404)
            self.render(
                'html/404.html',
                kwd=kwd,
                userinfo=self.userinfo,
            )

    def post(self, url_str=''):

        url_arr = self.parse_url(url_str)

        if url_arr[0] in ['to_add', '_add', 'add']:
            if len(url_arr) == 2:
                self.add(uid=url_arr[1])
            else:
                self.add()

        elif url_arr[0] in ['cat_add', '_cat_add']:
            self.add(catid=url_arr[1])
        elif url_arr[0] == 'rel':
            if self.get_current_user():
                self.add_relation(url_arr[1])
            else:
                self.redirect('/user/login')

        elif url_arr[0] in ['edit', '_edit']:
            self.update(url_arr[1])

        elif url_arr[0] == 'rel':
            if self.get_current_user():
                self.add_relation(url_arr[1], url_arr[2])
            else:
                self.redirect('/user/login')

        else:
            return False

    def view_info(self, info_id):
        '''
        Render the info
        :param info_id:
        :return: Nonthing.
        '''
        postinfo = self.mpost.get_by_uid(info_id)
        logger.warning('info kind:{0} '.format(postinfo.kind))

        # If not, there must be something wrong.
        if postinfo.kind == self.kind:
            pass
        else:
            self.redirect('/{0}/{1}'.format(router_post[postinfo.kind],
                                            info_id),
                          permanent=True)

        if postinfo:
            pass
        else:
            kwd = {
                'info': '您要找的信息不存在。',
            }
            self.render(
                'html/404.html',
                kwd=kwd,
                userinfo=self.userinfo,
            )
            return False

        cats = self.mpost2catalog.query_by_entity_uid(info_id,
                                                      kind=postinfo.kind)
        cat_uid_arr = []
        for cat_rec in cats:
            cat_uid = cat_rec.tag.uid
            cat_uid_arr.append(cat_uid)
        logger.info('info category: {0}'.format(cat_uid_arr))

        rel_recs = self.mrel.get_app_relations(postinfo.uid,
                                               8,
                                               kind=postinfo.kind)
        logger.info('rel_recs count: {0}'.format(rel_recs.count()))

        if len(cat_uid_arr) > 0:
            rand_recs = self.mpost.query_cat_random(cat_uid_arr[0],
                                                    4 - rel_recs.count() + 4)
        else:
            rand_recs = self.mpost.query_random(num=4 - rel_recs.count() + 4,
                                                kind=postinfo.kind)

        self.chuli_cookie_relation(info_id)
        cookie_str = tools.get_uuid()

        if 'def_cat_uid' in postinfo.extinfo:
            ext_catid = postinfo.extinfo['def_cat_uid']
        else:
            ext_catid = ''

        if len(ext_catid) == 4:
            pass
        else:
            ext_catid = ''

        catinfo = None
        p_catinfo = None

        post2catinfo = self.mpost2catalog.get_entry_catalog(postinfo.uid)
        if post2catinfo:
            catid = post2catinfo.tag.uid
            catinfo = self.mcat.get_by_uid(catid)
            if catinfo:
                p_catinfo = self.mcat.get_by_uid(catinfo.pid)

        kwd = {
            'pager': '',
            'url': self.request.uri,
            'cookie_str': cookie_str,
            'daohangstr': '',
            'signature': info_id,
            'tdesc': '',
            'eval_0': self.mevaluation.app_evaluation_count(info_id, 0),
            'eval_1': self.mevaluation.app_evaluation_count(info_id, 1),
            'login': 1 if self.get_current_user() else 0,
            'has_image': 0,
            'parentlist': self.mcat.get_parent_list(),
            'parentname': '',
            'catname': '',
            'router': router_post[postinfo.kind]
        }
        self.mpost.view_count_increase(info_id)
        if self.get_current_user():
            self.musage.add_or_update(self.userinfo.uid, info_id,
                                      postinfo.kind)
        self.set_cookie('user_pass', cookie_str)
        tmpl = self.ext_tmpl_name(postinfo) if self.ext_tmpl_name(
            postinfo) else self.get_tmpl_name(postinfo)

        print('info tmpl: ' + tmpl)
        ext_catid2 = postinfo.extinfo[
            'def_cat_uid'] if 'def_cat_uid' in postinfo.extinfo else None

        if self.userinfo:
            recent_apps = self.musage.query_recent(self.userinfo.uid,
                                                   postinfo.kind, 6)[1:]
        else:
            recent_apps = []
        self.render(
            tmpl,
            kwd=dict(kwd, **self.extra_kwd(postinfo)),
            calc_info=postinfo,  # Deprecated
            post_info=postinfo,  # Deprecated
            postinfo=postinfo,
            userinfo=self.userinfo,
            catinfo=catinfo,
            pcatinfo=p_catinfo,
            relations=rel_recs,
            rand_recs=rand_recs,
            unescape=tornado.escape.xhtml_unescape,
            ad_switch=random.randint(1, 18),
            tag_info=self.mpost2label.get_by_id(info_id),
            recent_apps=recent_apps,
            cat_enum=self.mcat.get_qian2(ext_catid2[:2]) if ext_catid else [],
        )

    def extra_kwd(self, info_rec):
        '''
        The additional information.
        :param info_rec:
        :return: directory.
        '''
        return {}

    def chuli_cookie_relation(self, app_id):
        '''
        The current Info and the Info viewed last should have some relation.
        And the last viewed Info could be found from cookie.
        :param app_id: the current app
        :return: None
        '''
        last_app_uid = self.get_secure_cookie('use_app_uid')
        if last_app_uid:
            last_app_uid = last_app_uid.decode('utf-8')
        self.set_secure_cookie('use_app_uid', app_id)
        if last_app_uid and self.mpost.get_by_uid(last_app_uid):
            self.add_relation(last_app_uid, app_id)

    def ext_tmpl_name(self, rec):
        return None

    def get_tmpl_name(self, rec):
        '''
        According to the application, each info of it's classification could has different temaplate.
        :param rec: the App record.
        :return: the temaplte path.
        '''
        if 'def_cat_uid' in rec.extinfo and rec.extinfo['def_cat_uid'] != '':
            cat_id = rec.extinfo['def_cat_uid']
        else:
            cat_id = False
        if cat_id and self.sig == '2':
            tmpl = 'autogen/view/view_{0}.html'.format(cat_id)
        else:
            tmpl = 'post_{0}/show_map.html'.format(self.kind)
        return tmpl

    def add_relation(self, f_uid, t_uid):
        '''
        Add the relation. And the from and to, should have different weight.
        :param f_uid:
        :param t_uid:
        :return: return True if the relation has been succesfully added.
        '''
        if self.mpost.get_by_uid(t_uid):
            pass
        else:
            return False
        if f_uid == t_uid:
            return False

        # 针对分类进行处理。只有落入相同分类的,才加1
        f_cats = self.mpost2catalog.query_by_entity_uid(f_uid)
        t_cats = self.mpost2catalog.query_by_entity_uid(t_uid)
        flag = False
        for f_cat in f_cats:
            for t_cat in t_cats:
                if f_cat.tag == t_cat.tag:
                    flag = True
        if flag:
            pass
        else:
            return False

        self.mrel.add_relation(f_uid, t_uid, 2)
        self.mrel.add_relation(t_uid, f_uid, 1)
        return True

    def gen_uid(self):
        cur_uid = self.kind + tools.get_uu4d()
        while self.mpost.get_by_id(cur_uid):
            cur_uid = self.kind + tools.get_uu4d()
        return cur_uid

    @tornado.web.authenticated
    def to_add_with_category(self, catid):
        '''
        Used for OSGeo
        :param catid:
        :param sig:
        :return:
        '''
        if self.check_post_role(self.userinfo)['ADD']:
            pass
        else:
            return False
        catinfo = self.mcat.get_by_uid(catid)
        kwd = {
            'uid': self.gen_uid(),
            'userid': self.userinfo.user_name,
            'def_cat_uid': catid,
            'parentname': self.mcat.get_by_id(catinfo.pid).name,
            'catname': self.mcat.get_by_id(catid).name,
        }

        self.render('autogen/add/add_{0}.html'.format(catid),
                    userinfo=self.userinfo,
                    kwd=kwd)

    @tornado.web.authenticated
    def to_add(self, uid=''):
        # Used for yunsuan, maplet
        if self.check_post_role(self.userinfo)['ADD']:
            pass
        else:
            return False
        if uid != '' and self.mpost.get_by_uid(uid):
            # todo:
            # self.redirect('/{0}/edit/{1}'.format(self.app_url_name, uid))
            pass
        self.render('post_{0}/add.html'.format(self.kind),
                    tag_infos=self.mcat.query_all(by_order=True,
                                                  kind=self.kind),
                    userinfo=self.userinfo,
                    kwd={
                        'uid': uid,
                    })

    @tornado.web.authenticated
    def to_del_app(self, uid):
        current_infor = self.mpost.get_by_uid(uid)

        if self.check_post_role(self.userinfo)['DELETE']:
            pass
        else:
            return False

        if self.mpost.delete(uid):
            self.redirect('/list/{0}'.format(
                current_infor.extinfo['def_cat_uid']))
        else:
            self.redirect('/{0}/{1}'.format(router_post[self.kind], uid))

    @tornado.web.authenticated
    def to_edit(self, infoid):

        if self.check_post_role(self.userinfo)['EDIT']:
            pass
        else:
            return False

        rec_info = self.mpost.get_by_uid(infoid)
        postinfo = rec_info

        if rec_info:
            pass
        else:
            self.render('html/404.html')
            return
        if 'def_cat_uid' in rec_info.extinfo:
            catid = rec_info.extinfo['def_cat_uid']
        else:
            catid = ''

        if len(catid) == 4:
            pass
        else:
            catid = ''

        catinfo = None
        p_catinfo = None

        post2catinfo = self.mpost2catalog.get_entry_catalog(postinfo.uid)
        if post2catinfo:
            catid = post2catinfo.tag.uid
            catinfo = self.mcat.get_by_uid(catid)
            if catinfo:
                p_catinfo = self.mcat.get_by_uid(catinfo.pid)

        kwd = {
            'def_cat_uid': catid,
            'parentname': '',
            'catname': '',
            'parentlist': self.mcat.get_parent_list(),
            'userip': self.request.remote_ip
        }

        if self.sig == '2':
            tmpl = 'autogen/edit/edit_{0}.html'.format(catid)
        else:
            tmpl = 'post_{0}/edit.html'.format(self.kind)

        logger.info('Meta template: {0}'.format(tmpl))

        self.render(
            tmpl,
            kwd=kwd,
            calc_info=rec_info,  # Deprecated
            post_info=rec_info,  # Deprecated
            app_info=rec_info,  # Deprecated
            postinfo=rec_info,
            catinfo=catinfo,
            pcatinfo=p_catinfo,
            userinfo=self.userinfo,
            unescape=tornado.escape.xhtml_unescape,
            cat_enum=self.mcat.get_qian2(catid[:2]),
            tag_infos=self.mcat.query_all(by_order=True, kind=self.kind),
            tag_infos2=self.mcat.query_all(by_order=True, kind=self.kind),
            app2tag_info=self.mpost2catalog.query_by_entity_uid(
                infoid, kind=self.kind),
            app2label_info=self.mpost2label.get_by_id(infoid,
                                                      kind=self.kind + '1'))

    def get_def_cat_uid(self, post_data):
        # 下面两种处理方式,上面是原有的,暂时保留以保持兼容
        ext_cat_uid = {}
        if 'def_cat_uid' in post_data:
            ext_cat_uid['def_cat_uid'] = post_data['def_cat_uid']
            ext_cat_uid['def_cat_pid'] = self.mcat.get_by_uid(
                post_data['def_cat_uid']).pid
        if 'gcat0' in post_data:
            ext_cat_uid['def_cat_uid'] = post_data['gcat0']
            ext_cat_uid['def_cat_pid'] = self.mcat.get_by_uid(
                post_data['gcat0']).pid
        print(ext_cat_uid)
        return ext_cat_uid

    @tornado.web.authenticated
    def update(self, uid):

        if self.check_post_role(self.userinfo)['EDIT']:
            pass
        else:
            return False

        postinfo = self.mpost.get_by_uid(uid)
        if postinfo.kind == self.kind:
            pass
        else:
            return False

        post_data = {}
        ext_dic = {}
        for key in self.request.arguments:
            if key.startswith('ext_') or key.startswith('tag_'):
                ext_dic[key] = self.get_argument(key)
            else:
                post_data[key] = self.get_arguments(key)[0]

        post_data['user_name'] = self.userinfo.user_name

        if 'valid' in post_data:
            post_data['valid'] = int(post_data['valid'])
        else:
            post_data['valid'] = postinfo.valid

        ext_dic['def_uid'] = str(uid)
        print(post_data)

        ext_dic = dict(ext_dic, **self.get_def_cat_uid(post_data))

        ext_dic['def_tag_arr'] = [
            x.strip() for x in post_data['tags'].strip().strip(',').split(',')
        ]
        ext_dic = self.extra_data(ext_dic, post_data)

        cnt_old = tornado.escape.xhtml_unescape(postinfo.cnt_md).strip()
        cnt_new = post_data['cnt_md'].strip()
        if cnt_old == cnt_new:
            pass
        else:
            self.mpost_hist.insert_data(postinfo)

        self.mpost.modify_meta(uid, post_data, extinfo=ext_dic)
        self.update_category(uid)
        self.update_tag(uid)

        print('post kind:' + self.kind)
        print('update jump to:', '/{0}/{1}'.format(router_post[self.kind],
                                                   uid))

        self.redirect('/{0}/{1}'.format(router_post[postinfo.kind], uid))

    @tornado.web.authenticated
    def add(self, uid='', catid=''):
        print('info adding: ', 'catid: ', catid, 'infoid:', uid)

        if self.check_post_role(self.userinfo)['ADD']:
            pass
        else:
            return False

        ext_dic = {}
        post_data = {}
        for key in self.request.arguments:
            if key.startswith('ext_') or key.startswith('tag_'):
                ext_dic[key] = self.get_argument(key)
            else:
                post_data[key] = self.get_arguments(key)[0]
        post_data['user_name'] = self.userinfo.user_name
        post_data['kind'] = self.kind
        if catid == '':
            pass
        else:
            catinfo = self.mcat.get_by_uid(catid)
            if catinfo:
                post_data['kind'] = catinfo.kind
                print('Got category inf: ', catinfo.name, 'kind: ',
                      catinfo.kind)
            else:
                print('Could not find the category: ', catid)

        if uid == '':
            uid = self.gen_uid()

        if 'valid' in post_data:
            post_data['valid'] = int(post_data['valid'])
        else:
            post_data['valid'] = 1

        ext_dic['def_uid'] = uid

        ext_dic = dict(ext_dic, **self.get_def_cat_uid(post_data))

        ext_dic['def_tag_arr'] = [
            x.strip() for x in post_data['tags'].strip().strip(',').split(',')
        ]
        ext_dic = self.extra_data(ext_dic, post_data)

        self.mpost.modify_meta(ext_dic['def_uid'], post_data, extinfo=ext_dic)
        self.update_category(ext_dic['def_uid'])
        self.update_tag(ext_dic['def_uid'])

        self.redirect('/{0}/{1}'.format(router_post[self.kind], uid))
예제 #18
0
class InfoListHandler(BaseHandler):
    def initialize(self, hinfo=''):
        self.init()
        self.template_dir_name = 'infor'
        self.minfo = MInfor()
        self.mappcat = MCategory()

    def get(self, url_str=''):
        url_arr = self.parse_url(url_str)

        if len(url_str) == 4:

            self.list(url_str)
        elif len(url_str) > 4:
            self.echo_html(url_str)
        else:
            self.render('html/404.html', kwd={})

    def gen_redis_kw(self):
        condition = {}
        if self.get_current_user():
            redis_kw = redisvr.smembers(config.redis_kw +
                                        self.userinfo.user_name)
        else:
            redis_kw = []

        kw_condition_arr = []
        for x in redis_kw:
            kw_condition_arr.append(x.decode('utf-8'))
        if redis_kw:
            condition['def_tag_arr'] = kw_condition_arr
        return condition

    def echo_html(self, url_str):
        print(url_str)

        condition = self.gen_redis_kw()

        url_arr = self.parse_url(url_str)
        sig = url_arr[0]

        num = (len(url_arr) - 2) // 2

        if sig.endswith('00'):
            condition['def_cat_pid'] = sig
        else:
            condition['def_cat_uid'] = sig

        fenye_num = 1
        for ii in range(num):
            ckey = url_arr[ii * 2 + 2]

            tval = url_arr[ii * 2 + 3]
            if tval == '0':
                continue
            if ckey == 'fenye':
                # 分页参数。单独处理。
                fenye_num = int(tval)
                continue

            else:
                cval = tval
            ckey = 'tag_' + ckey
            condition[ckey] = cval

        print(condition)
        if url_arr[1] == 'con':
            infos = self.minfo.get_list_fenye(condition, fenye_num)
            self.echo_html_list_str(sig, infos)
        elif url_arr[1] == 'num':
            allinfos = self.minfo.get_list(condition)
            self.echo_html_fenye_str(allinfos.count(), fenye_num)

    def echo_html_list_str(self, list_type, infos):
        '''
        生成 list 后的 HTML 格式的字符串
        '''
        zhiding_str = ''
        tuiguang_str = ''
        imgname = 'fixed/zhanwei.png'

        kwd = {
            'imgname': imgname,
            'zhiding': zhiding_str,
            'tuiguang': tuiguang_str,
        }
        print(kwd)
        print('list type:', list_type)
        print('infos count', len(infos))
        self.render('autogen/infolist/infolist_{1}.html'.format(
            self.template_dir_name, list_type),
                    userinfo=self.userinfo,
                    kwd=kwd,
                    html2text=html2text,
                    unescape=tornado.escape.xhtml_unescape,
                    post_infos=infos,
                    widget_info=kwd)

    def echo_html_fenye_str(self, rec_num, fenye_num):
        '''
        生成分页的导航
        '''

        pagination_num = int(math.ceil(rec_num * 1.0 / 10))

        if pagination_num == 1 or pagination_num == 0:
            fenye_str = ''

        elif pagination_num > 1:
            pager_mid = ''
            pager_pre = ''
            pager_next = ''
            pager_last = ''
            pager_home = ''
            fenye_str = '<ul class="pagination">'

            if fenye_num > 1:
                pager_home = '''

                  <li class="{0}" name='fenye' onclick='change(this);'
                  value='{1}'><a>首页</a></li>'''.format('', 1)

                pager_pre = ''' <li class="{0}" name='fenye' onclick='change(this);'
                  value='{1}'><a>上一页</a></li>'''.format('', fenye_num - 1)
            if fenye_num > 5:
                cur_num = fenye_num - 4
            else:
                cur_num = 1

            if pagination_num > 10 and cur_num < pagination_num - 10:
                show_num = cur_num + 10

            else:
                show_num = pagination_num + 1

            for num in range(cur_num, show_num):
                if num == fenye_num:
                    checkstr = 'active'
                else:
                    checkstr = ''

                tmp_str_df = '''

                  <li class="{0}" name='fenye' onclick='change(this);'
                  value='{1}'><a>{1}</a></li>'''.format(checkstr, num)

                pager_mid += tmp_str_df
            if fenye_num < pagination_num:
                pager_next = '''

                  <li class="{0}" name='fenye' onclick='change(this);'
                  value='{1}'><a>下一页</a></li>'''.format('', fenye_num + 1)
                pager_last = '''

                  <li class="{0}" name='fenye' onclick='change(this);'
                  value='{1}'><a>末页</a></li>'''.format('', pagination_num)

            fenye_str += pager_home + pager_pre + pager_mid + pager_next + pager_last
            fenye_str += '</ul>'

        else:
            pass
        self.write(fenye_str)

    def list(self, input):
        '''
        页面打开后的渲染方法,不包含 list 的查询结果与分页导航
        '''

        condition = self.gen_redis_kw()

        sig = input
        bread_title = ''
        bread_crumb_nav_str = '<li>当前位置:<a href="/">信息</a></li>'

        if input.endswith('00'):
            parent_id = input
            parent_catname = self.mappcat.get_by_id(parent_id).name
            condition['parentid'] = [parent_id]
            catname = self.mappcat.get_by_id(sig).name
            bread_crumb_nav_str += '<li><a href="/list/{0}">{1}</a></li>'.format(
                sig, catname)
            bread_title = '{1}'.format(sig, catname)

        else:
            condition['catid'] = [sig]
            parent_id = sig[:2] + '00'
            parent_catname = self.mappcat.get_by_id(parent_id).name
            catname = self.mappcat.get_by_id(sig).name
            bread_crumb_nav_str += '<li><a href="/list/{0}">{1}</a></li>'.format(
                parent_id, parent_catname)

            bread_crumb_nav_str += '<li><a href="/list/{0}">{1}</a></li>'.format(
                sig, catname)
            bread_title += '{1} - '.format(parent_id, parent_catname)
            bread_title += '{1}'.format(sig, catname)

        num = self.minfo.get_num_condition(condition)

        kwd = {
            'catid': input,
            'daohangstr': bread_crumb_nav_str,
            'breadtilte': bread_title,
            'parentid': parent_id,
            'parentlist': self.mappcat.get_parent_list(),
            'condition': condition,
            'catname': catname,
            'rec_num': num,
        }

        cat_rec = self.mappcat.get_by_uid(input)
        role_mask_idx = cat_rec.role_mask.index('1')

        if self.get_current_user():
            redis_kw = redisvr.smembers(config.redis_kw +
                                        self.userinfo.user_name)
        else:
            redis_kw = []
        kw_condition_arr = []
        for x in redis_kw:
            kw_condition_arr.append(x.decode('utf-8'))
        self.render(
            'autogen/list/list_{1}.html'.format(self.template_dir_name, input),
            userinfo=self.userinfo,
            kwd=kwd,
            widget_info=kwd,
            condition_arr=kw_condition_arr,
            cat_enum=self.mappcat.get_qian2(parent_id[:2]),
            role_mask_idx=role_mask_idx,
        )
예제 #19
0
    def initialize(self):
        self.init()

        self.mequa = MInfor()
        self.mtag = MInforLabel()
        self.mapp2tag = MInfor2Label()
예제 #20
0
class MetaHandler(PostHandler):
    def initialize(self):

        self.init()
        self.mpost = MInfor()
        self.mcat = MCategory()
        self.cats = self.mcat.query_all()
        self.mpost_hist = MInfoHist()
        self.mpost2catalog = MInfor2Catalog()
        self.mpost2reply = MInfor2Reply()
        self.mpost2label = MInfor2Label()
        self.mrel = MInforRel()

        self.musage = MUsage()
        self.mevaluation = MEvaluation()
        self.kind = '2'
        # if 'app_url_name' in cfg:
        #     self.app_url_name = cfg['app_url_name']
        # else:
        #     self.app_url_name = 'info'

    def get(self, url_str=''):

        url_arr = self.parse_url(url_str)

        if url_arr[0] == 'cat_add':
            self.user_to_add(url_arr[1])
        elif url_arr[0] == 'catalog':
            self.catalog()
        # elif len(url_arr) == 1 and len(url_str) == 4:
        #     self.redirect('/{0}/{1}'.format(self.app_url_name, url_arr[0]))
        elif len(url_arr) == 2:
            if url_arr[0] == 'edit':
                self.to_edit_app(url_arr[1])
            elif url_arr[0] == 'add':
                self.to_add_app(url_arr[1])
            elif url_arr[0] == 'delete':
                self.to_del_app(url_arr[1])
            else:
                '''
                从相关计算中过来的。
                '''
                pass
                # self.mrel.update_relation(url_arr[1], url_arr[0])
                # self.redirect('/{0}/{1}'.format(self.app_url_name, url_arr[0]))
        else:
            kwd = {
                'title': '',
                'info': '',
            }
            self.render(
                'html/404.html',
                kwd=kwd,
                userinfo=self.userinfo,
            )

    def post(self, url_str=''):

        url_arr = self.parse_url(url_str)

        if url_arr[0] == 'to_add':
            self.add()
        elif url_arr[0] == 'rel':
            if self.get_current_user():
                self.add_relation(url_arr[1])
            else:
                self.redirect('/user/login')
        elif url_arr[0] == 'comment_add':
            self.add_comment(url_arr[1])
        elif url_arr[0] == 'edit':
            self.update(url_arr[1])
        elif url_arr[0] == 'add':
            self.add(url_arr[1])
        else:
            return False

    def catalog(self):
        self.render('infor/app/catalog.html',
                    userinfo=self.userinfo,
                    kwd={
                        'uid': '',
                    })

    @tornado.web.authenticated
    def user_to_add(self, catid, sig=''):

        uid = sig + tools.get_uu4d()
        while self.mpost.get_by_uid(uid):
            uid = sig + tools.get_uu4d()

        kwd = {
            'uid': uid,
            'userid': self.userinfo.user_name,
            'def_cat_uid': catid,
            'parentname': self.mcat.get_by_id(catid[:2] + '00').name,
            'catname': self.mcat.get_by_id(catid).name,
        }

        self.render('autogen/add/add_{0}.html'.format(catid),
                    userinfo=self.userinfo,
                    kwd=kwd)

    def check_priv(self, userinfo, cat_id):
        cat_rec = self.mcat.get_by_uid(cat_id)
        role_mask_idx = cat_rec.role_mask.index('1')
        priv_dic = {
            'ADD': False,
            'EDIT': False,
            'DELETE': False,
            'ADMIN': False
        }
        if userinfo.role[role_mask_idx] >= '1':
            priv_dic['ADD'] = True
        if userinfo.role[role_mask_idx] >= '2':
            priv_dic['EDIT'] = True
        if userinfo.role[role_mask_idx] >= '4':
            priv_dic['DELETE'] = True
        if userinfo.role[role_mask_idx] >= '8':
            priv_dic['ADMIN'] = True
        return priv_dic

    @tornado.web.authenticated
    def to_add_app(self, uid):
        if self.mpost.get_by_uid(uid):
            # todo:
            # self.redirect('/{0}/edit/{1}'.format(self.app_url_name, uid))
            pass
        else:
            self.render('infor/app/add.html',
                        tag_infos=self.mcat.query_all(),
                        userinfo=self.userinfo,
                        kwd={
                            'uid': uid,
                        })

    @tornado.web.authenticated
    def to_del_app(self, uid):
        current_infor = self.mpost.get_by_uid(uid)
        if self.check_priv(self.userinfo,
                           current_infor.extinfo['def_cat_uid'])['DELETE']:
            pass
        else:
            return False

        if self.mpost.delete(uid):
            self.redirect('/list/{0}'.format(
                current_infor.extinfo['def_cat_uid']))
        else:
            self.redirect('/info/{0}'.format(uid))

    @tornado.web.authenticated
    def to_edit_app(self, infoid):

        rec_info = self.mpost.get_by_uid(infoid)

        if rec_info:
            pass
        else:
            self.render('html/404.html')
            return
        if 'def_cat_uid' in rec_info.extinfo:
            catid = rec_info.extinfo['def_cat_uid']
        else:
            catid = ''

        if len(catid) == 4:
            pass
        else:
            catid = ''

        kwd = {
            'def_cat_uid':
            catid,
            'parentname':
            self.mcat.get_by_id(catid[:2] + '00').name if catid != '' else '',
            'catname':
            self.mcat.get_by_id(catid).name if catid != '' else '',
            'parentlist':
            self.mcat.get_parent_list(),
            'userip':
            self.request.remote_ip
        }

        if cfg['site_type'] == 2:
            tmpl = 'autogen/edit/edit_{0}.html'.format(catid)
        else:
            tmpl = 'infor/app/edit.html'

        self.render(tmpl,
                    kwd=kwd,
                    calc_info=rec_info,
                    post_info=rec_info,
                    userinfo=self.userinfo,
                    app_info=rec_info,
                    unescape=tornado.escape.xhtml_unescape,
                    cat_enum=self.mcat.get_qian2(catid[:2],
                                                 kind=self.kind + '0'),
                    tag_infos=self.mcat.query_all(by_order=True,
                                                  kind=constant['cate_info']),
                    tag_infos2=self.mcat.query_all(by_order=True,
                                                   kind=constant['cate_info']),
                    app2tag_info=self.mpost2catalog.query_by_entity_uid(
                        infoid, kind=constant['cate_info']),
                    app2label_info=self.mpost2label.get_by_id(
                        infoid, kind=constant['tag_info']))

    def check_update_role(self, current_info, post_data):
        #  to check if current user could update the meta
        if current_info.user_name == self.userinfo.user_name:
            return True
        elif self.userinfo.role[2] >= '1':
            return True
        elif 'def_cat_uid' in post_data and self.check_priv(
                self.userinfo, post_data['def_cat_uid'])['EDIT']:
            return True
        else:
            return False

    def get_def_cat_uid(self, post_data):
        # 下面两种处理方式,上面是原有的,暂时保留以保持兼容
        ext_cat_uid = {}
        if 'def_cat_uid' in post_data:
            ext_cat_uid['def_cat_uid'] = post_data['def_cat_uid']
            ext_cat_uid['def_cat_pid'] = '{0}00'.format(
                post_data['def_cat_uid'][:2])
        if 'gcat0' in post_data:
            ext_cat_uid['def_cat_uid'] = post_data['gcat0']
            ext_cat_uid['def_cat_pid'] = '{0}00'.format(post_data['gcat0'][:2])
        print(ext_cat_uid)
        return ext_cat_uid

    @tornado.web.authenticated
    def update(self, uid):
        post_data = {}
        ext_dic = {}
        for key in self.request.arguments:
            if key.startswith('ext_') or key.startswith('tag_'):
                ext_dic[key] = self.get_argument(key)
            else:
                post_data[key] = self.get_arguments(key)[0]

        post_data['user_name'] = self.userinfo.user_name

        current_info = self.mpost.get_by_uid(uid)

        if self.check_update_role(current_info, post_data):
            pass
        else:
            print('No privilege.')
            return False

        if 'valid' in post_data:
            post_data['valid'] = int(post_data['valid'])
        else:
            post_data['valid'] = current_info.valid

        ext_dic['def_uid'] = str(uid)
        print(post_data)

        ext_dic = dict(ext_dic, **self.get_def_cat_uid(post_data))

        ext_dic['def_tag_arr'] = [
            x.strip() for x in post_data['tags'].strip().strip(',').split(',')
        ]
        ext_dic = self.extra_data(ext_dic, post_data)
        self.mpost_hist.insert_data(self.mpost.get_by_id(uid))

        self.mpost.modify_meta(uid, post_data, extinfo=ext_dic)
        self.update_catalog(uid)
        self.update_tag(uid)
        self.redirect('/info/{0}'.format(uid))

    @tornado.web.authenticated
    def add(self, uid='', sig=''):

        ext_dic = {}
        post_data = {}
        for key in self.request.arguments:
            if key.startswith('ext_') or key.startswith('tag_'):
                ext_dic[key] = self.get_argument(key)
            else:
                post_data[key] = self.get_arguments(key)[0]

        if self.check_priv(self.userinfo, post_data['def_cat_uid'])['ADD']:
            pass
        else:
            return False

        if uid == '':
            uid = sig + tools.get_uu4d()
            while self.mpost.get_by_uid(uid):
                uid = sig + tools.get_uu4d()
            post_data['uid'] = uid

        post_data['user_name'] = self.userinfo.user_name
        if 'valid' in post_data:
            post_data['valid'] = int(post_data['valid'])
        else:
            post_data['valid'] = 1

        ext_dic['def_uid'] = str(uid)

        ext_dic = dict(ext_dic, **self.get_def_cat_uid(post_data))

        ext_dic['def_tag_arr'] = [
            x.strip() for x in post_data['tags'].strip().strip(',').split(',')
        ]
        ext_dic = self.extra_data(ext_dic, post_data)

        self.mpost.modify_meta(ext_dic['def_uid'], post_data, extinfo=ext_dic)
        self.update_catalog(ext_dic['def_uid'])
        self.update_tag(ext_dic['def_uid'])

        # self.redirect('/list/{0}'.format(ext_dic['def_cat_uid']))
        self.redirect('/info/{0}'.format(uid))

    @tornado.web.authenticated
    def extra_data(self, ext_dic, post_data):
        '''
        The additional information.
        :param post_data:
        :return: directory.
        '''
        return ext_dic

    @tornado.web.authenticated
    def add_comment(self, id_post):
        post_data = self.get_post_data()
        post_data['user_id'] = self.userinfo.uid
        post_data['user_name'] = self.userinfo.user_name
        comment_uid = self.mpost2reply.insert_data(post_data, id_post)
        if comment_uid:
            output = {
                'pinglun': comment_uid,
            }
        else:
            output = {
                'pinglun': 0,
            }
        return json.dump(output, self)

    def add_relation(self, f_uid, t_uid):
        if False == self.mpost.get_by_uid(t_uid):
            return False
        if f_uid == t_uid:
            '''
            关联其本身
            '''
            return False
        self.mrel.add_relation(f_uid, t_uid, 2)
        self.mrel.add_relation(t_uid, f_uid, 1)
        return True
예제 #21
0
class AdminPostHandler(PostHandler):
    def initialize(self, hinfo=''):
        self.init()
        self.mevaluation = MEvaluation()
        self.mpost2label = MInfor2Label()
        self.mpost2catalog = MInfor2Catalog()
        self.mpost = MInfor()
        self.musage = MUsage()
        self.mcat = MCategory()
        self.mrel = MInforRel()
        self.mreply = MReply()
        self.mpost_hist = MInfoHist()

    def get(self, url_str=''):
        if self.userinfo and self.userinfo.role[2] >= '3':
            pass
        else:
            return False
        url_arr = self.parse_url(url_str)

        if len(url_arr) == 2:
            if url_arr[0] in ['_edit']:
                self.to_edit(url_arr[1])
        else:
            return False

    def post(self, url_str=''):
        if self.userinfo and self.userinfo.role[2] >= '3':
            pass
        else:
            return False

        url_arr = self.parse_url(url_str)

        if len(url_arr) == 2:
            if url_arr[0] in ['_edit']:
                self.update(url_arr[1])
        else:
            return False

    @tornado.web.authenticated
    def to_edit(self, post_uid):
        postinfo = self.mpost.get_by_uid(post_uid, )
        json_cnt = json.dumps(postinfo.extinfo, indent=True)
        self.render(
            'man_post/admin_post.html',
            postinfo=postinfo,
            sig_dic=router_post,
            userinfo=self.userinfo,
            unescape=tornado.escape.xhtml_unescape,
            json_cnt=json_cnt,
        )

    @tornado.web.authenticated
    def update(self, post_uid):
        post_data = self.get_post_data()

        logger.info('admin post update: {0}'.format(post_data))

        ext_dic = {}
        ext_dic['def_uid'] = post_uid
        ext_dic['def_cat_uid'] = post_data['gcat0']
        ext_dic['def_cat_pid'] = self.mcat.get_by_uid(post_data['gcat0']).pid

        self.mpost.update_kind(post_uid, post_data['kcat'])
        self.mpost.update_jsonb(post_uid, ext_dic)
        self.update_category(post_uid)

        self.redirect('/{0}/{1}'.format(router_post[post_data['kcat']],
                                        post_uid))
예제 #22
0
class TestApp():
    def setup(self):
        print('setup 方法执行于本类中每条用例之前')
        self.uu = MInfor()

        self.title = '哈哈sdfsdf'
        self.uid = 'g' + tools.get_uu4d()

    def test_insert(self):
        uid = self.uid
        post_data = {
            'title': self.title,
            'keywords': 'sd,as',
            'cnt_md': '## adslkfjasdf\n lasdfkjsadf',
            'logo': '/static/',
            'user_name': 'ss',
            'extinfo': '',
            'valid': 1,
        }
        extinfo = {}

        self.uu.add_meta(uid, post_data, extinfo)
        tt = self.uu.get_by_uid(uid)
        assert tt.uid == uid

    def test_insert2(self):
        uid = self.uid
        post_data = {
            'title': '',
            'keywords': 'sd,as',
            'cnt_md': '## adslkfjasdf\n lasdfkjsadf',
            'logo': '/static/',
            'user_name': 'ss',
            'extinfo': ''
        }
        extinfo = {}

        self.uu.add_meta(uid, post_data, extinfo)
        tt = self.uu.get_by_uid(uid)
        assert tt == False

        post_data = {
            'title': '1',
            'keywords': 'sd,as',
            'cnt_md': '## adslkfjasdf\n lasdfkjsadf',
            'logo': '/static/',
            'user_name': 'ss',
            'extinfo': ''
        }
        uu = self.uu.add_meta(self.uid, post_data)
        assert uu == False

        post_data = {
            'title': '天',
            'keywords': 'sd,as',
            'cnt_md': '## adslkfjasdf\n lasdfkjsadf',
            'logo': '/static/',
            'user_name': 'ss',
            'extinfo': ''
        }
        uu = self.uu.add_meta(self.uid, post_data)
        assert uu == False

    def test_upate(self):
        assert True

    def tearDown(self):
        print("function teardown")
        tt = self.uu.get_by_uid(self.uid)
        if tt:
            self.uu.delete(tt.uid)
예제 #23
0
class UserListHandler(BaseHandler):
    def initialize(self):
        self.init()
        self.mequa = MInfor()
        self.musage = MUsage()

    def get(self, url_str=''):
        if len(url_str) > 0:
            url_arr = url_str.split('/')
        if url_str == 'recent':
            self.to_find(url_str)
        if url_str == 'app':
            self.list_app()
        elif url_str == 'user_recent':
            self.user_recent()
        elif url_str == 'user_most':
            self.user_most()

    def list_app(self):
        kwd = {
            'pager': '',
            'title': '最近使用的运算应用',
        }
        self.render(
            'user/info_list/list_app.html',
            kwd=kwd,
            userinfo=self.userinfo,
        )

    @tornado.web.authenticated
    def user_most(self):
        kwd = {
            'pager': '',
            'title': '我使用最多的云算应用',
        }
        self.render(
            'user/info_list/user_most.html'.format(input),
            kwd=kwd,
            user_name=self.get_current_user(),
            userinfo=self.userinfo,
        )

    @tornado.web.authenticated
    def user_recent(self):
        kwd = {'pager': '', 'title': '我最近使用的云算应用'}
        self.render(
            'user/info_list/user_recent.html'.format(input),
            kwd=kwd,
            user_name=self.get_current_user(),
            userinfo=self.userinfo,
        )

    def post(self, input=''):
        if len(input) > 0:
            ip_arr = input.split(r'/')
        if input == 'find':
            self.find()

    def to_find(self, input):
        kwd = {
            'pager': '',
        }
        self.render('user/info_list/most.html'.format(input),
                    topmenu='',
                    userinfo=self.userinfo,
                    kwd=kwd)

    def list_recent(self):
        recs = self.mequa.query_recent(20)
        kwd = {
            'pager': '',
            'title': '最近使用的云算应用',
        }
        self.render(
            'user/info_list/list.html'.format(input),
            kwd=kwd,
            rand_eqs=self.get_random(),
            recs=recs,
            userinfo=self.userinfo,
        )

    def find(self):
        keyword = self.get_argument('keyword').strip()

        kwd = {
            'pager': '',
            'title': '查找结果',
        }
        self.render('user/info_list/find_list.html'.format(input),
                    userinfo=self.userinfo,
                    kwd=kwd,
                    recs=self.mequa.get_by_keyword(keyword))

    def get_random(self):
        return self.mequa.query_random()
예제 #24
0
class InfoTagHandler(BaseHandler):
    def initialize(self, hinfo=''):
        self.init()
        self.template_dir_name = 'infor'
        self.minfo = MInfor()
        self.mcat = MCategory()

    def get(self, url_str=''):
        print('tag:', url_str)
        url_arr = self.parse_url(url_str)

        if len(url_arr) == 1:
            self.list(url_str)
        elif len(url_arr) == 2:
            if url_arr[0] == 'remove':
                self.remove_redis_keyword(url_arr[1])
            else:
                self.list(url_arr[0], url_arr[1])

    @tornado.web.authenticated
    def remove_redis_keyword(self, kw):
        redisvr.srem(config.redis_kw + self.userinfo.user_name, kw)
        return json.dump({}, self)

    def list(self, tag_slug, cur_p=''):
        # 下面用来使用关键字过滤信息,如果网站信息量不是很大不要开启
        # Todo:
        # if self.get_current_user():
        #     redisvr.sadd(config.redis_kw + self.userinfo.user_name, tag_slug)

        if cur_p == '':
            current_page_num = 1
        else:
            current_page_num = int(cur_p)

        tag_name = 'fd'
        kwd = {
            'tag_name': tag_name,
            'tag_slug': tag_slug,
            'title': tag_name,
            'current_page': current_page_num
        }

        info = self.minfo.query_by_tagname(tag_slug)

        page_num = int(info.count() / config.page_num) + 1

        print('tag tmpl:',
              '{0}/label/list.html'.format(self.template_dir_name))

        self.render(
            '{0}/label/list.html'.format(self.template_dir_name),
            kwd=kwd,
            userinfo=self.userinfo,
            infos=self.minfo.query_pager_by_tag(tag_slug, current_page_num),
            pager=self.gen_pager(tag_slug, page_num, current_page_num),
        )

    def gen_pager(self, cat_slug, page_num, current):
        '''
        cat_slug 分类
        page_num 页面总数
        current 当前页面
        '''

        if page_num == 1:
            return ''

        pager_shouye = '''
        <li class="{0}">
        <a  href="/info_tag/{1}">&lt;&lt; 首页</a>
                    </li>'''.format('' if current <= 1 else '', cat_slug)

        pager_pre = '''
                    <li class=" previous {0}">
                    <a  href="/info_tag/{1}/{2}">&lt; 前页</a>
                    </li>
                    '''.format('' if current <= 1 else '', cat_slug,
                               current - 1)
        pager_mid = ''
        for ind in range(0, page_num):
            tmp_mid = '''
                    <li class=" page {0}">
                    <a  href="/info_tag/{1}/{2}">{2}</a></li>
                    '''.format('active' if ind + 1 == current else '',
                               cat_slug, ind + 1)
            pager_mid += tmp_mid
        pager_next = '''
                    <li class=" next {0}">
                    <a  href="/info_tag/{1}/{2}">后页 &gt;</a>
                    </li>
                    '''.format('' if current >= page_num else '', cat_slug,
                               current + 1)
        pager_last = '''
                    <li class=" last {0}">
                    <a href="/info_tag/{1}/{2}">末页
                        &gt;&gt;</a>
                    </li>
                    '''.format('' if current >= page_num else '', cat_slug,
                               page_num)
        pager = pager_shouye + pager_pre + pager_mid + pager_next + pager_last
        return (pager)
예제 #25
0
 def initialize(self):
     self.init()
     self.mequa = MInfor()
     self.musage = MUsage()
     self.mrel = MInforRel()
     self.mcollect = MEvaluation()
예제 #26
0
 def initialize(self):
     self.init()
     self.mequa = MInfor()
     self.musage = MUsage()
예제 #27
0
class InfoHandler(BaseHandler):
    def initialize(self, hinfo=''):
        self.init()
        self.mevaluation = MEvaluation()
        self.mapp2catalog = MInfor2Catalog()
        self.mapp2tag = MInfor2Label()
        self.minfo = MInfor()
        self.musage = MUsage()
        self.mcat = MCategory()
        self.mrel = MInforRel()
        # self.mreply = MInfor2Reply()
        self.kind = '2'

    def get(self, url_str=''):
        url_arr = self.parse_url(url_str)
        if len(url_arr) == 1 and len(url_str) == 4:
            self.view_info(url_str)
        else:
            kwd = {
                'title': '',
                'info': '',
            }
            self.set_status(404)
            self.render(
                'html/404.html',
                kwd=kwd,
                userinfo=self.userinfo,
            )

    def post(self, url_str=''):
        url_arr = self.parse_url(url_str)
        if url_arr[0] == 'rel':
            if self.get_current_user():
                self.add_relation(url_arr[1], url_arr[2])
            else:
                self.redirect('/user/login')
        elif url_arr[0] == 'comment_add':
            self.add_comment(url_arr[1])
        else:
            return False

    @tornado.web.authenticated
    def add_comment(self, id_post):
        post_data = {}
        for key in self.request.arguments:
            post_data[key] = self.get_arguments(key)
        post_data['user_id'] = self.userinfo.uid
        post_data['user_name'] = self.userinfo.user_name
        comment_uid = self.mreply.insert_data(post_data, id_post)
        if comment_uid:
            output = {
                'pinglun': comment_uid,
            }
        else:
            output = {
                'pinglun': 0,
            }
        return json.dump(output, self)

    def view_info(self, info_id):
        '''
        Render the info
        :param info_id:
        :return: Nonthing.
        '''
        app_rec = self.minfo.get_by_uid(info_id)

        if app_rec:
            pass
        else:
            kwd = {
                'info': '您要找的信息不存在。',
            }
            self.render(
                'html/404.html',
                kwd=kwd,
                userinfo=self.userinfo,
            )
            return False
        #
        cats = self.mapp2catalog.query_by_entity_uid(info_id, kind='20')
        cat_uid_arr = []
        for cat_rec in cats:
            cat_uid = cat_rec.tag.uid
            cat_uid_arr.append(cat_uid)
        print('info category:', cat_uid_arr)
        replys = []  # self.mreply.get_by_id(info_id)
        rel_recs = self.mrel.get_app_relations(app_rec.uid, 0, kind='2')
        if len(cat_uid_arr) > 0:
            rand_recs = self.minfo.query_cat_random(cat_uid_arr[0],
                                                    4 - rel_recs.count() + 4)
        else:
            rand_recs = self.minfo.query_random(4 - rel_recs.count() + 4)

        self.chuli_cookie_relation(info_id)
        cookie_str = tools.get_uuid()

        if 'def_cat_uid' in app_rec.extinfo:
            ext_catid = app_rec.extinfo['def_cat_uid']
        else:
            ext_catid = ''

        if len(ext_catid) == 4:
            pass
        else:
            ext_catid = ''
        parent_name = self.mcat.get_by_id(ext_catid[:2] +
                                          '00').name if ext_catid != '' else ''
        if ext_catid != '':
            cat_rec = self.mcat.get_by_uid(ext_catid)
            role_mask_idx = cat_rec.role_mask.index('1')
            cat_name = cat_rec.name
        else:
            role_mask_idx = 0
            cat_name = ''

        parentname = '<a href="/list/{0}">{1}</a>'.format(
            ext_catid[:2] + '00', parent_name)

        catname = '<a href="/list/{0}">{1}</a>'.format(ext_catid, cat_name)

        kwd = {
            'pager': '',
            'url': self.request.uri,
            'cookie_str': cookie_str,
            'daohangstr': '',
            'signature': info_id,
            'tdesc': '',
            'eval_0': self.mevaluation.app_evaluation_count(info_id, 0),
            'eval_1': self.mevaluation.app_evaluation_count(info_id, 1),
            'site_url': config.site_url,
            'login': 1 if self.get_current_user() else 0,
            'has_image': 0,
            'parentlist': self.mcat.get_parent_list(),
            'parentname': parentname,
            'catname': catname,
        }
        self.minfo.view_count_increase(info_id)
        if self.get_current_user():
            self.musage.add_or_update(self.userinfo.uid, info_id)
        self.set_cookie('user_pass', cookie_str)
        tmpl = self.ext_tmpl_name(app_rec) if self.ext_tmpl_name(
            app_rec) else self.get_tmpl_name(app_rec)
        print('info tmpl: ' + tmpl)
        ext_catid2 = app_rec.extinfo[
            'def_cat_uid'] if 'def_cat_uid' in app_rec.extinfo else None

        self.render(
            tmpl,
            kwd=dict(kwd, **self.extra_kwd(app_rec)),
            calc_info=app_rec,  # Deprecated
            post_info=app_rec,  # Deprecated
            postinfo=app_rec,
            userinfo=self.userinfo,
            relations=rel_recs,
            rand_recs=rand_recs,
            unescape=tornado.escape.xhtml_unescape,
            ad_switch=random.randint(1, 18),
            tag_info=self.mapp2tag.get_by_id(info_id,
                                             kind=tools.constant['tag_info']),
            recent_apps=self.musage.query_recent(self.get_current_user(),
                                                 6)[1:],
            replys=[],  # replys,
            cat_enum=self.mcat.get_qian2(ext_catid2[:2],
                                         kind=tools.constant['cate_info'])
            if ext_catid else [],
            role_mask_idx=role_mask_idx,
        )

    def extra_kwd(self, info_rec):
        '''
        The additional information.
        :param info_rec:
        :return: directory.
        '''
        return {}

    def chuli_cookie_relation(self, app_id):
        '''
        The current Info and the Info viewed last should have some relation.
        And the last viewed Info could be found from cookie.
        :param app_id: the current app
        :return: None
        '''
        last_app_uid = self.get_secure_cookie('use_app_uid')
        if last_app_uid:
            last_app_uid = last_app_uid.decode('utf-8')
        self.set_secure_cookie('use_app_uid', app_id)
        if last_app_uid and self.minfo.get_by_uid(last_app_uid):
            self.add_relation(last_app_uid, app_id)

    def ext_tmpl_name(self, rec):
        return None

    def get_tmpl_name(self, rec):
        '''
        According to the application, each info of it's classification could has different temaplate.
        :param rec: the App record.
        :return: the temaplte path.
        '''
        if 'def_cat_uid' in rec.extinfo and rec.extinfo['def_cat_uid'] != '':
            cat_id = rec.extinfo['def_cat_uid']
        else:
            cat_id = False
        if cat_id:
            tmpl = 'autogen/view/view_{0}.html'.format(cat_id)
        else:
            tmpl = 'infor/app/show_map.html'
        return tmpl

    def add_relation(self, f_uid, t_uid):
        '''
        Add the relation. And the from and to, should have different weight.
        :param f_uid:
        :param t_uid:
        :return: return True if the relation has been succesfully added.
        '''
        if self.minfo.get_by_uid(t_uid):
            pass
        else:
            return False
        if f_uid == t_uid:
            return False

        # 针对分类进行处理。只有落入相同分类的,才加1
        f_cats = self.mapp2catalog.query_by_entity_uid(f_uid)
        t_cats = self.mapp2catalog.query_by_entity_uid(t_uid)
        flag = False

        for f_cat in f_cats:
            print(f_cat.tag)
            for t_cat in t_cats:
                print(t_cat.tag)
                if f_cat.tag == t_cat.tag:
                    flag = True
        if flag:
            pass
        else:
            return False

        self.mrel.add_relation(f_uid, t_uid, 2)
        self.mrel.add_relation(t_uid, f_uid, 1)
        return True
예제 #28
0
    def setup(self):
        print('setup 方法执行于本类中每条用例之前')
        self.uu = MInfor()

        self.title = '哈哈sdfsdf'
        self.uid = 'g' + tools.get_uu4d()
예제 #29
0
 def initialize(self):
     self.init()
     self.mapp = MInfor()
     self.mpost = MPost()
     self.rel_post2app = MRelPost2Infor()
     self.rel_app2post = MRelInfor2Post()