Пример #1
0
 def post(self, secret=""):
     cats = (self.get_argument("cats", ""),)
     if cats and secret:
         if secret == getAttr("MOVE_SECRET"):
             Category.set_cats(encode_special_txt(cats[0]))
             return self.write("1")
     return self.write("0")
Пример #2
0
 def post(self, secret=''):
     cats = self.get_argument("cats", ''),
     if cats and secret:
         if secret == getAttr('MOVE_SECRET'):
             Category.set_cats(encode_special_txt(cats[0]))
             return self.write('1')
     return self.write('0')
Пример #3
0
def getCategory(current_category_key):
    current_category = None
    lineage = []
    
    try:
        current_category = Category.get(db.Key(current_category_key))
        lineage = [Category.get(key) for key in current_category.lineage]
    except db.BadKeyError:
        pass
    except AttributeError:
        pass
    
    #todo - massive oppurtunity for optimization
    retval = current_category.key().__str__() + ',' + current_category.name + ';'
    
    for category in lineage:
        retval += category.key().__str__() + ',' + category.name + ','
    retval += ';'
    
    for category in Category.children(current_category):
        retval += category.key().__str__() + ',' + category.name + ','
    
    print 'Content-Type: text/plain;charset=UTF-8'
    print ''
    print retval
Пример #4
0
    def get(self, id=''):
        #try:
        if id:
            oldobj = Article.get_article_by_id_edit(id)
            print 'DelPost()', oldobj
            if not oldobj:
                return
            if MYSQL_TO_KVDB_SUPPORT:
                oldobj_category = oldobj['category']
                oldobj_archive = oldobj['archive']
                oldobj_tags = oldobj['tags']
            else:
                oldobj_category = oldobj.category
                oldobj_archive = oldobj.archive
                oldobj_tags = oldobj.tags

            Category.remove_postid_from_cat(oldobj_category, str(id))
            Archive.remove_postid_from_archive(oldobj_archive, str(id))
            Tag.remove_postid_from_tags(set(oldobj_tags.split(',')), str(id))
            Article.del_post_by_id(id)
            increment('Totalblog', NUM_SHARDS, -1)
            cache_key_list = [
                '/',
                'post:%s' % id,
                'cat:%s' % quoted_string(oldobj_category)
            ]
            clear_cache_by_pathlist(cache_key_list)
            clear_cache_by_pathlist(['post:%s' % id])
            self.redirect('%s/admin/edit_post/' % (BASE_URL))
Пример #5
0
def category_add():
    if request.method == 'POST':

        new_category = Category(name=request.form['name'],
                                description=request.form['description'],
                                user_id=login_session['user_id'])

        picture = request.files['category-pic']

        if picture and allowed_file(picture.filename):
            filename = secure_filename(picture.filename)
            extension = os.path.splitext(filename)[1]
            unique_filename = str(uuid.uuid4()) + str(extension)
            picture.save(
                os.path.join(app.config['UPLOAD_FOLDER'], unique_filename))
            new_category.picture = unique_filename

        session.add(new_category)
        session.commit()

        return redirect(url_for('category_view'))

    else:
        categories = session.query(Category).all()
        return render_template('add_category.html', categories=categories)
Пример #6
0
    def get(self, name=''):
        objs = Category.get_cat_page_posts(name, 1)

        catobj = Category.get_cat_by_name(name)
        if catobj:
            pass
        else:
            self.redirect(BASE_URL)
            return

        allpost = catobj.id_num
        allpage = allpost / EACH_PAGE_POST_NUM
        if allpost % EACH_PAGE_POST_NUM:
            allpage += 1

        output = self.render('index.html', {
            'title': "%s - %s" % (catobj.name, SITE_TITLE),
            'keywords': catobj.name,
            'description': SITE_DECR,
            'objs': objs,
            'cats': Category.get_all_cat_name(),
            'tags': Tag.get_hot_tag_name(),
            'page': 1,
            'allpage': allpage,
            'listtype': 'cat',
            'name': name,
            'namemd5': md5(name.encode('utf-8')).hexdigest(),
            'comments': Comment.get_recent_comments(),
            'links': Link.get_all_links(),
        },
                             layout='_layout.html')
        self.write(output)
        return output
Пример #7
0
 def get(self, name = ''):
     objs = Category.get_cat_page_posts(name, 1)
     
     catobj = Category.get_cat_by_name(name)
     if catobj:
         pass
     else:
         self.redirect(BASE_URL)
         return
     
     allpost =  catobj.id_num
     allpage = allpost/EACH_PAGE_POST_NUM
     if allpost%EACH_PAGE_POST_NUM:
         allpage += 1
         
     output = self.render('index.html', {
         'title': "%s - %s"%( catobj.name, SITE_TITLE),
         'keywords':catobj.name,
         'description':SITE_DECR,
         'objs': objs,
         'cats': Category.get_all_cat_name(),
         'tags': Tag.get_hot_tag_name(),
         'page': 1,
         'allpage': allpage,
         'listtype': 'cat',
         'name': name,
         'namemd5': md5(name.encode('utf-8')).hexdigest(),
         'comments': Comment.get_recent_comments(),
         'links':Link.get_all_links(),
     },layout='_layout.html')
     self.write(output)
     return output
Пример #8
0
    def get(self, id=""):
        # try:
        if id:
            oldobj = Article.get_article_by_id_edit(id)
            print "DelPost()", oldobj
            if not oldobj:
                return
            if MYSQL_TO_KVDB_SUPPORT:
                oldobj_category = oldobj["category"]
                oldobj_archive = oldobj["archive"]
                oldobj_tags = oldobj["tags"]
            else:
                oldobj_category = oldobj.category
                oldobj_archive = oldobj.archive
                oldobj_tags = oldobj.tags

            Category.remove_postid_from_cat(oldobj_category, str(id))
            Archive.remove_postid_from_archive(oldobj_archive, str(id))
            Tag.remove_postid_from_tags(set(oldobj_tags.split(",")), str(id))
            Article.del_post_by_id(id)
            increment("Totalblog", NUM_SHARDS, -1)
            cache_key_list = ["/", "post:%s" % id, "cat:%s" % quoted_string(oldobj_category)]
            clear_cache_by_pathlist(cache_key_list)
            clear_cache_by_pathlist(["post:%s" % id])
            self.redirect("%s/admin/edit_post/" % (BASE_URL))
Пример #9
0
    def post(self):
        self.set_header('Content-Type','application/json')
        rspd = {'status': 201, 'msg':'ok'}

        try:
            tf = {'true':1,'false':0}
            timestamp = int(time())
            post_dic = {
                'category': self.get_argument("cat"),
                'title': self.get_argument("tit"),
                'content': self.get_argument("con"),
                'tags': self.get_argument("tag",'').replace(u',',','),
                'closecomment': self.get_argument("clo",'0'),
                'password': self.get_argument("password",''),
                'add_time': timestamp,
                'edit_time': timestamp,
                'archive': genArchive(),
            }
            if post_dic['tags']:
                tagslist = set([x.strip() for x in post_dic['tags'].split(',')])
                try:
                    tagslist.remove('')
                except:
                    pass
                if tagslist:
                    post_dic['tags'] = ','.join(tagslist)
            post_dic['closecomment'] = tf[post_dic['closecomment'].lower()]
        except:
            rspd['status'] = 500
            rspd['msg'] = '错误: 注意必填的三项'
            self.write(json.dumps(rspd))
            return

        postid = Article.add_new_article(post_dic)
        if postid:
            keyname = 'pv_%s' % (str(postid))
            set_count(keyname,0,0)
            
            Category.add_postid_to_cat(post_dic['category'], str(postid))
            Archive.add_postid_to_archive(genArchive(), str(postid))
            increment('Totalblog')
            if post_dic['tags']:
                Tag.add_postid_to_tags(post_dic['tags'].split(','), str(postid))

            rspd['status'] = 200
            rspd['msg'] = '完成: 你已经成功添加了一篇文章 <a href="/t/%s" target="_blank">查看</a>' % str(postid)
            clear_cache_by_pathlist(['/', 'cat:%s' % quoted_string(post_dic['category'])])

            if not debug:
                add_task('default', '/task/pingrpctask')

            self.write(json.dumps(rspd))
            return
        else:
            rspd['status'] = 500
            rspd['msg'] = '错误: 未知错误,请尝试重新提交'
            self.write(json.dumps(rspd))
            return
Пример #10
0
def api_article_edit(*, request, id, title):
    r = web.Response()
    cate = Category(id = id, title = title, create_time = currentTime(), is_delete = 0)
    result = yield from cate.update()
    if result is not None:
        result = APIResult(1, '', '修改成功')
    else:
        result = APIResult(0, '', '修改失败')
    return jsonResult(r, result)
Пример #11
0
    def post(self):
        self.set_header('Content-Type', 'application/json')
        rspd = {'status': 201, 'msg': 'ok'}

        try:
            tf = {'true': 1, 'false': 0}
            timestamp = int(time())
            post_dic = {
                'category': self.get_argument("cat"),
                'title': self.get_argument("tit"),
                'content': self.get_argument("con"),
                'tags': self.get_argument("tag", '').replace(u',', ','),
                'closecomment': self.get_argument("clo", '0'),
                'password': self.get_argument("password", ''),
                'add_time': timestamp,
                'edit_time': timestamp,
            }
            if post_dic['tags']:
                tagslist = set(
                    [x.strip() for x in post_dic['tags'].split(',')])
                try:
                    tagslist.remove('')
                except:
                    pass
                if tagslist:
                    post_dic['tags'] = ','.join(tagslist)
            post_dic['closecomment'] = tf[post_dic['closecomment'].lower()]
        except:
            rspd['status'] = 500
            rspd['msg'] = '错误: 注意必填的三项'
            self.write(json.dumps(rspd))
            return

        postid = Article.add_new_article(post_dic)
        if postid:
            Category.add_postid_to_cat(post_dic['category'], str(postid))
            if post_dic['tags']:
                Tag.add_postid_to_tags(post_dic['tags'].split(','),
                                       str(postid))

            rspd['status'] = 200
            rspd[
                'msg'] = '完成: 你已经成功添加了一篇文章 <a href="/t/%s" target="_blank">查看</a>' % str(
                    postid)
            clear_cache_by_pathlist(
                ['/', 'cat:%s' % quoted_string(post_dic['category'])])

            if not debug:
                add_task('default', '/task/pingrpctask')

            self.write(json.dumps(rspd))
            return
        else:
            rspd['status'] = 500
            rspd['msg'] = '错误: 未知错误,请尝试重新提交'
            self.write(json.dumps(rspd))
            return
Пример #12
0
def api_category_delete(*, request, category_id):
    r = web.Response()
    category = Category(id=category_id)
    category_result = yield from category.delete()
    if int(category_id) > 0 and int(category_result) > 0:
        result = APIResult(1, '', '删除成功')
    else:
        result = APIResult(0, '', '删除失败')
    return jsonResult(r, result)
Пример #13
0
def _create_structure():
    category = Category('test category', 'category test', 'test_category')
    category.meta = {'id': 1, 'webtranslateit_ids': {'content': 1}}
    section = Section(category, 'test section', 'section test', 'test_section')
    section.meta = {'id': 2, 'webtranslateit_ids': {'content': 2}}
    category.sections.append(section)
    article = Article(section, 'test article', 'article body', 'test_article')
    article.meta = {'id': 3, 'webtranslateit_ids': {'content': 3, 'body': 4}}
    section.articles.append(article)
    return category, section, article
Пример #14
0
 def create_category(category_name):
     """ Create a category in datastore """
     query = Category.all()
     query.filter("description =", category_name)
     ret = query.get()
     if ret is None:
         ret = Category()
         ret.description = category_name
         ret.put()
     return ret
Пример #15
0
def load_categories():
    """Load categories infomation."""

    clothing = Category(cg_name='clothing')
    shoes = Category(cg_name='shoes')

    db.session.add(clothing)
    db.session.add(shoes)

    db.session.commit()
Пример #16
0
def createall():
    "Creates database tables"
    db.create_all()
    from model import Category
    for i in range(len(CATALOG)):
        item = Category()
        item.id = i + 1  # item.id 不能为0,所以必须从1 开始
        item.category_name = CATALOG[i]
        db.session.add(item)
    db.session.commit()
Пример #17
0
def createall():
    "Creates database tables"
    db.create_all()
    "add Category"
    lists=[u'PYTHON',u'编程珠玑',u'数据库',u'操作系统',u"杂项"]
    from model import Category
    for i in range(1, 6):
        item = Category()
        item.id = i
        item.category_name = lists[i-1]
        db.session.add(item)
    db.session.commit()
Пример #18
0
def get_categories_list_json(load_all=False):
    """Return JSON list of all categories in database."""

    if not load_all:
        load_all = request.args.get('loadAll')

    if load_all:
        categories = Category.load_with_projects_media()
    else:
        categories = Category.load_with_projects()

    return jsonify_list(Category.get_json_from_list(categories, True))
Пример #19
0
def createall():
    "Creates database tables"
    db.create_all()
    "add Category"
    lists = [u'PYTHON', u'编程珠玑', u'数据库', u'操作系统', u"杂项"]
    from model import Category
    for i in range(1, 7):
        item = Category()
        item.id = i
        item.category_name = lists[i - 1]
        db.session.add(item)
    db.session.commit()
Пример #20
0
    def post(self):
        self.set_header("Content-Type", "application/json")
        rspd = {"status": 201, "msg": "ok"}

        try:
            tf = {"true": 1, "false": 0}
            timestamp = int(time())
            post_dic = {
                "category": self.get_argument("cat"),
                "title": self.get_argument("tit"),
                "content": self.get_argument("con"),
                "tags": self.get_argument("tag", "").replace(u",", ","),
                "closecomment": self.get_argument("clo", "0"),
                "password": self.get_argument("password", ""),
                "add_time": timestamp,
                "edit_time": timestamp,
            }
            if post_dic["tags"]:
                tagslist = set([x.strip() for x in post_dic["tags"].split(",")])
                try:
                    tagslist.remove("")
                except:
                    pass
                if tagslist:
                    post_dic["tags"] = ",".join(tagslist)
            post_dic["closecomment"] = tf[post_dic["closecomment"].lower()]
        except:
            rspd["status"] = 500
            rspd["msg"] = "错误: 注意必填的三项"
            self.write(json.dumps(rspd))
            return

        postid = Article.add_new_article(post_dic)
        if postid:
            Category.add_postid_to_cat(post_dic["category"], str(postid))
            if post_dic["tags"]:
                Tag.add_postid_to_tags(post_dic["tags"].split(","), str(postid))

            rspd["status"] = 200
            rspd["msg"] = '完成: 你已经成功添加了一篇文章 <a href="/t/%s" target="_blank">查看</a>' % str(postid)
            clear_cache_by_pathlist(["/", "cat:%s" % quoted_string(post_dic["category"])])

            if not debug:
                add_task("default", "/task/pingrpctask")

            self.write(json.dumps(rspd))
            return
        else:
            rspd["status"] = 500
            rspd["msg"] = "错误: 未知错误,请尝试重新提交"
            self.write(json.dumps(rspd))
            return
Пример #21
0
    def test_encoder(self):
        p = Project('test')
        p.id = 1
        c = Category('test')
        c.id = 2
        c.project_id = p.id
        t = Task('test')
        t.id = 3
        t.category_id = c.id

        self.assertIsNotNone(json.dumps(p, cls=ModelEncoder))
        self.assertIsNotNone(json.dumps(c, cls=ModelEncoder))
        self.assertIsNotNone(json.dumps(t, cls=ModelEncoder))
Пример #22
0
    def post(self):
        args = create_parse.parse_args()

        entity = Category(name=args.get('name'),description=args.get('description'))

        try:
            db.session.add(entity)
            db.session.commit()
            return Resp(data=entity.to_json())
        except Exception as ex:
            db.session.rollback()

            return Resp(code=400,msg='insert failure')
Пример #23
0
def api_category_add(*, request, title):
    r = web.Response()
    category = yield from Category.findAll('title=?', [title])
    if len(category) > 0:
        result = APIResult(0, '', '该分类已存在')
    else:
        cate = Category(title = title)
        cate_id = yield  from cate.save()
        if cate_id > 0:
            result = APIResult(1, '', '分类添加成功')
        else:
            result = APIResult(0, '', '分类添加失败')
    return jsonResult(r, result)
Пример #24
0
    def post(self):
        caller = get_caller(request)
        if caller["role"] != "admin":
            return res("⛔️ Must be an admin to create a new category", "error"), 400

        req = parse(request)
        errors = CategorySchema().validate(req)
        if errors:
            return res("Errors in request", "alert", errors=errors), 400
        category = Category(name=req["name"])
        category.save()
        return res(
            "Category created successfully", "success", category=convert_query(category)
        )
Пример #25
0
 def post(self):
     pdict = self.request.POST
     action = pdict.get("action", "")
     
     if action == "new":
         try:
             Category.new(pdict.get("category.url", randstr()),
                          pdict.get("category.title"),
                          pdict.get("category.discription") )
             Category.refresh_total()
         except Rollback, ex:
             self.jsonout(ex)
         else:
             self.jsonout("ok")
Пример #26
0
 def get(self, id = ''):
     try:
         if id:
             oldobj = Article.get_article_by_id_edit(id)
             Category.remove_postid_from_cat(oldobj.category, str(id))
             Archive.remove_postid_from_archive(oldobj.archive, str(id))
             Tag.remove_postid_from_tags( set(oldobj.tags.split(','))  , str(id))
             Article.del_post_by_id(id)
             increment('Totalblog',NUM_SHARDS,-1)
             cache_key_list = ['/', 'post:%s'% id, 'cat:%s' % quoted_string(oldobj.category)]
             clear_cache_by_pathlist(cache_key_list)
             clear_cache_by_pathlist(['post:%s'%id])
             self.redirect('%s/admin/edit_post/'% (BASE_URL))
     except:
         pass
Пример #27
0
def get_categories_json(load_all=False):
    """Return JSON object of all categories in database.

    If loadAll is present, greedily load all nested objects.
    """

    if not load_all:
        load_all = request.args.get('loadAll')

    if load_all:
        categories = Category.load_with_projects_media()
    else:
        categories = Category.load_with_projects()

    return jsonify_list(Category.get_json_from_list(categories))
Пример #28
0
def api_getCategory(*, request, page):
    r = web.Response()
    if (page is not None and len(page) > 0):
        num = yield from Category.findNumber('count(id)')
        p = Page(num, int(page))
        if num == 0:
            data = dict(page = class_to_dict(p), blogs = ())
        else:
            categorys = yield from Category.findAll(orderBy='create_time desc', limit=(p.offset, p.limit))
            data = dict(page=class_to_dict(p), blogs=categorys)
    else:
        categorys = yield from Category.findAll(orderBy='create_time desc')
        data = categorys
    result = APIResult(1, data)
    return jsonResult(r, result)
Пример #29
0
    def get(self, listtype='', direction='next', page='1', name=''):
        if listtype == 'cat':
            objs = Category.get_cat_page_posts(name, page)
            catobj = Category.get_cat_by_name(name)
        elif listtype == 'tag':
            objs = Tag.get_tag_page_posts(name, page)
            catobj = Tag.get_tag_by_name(name)
        elif listtype == 'archive':
            objs = Archive.get_archive_page_posts(name, page)
            catobj = Archive.get_archive_by_name(name)
        #
        if not catobj:
            return self.redirect(BASE_URL)

        if not objs:
            return self.redirect(BASE_URL)

        if MYSQL_TO_KVDB_SUPPORT:
            allpost = len(catobj.split(','))
        else:
            allpost = catobj.id_num
        allpage = allpost / EACH_PAGE_POST_NUM
        if allpost % EACH_PAGE_POST_NUM:
            allpage += 1

        output = self.render(
            'index.html', {
                'title': "%s - %s | Part %s" %
                (name, getAttr('SITE_TITLE'), page),
                'keywords': name,
                'description': getAttr('SITE_DECR'),
                'objs': objs,
                'cats': Category.get_all_cat_name(),
                'tags': Tag.get_hot_tag_name(),
                'archives': Archive.get_all_archive_name(),
                'page': int(page),
                'allpage': allpage,
                'listtype': listtype,
                'name': name,
                'namemd5': md5(name.encode('utf-8')).hexdigest(),
                'comments': Comment.get_recent_comments(),
                'links': Link.get_all_links(),
                'isauthor': self.isAuthor(),
                'Totalblog': get_count('Totalblog', NUM_SHARDS, 0),
            },
            layout='_layout.html')
        self.write(output)
        return output
Пример #30
0
    def get(self, sid):
        try:
            shop = Shop.get(id=sid)
        except:
            self.flash("此商品不存在")
            self.redirect("/admin/addshop")
            return

        try:
            category = Category.get(id=shop.cid)
        except:
            pass

        categoryattrs = CategoryAttr.select().where(
            CategoryAttr.cid == shop.cid)

        pics = [
            shoppic.path
            for shoppic in ShopPic.select().where(ShopPic.sid == sid)
        ]
        shop.args = simplejson.loads(shop.args)

        self.render('admin/editshop.html',
                    shop=shop,
                    pics=pics,
                    category=category,
                    categoryattrs=categoryattrs)
Пример #31
0
 def get(self, direction = 'next', page = '2', base_id = '1'):
     if page == '1':
         self.redirect(BASE_URL)
         return
     objs = Article.get_page_posts(direction, page, base_id)
     if objs:
         if direction == 'prev':
             objs.reverse()            
         fromid = objs[0].id
         endid = objs[-1].id
     else:
         fromid = endid = ''
     
     allpost =  Article.count_all_post()
     allpage = allpost/EACH_PAGE_POST_NUM
     if allpost%EACH_PAGE_POST_NUM:
         allpage += 1
     output = self.render('index.html', {
         'title': "%s - %s | Part %s"%(SITE_TITLE,SITE_SUB_TITLE, page),
         'keywords':KEYWORDS,
         'description':SITE_DECR,
         'objs': objs,
         'cats': Category.get_all_cat_name(),
         'tags': Tag.get_hot_tag_name(),
         'page': int(page),
         'allpage': allpage,
         'listtype': 'index',
         'fromid': fromid,
         'endid': endid,
         'comments': Comment.get_recent_comments(),
         'links':Link.get_all_links(),
     },layout='_layout.html')
     self.write(output)
     return output
Пример #32
0
    def post(self, caid):
        try:
            categoryattr = CategoryAttr.get(id=caid)
            category = Category.get(id=categoryattr.cid)
        except:
            self.flash("此分类属性不存在")
            self.redirect("/admin/categorys")
            return

        name = self.get_argument("name", None)
        dec = self.get_argument("dec", "")
        order = int(self.get_argument("order", 1))

        categoryattr.name = name
        categoryattr.dec = dec
        categoryattr.order = order

        try:
            categoryattr.validate()
            categoryattr.save()
            self.flash(u"分类属性%s修改成功" % name)
            self.redirect("/admin/categoryattrs/%d" % int(categoryattr.cid))
            return
        except Exception, ex:
            self.flash(str(ex))
Пример #33
0
    def get(self, name = ''):
        objs = Tag.get_tag_page_posts(name, 1)

        catobj = Tag.get_tag_by_name(name)
        if catobj:
            pass
        else:
            self.redirect(BASE_URL)
            return

        allpost =  catobj.id_num
        allpage = allpost/EACH_PAGE_POST_NUM
        if allpost%EACH_PAGE_POST_NUM:
            allpage += 1

        output = self.render('index.html', {
            'title': "%s - %s"%( catobj.name, getAttr('SITE_TITLE')),
            'keywords':catobj.name,
            'description':getAttr('SITE_DECR'),
            'objs': objs,
            'cats': Category.get_all_cat_name(),
            'tags': Tag.get_hot_tag_name(),
            'archives': Archive.get_all_archive_name(),
            'page': 1,
            'allpage': allpage,
            'listtype': 'tag',
            'name': name,
            'namemd5': md5(name.encode('utf-8')).hexdigest(),
            'comments': Comment.get_recent_comments(),
            'links':Link.get_all_links(),
            'isauthor':self.isAuthor(),
            'Totalblog':get_count('Totalblog',NUM_SHARDS,0),
        },layout='_layout.html')
        self.write(output)
        return output
Пример #34
0
def make_categories():
    """ Let's make some categories! """

    print 'Making Categories...'

    # Let's delete the table in case I want to redo this
    Category.query.delete()

    category_dict = {'opr': 'Operations',
                     'mar': 'Marketing',
                     'mds': 'Markdowns',
                     'vix': 'Visual Merchandising',
                     'pro': 'Promotions',
                     'evt': 'Events',
                     'hrp': 'Human Resources/Payroll',
                     'mis': 'Miscellaneous'}

    for category in category_dict:
        cat_id = category
        name = category_dict[category]

        category_obj = Category(cat_id=cat_id, name=name)

        db.session.add(category_obj)

    db.session.commit()
Пример #35
0
    def get(self, ename):

        try:
            shop = Shop.get(ename=ename)
            shop.views = shop.views + 1
            shop.save()
            category = Category.get(id=shop.cid)
        except:
            raise HTTPError(404)
            return

        categoryattrs = CategoryAttr.select().where(
            CategoryAttr.cid == shop.cid)
        shopattrs = ShopAttr.select().where(ShopAttr.sid == shop.id)
        if shop.args:
            shop.args = simplejson.loads(shop.args)
        pics = ShopPic.select().where(ShopPic.sid == shop.id)

        recomshops = Shop.select().where((Shop.status == 1)
                                         & (Shop.id != shop.id)).paginate(
                                             1, 5)
        self.render("shop/shop.html",
                    shop=shop,
                    category=category,
                    categoryattrs=categoryattrs,
                    shopattrs=shopattrs,
                    pics=pics,
                    recomshops=recomshops)
Пример #36
0
    def get(self):

        urls = []

        def addurl(loc, lastmod=None, changefreq=None, priority=None):
            url_info = {
                'location': loc,
                'lastmod': lastmod,
                'changefreq': changefreq,
                'priority': priority,
            }
            urls.append(url_info)

        addurl(g_blog.baseurl, changefreq='daily', priority=1)

        entries = Entry.all().filter('published =', True).order('-date').fetch(g_blog.sitemap_entries)

        for item in entries:
            loc = '%s/%s' % (g_blog.baseurl, item.link)
            addurl(loc, item.date, 'daily', 0.9)

        if g_blog.sitemap_include_category:
            cats = Category.all()
            for cat in cats:
                loc = '%s/category/%s' % (g_blog.baseurl, cat.slug)
                addurl(loc, None, 'weekly', 0.8)

        if g_blog.sitemap_include_tag:
            tags = Tag.all()
            for tag in tags:
                loc = '%s/tag/%s' % (g_blog.baseurl, urlencode(tag.tag))
                addurl(loc, None, 'weekly', 0.8)

        self.response.headers['Content-Type'] = 'text/xml; charset=utf-8'
        self.render2('views/sitemap.xml', {'urlset': urls})
Пример #37
0
 def get(self):
     try:
         objs = Article.get_post_for_homepage()
     except:
         self.redirect('/install')
         return
     if objs:
         fromid = objs[0].id
         endid = objs[-1].id
     else:
         fromid = endid = ''
     
     allpost =  Article.count_all_post()
     allpage = allpost/EACH_PAGE_POST_NUM
     if allpost%EACH_PAGE_POST_NUM:
         allpage += 1
     
     output = self.render('index.html', {
         'title': "%s - %s"%(SITE_TITLE,SITE_SUB_TITLE),
         'keywords':KEYWORDS,
         'description':SITE_DECR,
         'objs': objs,
         'cats': Category.get_all_cat_name(),
         'tags': Tag.get_hot_tag_name(),
         'page': 1,
         'allpage': allpage,
         'listtype': 'index',
         'fromid': fromid,
         'endid': endid,
         'comments': Comment.get_recent_comments(),
         'links':Link.get_all_links(),
     },layout='_layout.html')
     self.write(output)
     return output
Пример #38
0
 def post(self, caid):
     try:
         categoryattr = CategoryAttr.get(id = caid)
         category = Category.get(id = categoryattr.cid)
     except:
         self.flash("此分类属性不存在")
         self.redirect("/admin/categorys")
         return
     
     name = self.get_argument("name", None)
     dec = self.get_argument("dec", "")
     order = int(self.get_argument("order", 1))
         
     categoryattr.name = name
     categoryattr.dec = dec
     categoryattr.order = order
     
     try:
         categoryattr.validate()
         categoryattr.save()
         self.flash(u"分类属性%s修改成功" % name)
         self.redirect("/admin/categoryattrs/%d" % int(categoryattr.cid))
         return
     except Exception, ex:
         self.flash(str(ex))
Пример #39
0
    def post(self):
        # add new post or edit existed post
        t_values = {}
        current_post_id = self.request.POST["current_post_id"]
        post_title = self.request.POST["blog_title"]
        post_slug = get_safe_slug(self.request.POST["blog_slug"])
        post_content = self.request.POST["blog_content"]
        # find category
        blog_category_id = self.request.POST["blog_category_id"]
        post_category = Category.get_by_id(long(blog_category_id))
        if post_category:
            logging.info("find category %s for id %s" % (post_category.name, blog_category_id))
        else:
            logging.error("category id %s can't be located" % (blog_category_id))

        if current_post_id:
            logging.info("PostManager: post : edit post current_post_id = %s" % (current_post_id))
            # update existed post
            post = Entry.get_by_id(long(current_post_id))
            if post:
                t_values['alert_message'] = "Post %s has been updated!" % (post.title)
                post.title = post_title
                post.slug = post_slug
                post.content = post_content
                post.entrytype = "post"
                # update category count if this post is public
                if post.is_external_page and post.category != post_category:
                    if post.category and (post.category.entrycount > 0):
                        post.category.entrycount -= 1
                        post.category.put()
                    post_category.entrycount += 1
                    post.category.put()
                post.category = post_category
                post.put()
        else:
            logging.info("PostManager: post : new post title %s" % (self.request.POST['blog_title']))
            # create new post
            post = Entry()
            post.title = post_title
            post.slug = post_slug
            post.content = post_content
            post.entrytype = 'post'
            post.category = post_category
            # save as public or private?
            operation = self.request.POST["submit_action"]
            if operation == "save_publish":
                post.is_external_page = True
                # update category count
                post.category.entrycount += 1
                post.category.put()
            else:  # "save" operation
                post.is_external_page = False
            # save the post
            post.put()
            t_values['alert_message'] = "Post %s has been created!" % (post.title)

        # show all posts
        posts = Entry.all().filter("entrytype =", 'post')
        t_values['posts'] = posts
        return self.response.out.write(render_template("posts.html", t_values, "", True))
Пример #40
0
    def get(self, page_slug=""):
        if page_slug:
            t_values = {}

            posts = Entry.all().filter("is_external_page =", True).filter("entrytype =", 'page').filter("slug =", page_slug)
            if posts.count() == 1:
                logging.warning("find one page with slug=%s" % (page_slug))
                posts = posts.fetch(limit=1)
                post = posts[0]
                t_values['post'] = post
                # dump(post)

                # find all comments
                comments = Comment.all().filter("entry =", post).order("date")
                t_values['comments'] = comments
            else:
                logging.warning("%d entries share the same slug %s" % (posts.count(), page_slug))

            links = Link.all().order("date")
            t_values['links'] = links

            categories = Category.all()
            t_values['categories'] = categories

            pages = Entry.all().filter("is_external_page =", True).filter("entrytype =", 'page').order("date")
            t_values['pages'] = pages

            return self.response.out.write(render_template("page.html", t_values, "basic", False))
        else:
            self.redirect(uri_for("weblog.index"))
Пример #41
0
 def post(self, cid):
     try:
         category = Category.get(id = cid)
     except:
         self.flash("此分类不存在")
         self.redirect("/admin/categorys")
         return
     
     name = self.get_argument("name", None)
     dec = self.get_argument("dec", "")
     order = int(self.get_argument("order", 1))
         
     categoryattr = CategoryAttr()
     categoryattr.cid = cid
     categoryattr.name = name
     categoryattr.dec = dec
     categoryattr.order = order
     
     try:
         categoryattr.validate()
         categoryattr.save()
         self.flash("分类属性%s添加成功" % name)
         self.redirect("/admin/categoryattrs/%d" % int(cid))
         return
     except Exception as ex:
         self.flash(str(ex))
     
     self.render('admin/addcategoryattr.html', category = category, maxorder = CategoryAttr.maxorder(cid))
Пример #42
0
    def get(self):
        try:
            objs = Article.get_post_for_homepage()
        except:
            self.redirect('/install')
            return
        if objs:
            fromid = objs[0].id
            endid = objs[-1].id
        else:
            fromid = endid = ''

        allpost = Article.count_all_post()
        allpage = allpost / EACH_PAGE_POST_NUM
        if allpost % EACH_PAGE_POST_NUM:
            allpage += 1

        output = self.render('index.html', {
            'title': "%s - %s" % (SITE_TITLE, SITE_SUB_TITLE),
            'keywords': KEYWORDS,
            'description': SITE_DECR,
            'objs': objs,
            'cats': Category.get_all_cat_name(),
            'tags': Tag.get_hot_tag_name(),
            'page': 1,
            'allpage': allpage,
            'listtype': 'index',
            'fromid': fromid,
            'endid': endid,
            'comments': Comment.get_recent_comments(),
            'links': Link.get_all_links(),
        },
                             layout='_layout.html')
        self.write(output)
        return output
Пример #43
0
def search_categories(query):
    query = query.lower().strip()
    categories = Category.select().where(
        (fn.lower(Category.name).contains(query)) |
        (fn.lower(Category.extra).contains(query))
    )
    return categories
Пример #44
0
    def post(self):
        parent_key = self.request.get("parent_key")
        name = self.request.get("category_name")

        if len(name) < 3:
            pass  # no feedback, as of now
        else:
            try:
                parent = Category.get(db.Key(parent_key))
                Category.new(name, parent)
            except db.BadKeyError:
                pass  # no feedback, as of now
            except:
                pass  # no feedback, as of now

        self.redirect("./?category=" + parent_key)
Пример #45
0
 def get(self):
     self.echo('admin_addpost.html', {
         'title': "添加文章",
         'cats': Category.get_all_cat_name(),
         'tags': Tag.get_all_tag_name(),
     },
               layout='_layout_admin.html')
Пример #46
0
 def get(self, id = ''):
     obj = Category.get_cat_by_id(id)
     if obj:
         self.redirect('%s/category/%s'% (BASE_URL, obj.name), 301)
         return
     else:
         self.redirect(BASE_URL)
Пример #47
0
 def post(self, cid):
     
     try:
         category = Category.get(id = cid)
     except:
         self.flash("此分类不存在")
         self.redirect("/admin/categorys")
         return
     
     name = self.get_argument("name", None)
     slug = self.get_argument("slug", None)
     order = int(self.get_argument("order", 1))
     
     category.name = name
     category.slug = slug
     category.order = order
     
     try:
         category.validate()
         category.save()
         self.flash(u"分类%s修改成功" % name)
         self.redirect("/admin/categorys")
         return
     except Exception, ex:
         self.flash(str(ex))
Пример #48
0
async def api_create_category(request, *, name):
    check_admin(request)
    if not name or not name.strip():
        raise APIValueError('name', 'name cannot be empty.')
    category = Category(name=name.strip())
    await category.save()
    return category 
Пример #49
0
 def get(self):
     categories = Category.objects().all()
     return res(
         "All categories returned",
         "success",
         categories=convert_query(categories, list=True),
     )
Пример #50
0
def load_categories():
    """Load users from categories.csv into database"""

    print "Categories"

    # Delete all rows in table, so if we need to run this a second time,
    # we won't be adding duplicate categories
    Category.query.delete()

    # Read category.csv file and insert data
    for row in open("seed_data/categories.csv"):
        row = row.rstrip()
        cat_id, name, screenname, img_url = row.split(",")

        category = Category(cat_id=cat_id,
                            name=name,
                            screenname=screenname,
                            img_url=img_url)

        # Need to add to session to store
        db.session.add(category)

    # Commit my work

    db.session.commit()
Пример #51
0
	def update_basic_info(
		update_categories=False,
		update_tags=False,
		update_links=False,
		update_comments=False,
		update_archives=False,
		update_pages=False):

		from model import Entry,Archive,Comment,Category,Tag,Link
		basic_info = ObjCache.get(is_basicinfo=True)
		if basic_info is not None:
			info = ObjCache.get_cache_value(basic_info.cache_key)
			if update_pages:
				info['menu_pages'] = Entry.all().filter('entrytype =','page')\
							.filter('published =',True)\
							.filter('entry_parent =',0)\
							.order('menu_order').fetch(limit=1000)
			if update_archives:
				info['archives'] = Archive.all().order('-year').order('-month').fetch(12)
			if update_comments:
				info['recent_comments'] = Comment.all().order('-date').fetch(5)
			if update_links:
				info['blogroll'] = Link.all().filter('linktype =','blogroll').fetch(limit=1000)
			if update_tags:
				info['alltags'] = Tag.all().order('-tagcount').fetch(limit=100)
			if update_categories:
				info['categories'] = Category.all().fetch(limit=1000)

			logging.debug('basic_info updated')
			basic_info.update(info)
Пример #52
0
    def post(self):
        pdict = self.request.POST
        
        try:
            #def new(cls, title, category_keyname, author_keyname, url, keyword, tags, content, status=PostStatus.NORMAL, format=PostFormat.PLAIN, enablecomment=True):
            tags = pdict.get("post.tags").split(",")
            for i in tags:
                Tag.Incr(i)

            pkey = Post.new(title=pdict.get("post.title"),
                            category_keyname=pdict.get("post.category").decode(config.CHARSET).encode("utf-8"),
                            author_keyname=self.session.get("curr_ukey").decode(config.CHARSET).encode("utf-8"),
                            url=pdict.get("post.url"),
                            keyword=pdict.get("post.keyword").split(","),
                            tags=tags,
                            content=pdict.get("post.content"),
                            format=pdict.get("post.format") )
            p = Post.id(pkey.id())
            p.realurl = realurl(p)
            Post.put(p)
            Post.refresh_total()

        except Exception, ex:
            context = {}
            context.update(self.request.POST)
            context["errors_msg"] = ex
            context["page_name"] = u"添加文章"
            context["page_title"] = u"添加文章" 
            context["all_category"] = Category.get_all()
            self.render("admin_post_editor.html", context)
Пример #53
0
    def post(self, cid):

        try:
            category = Category.get(id=cid)
        except:
            self.flash("此分类不存在")
            self.redirect("/admin/categorys")
            return

        name = self.get_argument("name", None)
        slug = self.get_argument("slug", None)
        order = int(self.get_argument("order", 1))

        category.name = name
        category.slug = slug
        category.order = order

        try:
            category.validate()
            category.save()
            self.flash(u"分类%s修改成功" % name)
            self.redirect("/admin/categorys")
            return
        except Exception, ex:
            self.flash(str(ex))
Пример #54
0
    def get_category_articles(self, cid):
        k = 'wx_cat_%s' % (str(cid))
        v = getMc(k)
        if v:
            return v

        article_list = Category.get_cat_page_posts_by_cid(cid)
        if article_list:
            articles_msg = {'articles':[]}
            for obj in article_list:
                slug        = slugfy(obj['title'])
                if MYSQL_TO_KVDB_SUPPORT:
                    desc        = HTML_REG.sub('',obj['content'].decode('utf-8')[:DESCRIPTION_CUT_WORDS].encode('utf-8'))
                else:
                    desc        = HTML_REG.sub('',obj.content.decode('utf-8')[:DESCRIPTION_CUT_WORDS].encode('utf-8'))
                shorten_url = '%s/t/%s' % (BASE_URL, obj['id'])
                article = {
                        'title': slug,
                        'description':desc,
                        'picUrl':WX_DEFAULT_PIC,
                        'url':shorten_url,
                    }
                articles_msg['articles'].append(article)
                article = {}
            setMc(k,articles_msg)
            return articles_msg
        return ''
Пример #55
0
    def update_category_list(self):
        self.notify_admin('Sending category list...')

        # generate category links to previous messages
        all_categories = '\n'.join([
            "[{}](https://t.me/{}/{})".format(str(c), self.channel.username,
                                              c.current_message_id)
            for c in Category.select_all()
        ])

        url_stub = 'https://t.me/{}/'.format(self.channel.username)
        category_list = self._read_file(self.CATEGORY_LIST_FILE)

        # Insert placeholders
        text = category_list.format(url_stub + str(self.channel.intro_en_mid),
                                    url_stub + str(self.channel.intro_es_mid),
                                    all_categories,
                                    url_stub + str(self.channel.new_bots_mid))

        msg = self.send_or_edit(text, self.channel.category_list_mid)

        if msg:
            self.channel.category_list_mid = msg.message_id
            self.sent['category_list'] = "Category Links sent"
        self._save_channel()
Пример #56
0
 def get(self, id=''):
     obj = Category.get_cat_by_id(id)
     if obj:
         self.redirect('%s/category/%s' % (BASE_URL, obj.name), 301)
         return
     else:
         self.redirect(BASE_URL)
Пример #57
0
def posts_update(userid, pid):
    print(userid)

    try:
        post = Post.objects(pk=pid).first()
        if not post:
            raise ValidationError

        coverLst = post.covers
        coverLst.clear()

        for cover_obj in request.json.get('cover'):
            cover = Cover.objects(pk=cover_obj['uid']).first()
            coverLst.append(cover)

        post.categories.clear()
        for category_id in request.json.get('categories'):
            cate = Category.objects(pk=category_id).first()
            post.categories.append(cate)

        post.title = request.json.get('title')
        post.content = request.json.get('content')
        post.type = request.json.get('type')

        post.save()

    except:
        return jsonify({'message': 'post not found'})

    return jsonify(post.to_public_json())
Пример #58
0
def load_user_categories():
    """Load user categories from seed-user-category.txt into database."""

    print("User Categories")

    # Delete all rows in table, so if we need to run this a second time,
    # we won't be trying to add duplicate users
    Category.query.delete()

    # Read seed category file and insert data
    for row in open("seed/seed-user-category-2.txt"):
        row = row.rstrip()
        # Works for original seed data
        # user_id, base_category_id, name, description = row.split("|")

        # These are metadata lines in the file
        if not row.startswith('--'):
            category_id, name, description, user_id, base_category_id = row.split(
                "|")

            category = Category(category_id=int(category_id),
                                name=name,
                                description=description,
                                user_id=int(user_id),
                                base_category_id=base_category_id)
            db.session.add(category)
    db.session.commit()
Пример #59
0
def admin_page():
    url_for('static', filename='style.css')
    all_categories = Category.query.all()
    all_users = User.query.all()
    if request.method == "POST":
        if "add-category" in request.form:
            category = Category(name=request.form["category-name"])
            all_categories.append(category)
            database.session.add(category)
        elif "delete-category" in request.form:
            Category.query.filter_by(
                id=int(request.form["delete-category"])).delete()
        elif "add-user" in request.form:
            user = users.create(request.form["user-login"],
                                request.form["user-password"],
                                request.form["user-first-name"],
                                request.form["user-last-name"], "user-is-admin"
                                in request.form)
            all_users.append(user)
            database.session.add(user)
        elif "delete-user" in request.form:
            User.query.filter_by(login=request.form["delete-user"]).delete()
        database.session.commit()
    return render_template('admin.html',
                           categories=all_categories,
                           users=all_users,
                           is_admin=True)