Example #1
0
def api_article_add(*, request, title, category, tag, content, summary):
    r = web.Response()
    blog = Blogs(title = title, user_id = getWebCookie(request, 'id'), summary = summary, content = content)
    id = yield from blog.save()
    category = urldecode(category)
    category = category[0].split(',')
    tags = tag.split('/')
    if id > 0:
        #文章分类插入
        for i in category:
            blog_category = BlogCategory(blog_id = id, category_id = i)
            blog_category_id = yield from blog_category.save()
        #标签分类插入
        for t in tags:
            t = t.strip()
            tag_title = yield from Tag.findAll('title=?', [t])
            #如果标签存在,则插入博客标签表,若不存在,则两张表都要插入
            if len(tag_title) > 0:
                tag_id = tag_title[0].get('id')
            else:
                tag = Tag(title = t)
                tag_id = yield from tag.save()
            blog_tag = BlogTag(blog_id = id, tag_id = tag_id)
            blog_tag_id = yield from blog_tag.save()
    if id > 0 and blog_category_id > 0 and blog_tag_id > 0:
        result = APIResult(1, '', '发布成功')
    else:
        result = APIResult(0, '', '发布失败')
    return jsonResult(r, result)
Example #2
0
 def post(self, secret=""):
     tags = (self.get_argument("tags", ""),)
     if tags and secret:
         if secret == getAttr("MOVE_SECRET"):
             Tag.set_tags(encode_special_txt(tags[0]))
             return self.write("1")
     return self.write("0")
Example #3
0
 def post(self, secret=''):
     tags = self.get_argument("tags", ''),
     if tags and secret:
         if secret == getAttr('MOVE_SECRET'):
             Tag.set_tags(encode_special_txt(tags[0]))
             return self.write('1')
     return self.write('0')
Example #4
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, 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': 'tag',
            '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
Example #5
0
def pub(ctx,request:YuHeLg.Request):
    payload = request.json
    post = Post()
    try:
        post.title = payload.get("title")
        post.author_id = request.user.id
        post.postdate = datetime.datetime.now()
        cont = Content()
        cont.content = payload.get("content")
        post.content = cont
        tags = payload["tags"]
    except Exception as e:
        print(e)
        raise exc.HTTPBadRequest()

    taglist = re.split('[\s,]',tags)
    for tag in taglist:
        t = session.query(Tag).filter(Tag.tag == tag).first()
        if t is None:
            t = Tag()
            t.tag = tag
            session.add(t)
        pt = Post_tag()
        pt.tag = t
        pt.post = post
        session.add(pt)

    session.add(post)
    try:
        session.commit()
        return jsonify(post_id=post.id)
    except:
        session.rollback()
        raise exc.HTTPInternalServerError()
Example #6
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))
Example #7
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, 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': 'tag',
         '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
Example #8
0
def tag_add_process():
    """Takes in two params from form via POST request and adds tag to database."""
    #make sure only the logged in user can add new article
    tag_value = request.form.get("tag_value")
    article_id = request.form.get("article_id")
    user_id_value = session.get("user_id")
    # in future could verify article by same title doesn't exist
    if user_id_value:
        tag_object = Tag.get_tag_by_tag_value(tag_value)
        if tag_object:
            tag_id = tag_object.tag_id
        else:
            Tag.create_new_tag(tag_value)
            tag_object = Tag.get_tag_by_tag_value(tag_value)
            tag_id = tag_object.tag_id

        Tagging.create_new_tagging(article_id, tag_id)
        new_tag_attributes = {
            "tag_value": tag_value,
            "tag_id": tag_id,
            "article_id": article_id
        }
        return jsonify(new_tag_attributes)
    else:
        return redirect("/login")
Example #9
0
def home():
    user = {
        'username': '******',
        'age': 27
    }
    websites = ['baidu.com', 'google.com']
     #新建两篇文章
    art1 = Art(title='大海')
    art2 = Art(title='小人')
     #新建两个标签
    tag1 = Tag(name='酸')
    tag2 = Tag(name='甜')

    #添加多对多关系,文章1添加两个标签
    art1.tags.append(tag1)
    art1.tags.append(tag2)
    # 添加多对多关系,文章2添加两个标签
    art2.tags.append(tag1)
    art2.tags.append(tag2)


    #添加部分
    db.session.add(art1)
    db.session.add(art2)
    db.session.add(tag1)
    db.session.add(tag2)

    db.session.commit()
    return render_template('home.html', user=user, websites=websites)
Example #10
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))
Example #11
0
def papers(tag_id):
    if not tag_id:
        tags = Tag.select().paginate(0, 1)
    else:
        tags = Tag.select().where(Tag.id == tag_id)
    tag = tags[0]
    papers = Paper.select().where(Paper.tag == tag)
    return render_template("papers.html", tag=tag, papers=papers)
Example #12
0
def save_data(s3client, field, bucket, key):
    for data in read_fields(s3client, field, bucket, key):
        tag = Tag()
        tag.name = data.strip()
        try:
            tag.save(force_insert=True)
        except IntegrityError:
            pass
Example #13
0
	def get(self,req_user=''):
		user_lang = 'en'
		#********************** User Auth **************************#
		user = users.get_current_user()
		nickname = ''
		if user:
			nickname=user.nickname()
		if nickname:
			user_info = User.all().filter('user',nickname)
			if user_info.count(1)>0:
				user_info = user_info.get()
				user_lang = user_info.lang
			auth_url = users.create_logout_url(self.request.uri)
			auth_text= 'signout'
		else:
			auth_url = users.create_login_url(self.request.uri)
			auth_text= 'signin'
		
		entry_count =Entry.all().count(1000)
		if req_user:
			tag_user = req_user
			tags = Tag.all().filter("user",req_user)
		else:
			tag_user = '******'
			tags = Tag.all()
		tags_count = tags.count(1000)
		tag_list=[]
		for tag in tags:
			tag_count=tag.count_link + tag.count_note + tag.count_pic
			if tag.count_link >= tag.count_note:
				if tag.count_link >= tag.count_pic:
					max_type = 'link'
				else:
					max_type = 'pic'
			else:
				if tag.count_pic >= tag.count_note:
					max_type = 'pic'
				else:
					max_type = 'note'
			#logging.info(tag_count)
			#logging.info(entry_count)
			#logging.info(tags_count)
			tag_list.append({
				"info":tag,
				"type":max_type,
				"level":int(round(tag_count/(float(entry_count)/tags_count)))
				})
		template_values = {
			'nickname' : nickname,
			'req_user' : req_user,
			'auth_url' : auth_url,
			'auth_text': auth_text,
			'tag_user' : tag_user,
			'tags'     : tag_list,
			'uri'      : self.request.uri
			}
		path = os.path.join(os.path.dirname(__file__),'templates/'+user_lang+'/tag.html')
		self.response.out.write(template.render(path,template_values))
Example #14
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
Example #15
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
Example #16
0
def get_papers(tag_id):
    if tag_id:
        tags = Tag.select().where(Tag.id == tag_id)
    else:
        tags = Tag.select().paginate(0, 1)
    papers = Paper.select().where(
        Paper.tag << tags).dicts()  #.paginate(0, 100)
    response = {'papers': list(papers)}
    return jsonify(response)
Example #17
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
Example #18
0
    def get(self):
        # 获取要修改的tag
        self.from_name = self.get_argument('from_name', '').strip()

        if self.from_name:
            self.to_name = self.get_argument('to_name', '').strip()
            # 有目标tag,移动/重命名
            # 没目标tag,删除
            if self.to_name:
                Tag.move_tag(self.from_name, self.to_name)
            else:
                Tag.delete_tag(self.from_name)
        self.redirect('/dashboard')
Example #19
0
 def test_post_tag(self):
     t1 = Tag(name='iot')
     t2 = Tag(name='web')
     p1 = Post(content='This is a post contain iot and web tags.')
     p2 = Post(content='This is a post contain web.')
     p1.add_all_tags([t1, t2])
     p2.tags.append(t2)
     self.session.add_all([t1, t2, p1, p2])
     self.session.commit()
     self.assertCountEqual(t1.posts, [p1])
     self.assertCountEqual(t2.posts, [p1, p2])
     self.assertCountEqual(p1.tags, [t1, t2])
     self.assertCountEqual(p2.tags, [t2])
Example #20
0
    def post(self):
        """Creates a new tag for the logged in user"""
        user = utils.get_current_user()
        title = self.request.get('title')
        new_title = self.request.get('newTitle') or None
        
        if not user:
            self.error(403)
            return
        
        if not title:
            self.error(400)

        # Create new tag
        if not new_title:
            m = Tag.all().ancestor(user).filter('title_lower =', title.lower()).get()
            
            if m:
                # Not unique
                self.error(409)
                return

            m = Tag(
                parent=user,
                title=title,
                title_lower=title.lower(),
            )
            m.put()

        # Rename Tag
        else:
            m = Tag.all().ancestor(user).filter('title_lower =', new_title.lower()).get()
            if m:
                # Not unique
                self.error(409)
                return

            m = Tag.all().ancestor(user).filter('title_lower =', title.lower()).get()
            if not m:
                # Original tag not found
                self.error(404)
                return

            m.title = new_title
            m.title_lower = new_title.lower()
            m.save()

        self.response.headers['Content-Type'] = 'text/plain; charset=utf-8'
        self.response.headers['Access-Control-Allow-Origin'] = '*'
        self.response.out.write('ok')
Example #21
0
 def get(self,format):
     tags = Tag.all().run()
     db.delete(tags)
     
     firstLevelTags = [
         "ActionScript",
         "Asp",
         "BASIC",
         "C",
         "C++",
         "Clojure",
         "COBOL",
         "ColdFusion",
         "Erlang",
         "Fortran",
         "Groovy",
         "Haskell",
         "Java",
         "JavaScript",
         "Lisp",
         "Perl",
         "PHP",
         "Python",
         "Ruby",
         "Scala",
         "Scheme",
         "haxe",
         "nodejs",
         'framework',
         'tool',
         'wiki',
         'tutorial',
         'howto',
         'library',
         'service',
         'language'
     ]
     
     for tag in firstLevelTags:
         t = Tag(name=tag.lower())
         t.put()
         
     entries = Entry.all()
     for e in entries:
         newtags = getTagKeys(e.tagsRaw)
         e.tags = newtags
         e.put()
         
     simplewebapp.formatResponse(format, self, "OK")
     
Example #22
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
Example #23
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
Example #24
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
Example #25
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
Example #26
0
def get_tags_by_names(tags):

    sql = '''SELECT * FROM tag
             WHERE name in %(name)s'''
    rows = pg_select(sql, {'name': tuple(tags)})
    tags = [Tag(*row) for row in rows]
    return tags
Example #27
0
def add_tag():
    """Add/edit a tag"""

    # hold a list of new tags from string input
    new_tags = []

    # Get form variables
    image_id = request.form["image_id"]
    tag_string = request.form["query"]
    new_tags = get_tags_from_string(tag_string)

    if not image_id:
        raise Exception("No image to tag")

    all_tags = Image_Tags.query.filter_by(image_id=image_id).all()

    if all_tags:
        # add new tag to list of tags stored in db
        flash("Tag added.")

    else:
        # add new tag list to database
        tag_label = Tag(tag_label=tag_label)
        flash("Tag added.")
        db.session.add(tag_label)

    db.session.commit()

    return redirect("/images/%s" % image_id)
Example #28
0
def getTagsForUrl(url):
    try:
        content = resource.get(url).decodeBody().lower()
    except:
        content = ""
    
    soup = BeautifulSoup(content) 
    texts = soup.findAll(text=True)

    def visible(element):
        if element.parent.name in ['style', 'script', '[document]', 'head', 'title']:
            return False
        elif re.match('<!--.*-->', str(element)):
            return False
        return True
    
    visible_texts = filter(visible, texts)
    visibleText = " ".join(visible_texts)
    
    result = getTagsProposalsForText(visibleText)
    
    entry = Entry.all().filter("url =", url).fetch(1)
    if len(entry) > 0:
        entryStableTags = entry[0].tags
        for t in entryStableTags:
            found = False
            name = Tag.get(t).name
            for r in result:
                if name == r:
                    found = True
            if not found:
                result.append(name)
                
    return result
Example #29
0
def user2ag():
    user = User.select()[0]
    if not user.user_agent or not user.mac_address and request.endpoint not in (
            'user2code', 'static'):
        return redirect(url_for('user2code'))
    tags = Tag.select()
    g.tags = tags
Example #30
0
def add_project():
    """Add a new project to the database."""

    data = json.loads(request.data.decode())

    title = data.get('title')
    desc = data.get('desc')
    category_id = data.get('categoryId')
    tags = data.get('tags')

    # Add project
    project = Project(title, desc=desc)
    db.session.add(project)
    db.session.commit()

    # Add association
    db.session.add(CategoryProject(category_id, project.id))
    db.session.commit()

    # Add tags
    if tags:
        all_tags = Tag.create_tags(tags)
        db.session.add_all([TagProject(project.id, tag.code)
                            for tag in all_tags
                            ])
        db.session.commit()

    return get_project_json(project.id)
Example #31
0
def update_article_details():
    """Updates an article's details."""

    new_price = request.form.get('purchase-price')
    article_id = request.form.get('article-to-edit')
    tag_ids = request.form.getlist('article-tags')
    new_tag_string = request.form.get('new-tags')
    article = Article.query.filter_by(article_id=article_id).one()

    if new_price:
        article.update({'purchase_price': new_price})

    all_tags = []
    for tag_id in tag_ids:
        all_tags.append(Tag.query.filter_by(tag_id=tag_id).one())

    # TODO: Brute force method - remove all tags before appending
    # Better: Check for discrepancies; remove unchecked, then proceed

    # Any newly created tags should be added to this as well
    all_tags += Tag.parse_str_to_tag(new_tag_string, session['user_id'])

    # Then create all the tag relationships
    for tag in all_tags:
        article.add_tag(tag)

    return redirect(f'/articles/{article_id}')
Example #32
0
def load_waymarks():
    """Load points from Waymark scraped txt file into database"""

    print "Waymark Murals SF"

    for row in open("seed_data/waymarks.txt"):
        row = row.rstrip()

        latitude, longitude, title, artist, details, media_url = row.split('|')

        tag = Tag(latitude=latitude,
                  longitude=longitude,
                  title=title,
                  artist=artist,
                  details=details,
                  primary_image=media_url)

        db.session.add(tag)
        db.session.commit()

        tag_genre = TagGenre(tag_id=tag.tag_id, genre="art")

        db.session.add(tag_genre)

    db.session.commit()
Example #33
0
def load_art_points_Oakland():
    """Load points from Oakland public art csv data into database"""

    print "Tags Oakland"

    with open("seed_data/Oakland_Civic_Art.csv") as csv_file:
        for row in csv.reader(csv_file):

            title, artist, artist_origin, year, temp_or_perm, in_or_out, media, media_detail, location, address = row

            #parse location information into latitude and longitude
            lat_long = location.split('\n')[-1][1:-1].split(", ")

            latitude = float(lat_long[0])
            longitude = float(lat_long[1])

            tag = Tag(latitude=latitude,
                      longitude=longitude,
                      title=title,
                      artist=artist,
                      details=media_detail)

            db.session.add(tag)
            db.session.commit()

            tag_genre = TagGenre(tag_id=tag.tag_id, genre="art")

            db.session.add(tag_genre)

    db.session.commit()
Example #34
0
def load_art_points_SF():
    """Load points from SF public art csv data into database"""

    print "Tags SF"

    Tag.query.delete()

    with open("seed_data/SF_Civic_Art.csv") as csv_file:
        for row in csv.reader(csv_file):

            artist, created_at, patron, size, geometry, location, details, source, title = row[
                3:12]

            latitude = json.loads(geometry)['coordinates'][1]
            longitude = json.loads(geometry)['coordinates'][0]

            tag = Tag(latitude=latitude,
                      longitude=longitude,
                      title=title,
                      artist=artist,
                      details=details)

            db.session.add(tag)
            db.session.commit()

            tag_genre = TagGenre(tag_id=tag.tag_id, genre="art")

            db.session.add(tag_genre)

    db.session.commit()
Example #35
0
def load_freesound_audio():
    """Load points gathered from Freesound API"""

    print "Freesound SF"

    for row in open("seed_data/freesounds.txt"):
        row = row.rstrip()

        latitude, longitude, title, details, audio_url = row.split('|')

        tag = Tag(latitude=latitude,
                  longitude=longitude,
                  title=title,
                  details=details)

        db.session.add(tag)
        db.session.commit()

        tag_genre = TagGenre(tag_id=tag.tag_id, genre="audio")

        db.session.add(tag_genre)

        media = Media(tag_id=tag.tag_id,
                      media_url=audio_url,
                      media_type="audio")

        db.session.add(media)
    db.session.commit()
Example #36
0
    def delete(self, title):
        """Delete the specified tag for the current user"""
        user = utils.get_current_user()
        
        title = title.decode('utf-8')
        
        if not user:
            self.error(403)
            return
            
        m = Tag.all().ancestor(user).filter('title_lower =', title.lower()).get()
        if not m:
            # Original tag not found
            self.error(404)
            return

        entries = Entry.all().filter('tags =', m.key())

        # Remove tag from entries
        for entry in entries:
            logging.info(entry)
            entry.tags.remove(m.key())
            entry.save()
        
        m.delete()

        self.response.headers['Content-Type'] = 'text/plain; charset=utf-8'
        self.response.headers['Access-Control-Allow-Origin'] = '*'
        self.response.out.write('ok')
Example #37
0
    def get(self):

        entry_count = Entry.all().count(1000)
        tags = Tag.all().order('usetime')

        tags_count = tags.count(1000)
        tag_list = []
        for tag in tags:
            tag_count = tag.count_link + tag.count_note + tag.count_pic
            if tag.count_link >= tag.count_note:
                if tag.count_link >= tag.count_pic:
                    max_type = 'link'
                else:
                    max_type = 'pic'
            else:
                if tag.count_pic >= tag.count_note:
                    max_type = 'pic'
                else:
                    max_type = 'note'
            tag_list.append({
                "info": tag,
                "type": max_type,
                "level": tag_count / (entry_count / tags_count)
            })
        template_values = {'tags': tag_list}

        path = os.path.join(os.path.dirname(__file__), 'templates/tag.html')
        self.response.out.write(template.render(path, template_values))
Example #38
0
    def get(self):
        user = users.get_current_user()
        key = self.request.get('key')
        if key and users.is_current_user_admin():
            e = db.get(key)
            if e:

                if e.tags:
                    for tag_name in e.tags:
                        tag = Tag.all().filter('name', tag_name)
                        if (tag.count(1) > 0):
                            t = tag.get()
                            if e.type == 'link':
                                t.count_link -= 1
                            if e.type == 'note':
                                t.count_note -= 1
                            if e.type == 'pic':
                                t.count_pic -= 1
                            t.put()
                db.delete(e)
                self.response.out.write('1')

            else:
                self.response.out.write('0')
            memcache.delete(key)
        else:
            self.response.out.write('0')
Example #39
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
Example #40
0
    def get(self, user, tag_title):
        """Gets RSS feed for a user, filtered by tag"""
        user = utils.get_user_model_by_id_or_nick(user)
        
        if not user:
            self.error(403)
            return
            
        tag_title = tag_title.decode('utf-8')
        tag = Tag.all().ancestor(user.key()).filter('title_lower =', tag_title.lower()).get()

        if not tag:
            self.error(404)
            return

        entries = Entry.all().filter('tags =', tag.key()).filter('published =', True).order('-time_published').fetch(20)
        entries = [e.to_struct() for e in entries]
            
        path = os.path.join(os.path.dirname(__file__), 'template.rss')
        self.response.headers['Content-Type'] = 'application/xml; charset=utf-8'
        self.response.out.write(template.render(path, {
            'entries': entries,
            'url': self.request.url,
            'title': tag_title,
        }))
def add_or_rm_tags():
    """Lets an admin add or remove a tag to the tag table.
    Currently this route is throwing an ERROR. Please investigate."""

    if current_user.id == 1:

        if request.form.get("newtag", False):

            newtag = request.form["newtag"]

            tag_to_add = Tag(tag_name=newtag)
            db.session.add(tag_to_add)

        if request.form.get("rmtag", False):

            rmtag = request.form["rmtag"]

            try:
                Tag.query.filter_by(tag_name=rmtag).delete()
            except:
                print("Tag deletion Invalid")

        db.session.commit()

    return render_template("homepage.html")
Example #42
0
def validate():
    data = request.get_json()
    app_uuid = data["app_uuid"]
    #user_id = data["user_id"]

    if not Application.is_valid(app_uuid):
        abort(401)

    text_uuid, data_score = data["id"], data["score"]
    Tag.create(
        application_uuid=app_uuid,
        user_id=0,  #reserved for this front
        text_uuid=text_uuid,
        score=data_score,
        validated=True)
    return random_items()
Example #43
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)
Example #44
0
 def test_tag_creation(self):
     print '- test_tag_creation'
     tag = Tag.create('musk')
     self.assertEqual(tag.tag_id, 2)
     self.assertIsInstance(tag, Tag)
     self.assertEqual(tag.name, 'musk')
     print '+ passed'
Example #45
0
async def api_create_blog(request, *, name, summary, content, selectedTags):
    check_admin(request)
    if not name or not name.strip():
        raise APIValueError("name", "name cannot be empty.")
    if not summary or not summary.strip():
        raise APIValueError("summary", "summary cannot be empty.")
    if not content or not content.strip():
        raise APIValueError("content", "content cannot be empty.")
    blog = Blog(
        user_id=request.__user__.id,
        user_name=request.__user__.name,
        user_image=request.__user__.image,
        name=name.strip(),
        summary=summary.strip(),
        content=content.strip(),
    )
    await blog.save()
    for selectedTag in selectedTags:
        if selectedTag["key"]:
            blog_tag = BlogTag(blog_id=blog.id, tag_id=selectedTag["key"])
            await blog_tag.save()
        else:
            tag = Tag(name=selectedTag["value"])
            await tag.save()
            blog_tag = BlogTag(blog_id=blog.id, tag_id=tag.id)
            await blog_tag.save()
    return blog
Example #46
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')
Example #47
0
async def api_create_tag(request, *, name):
    check_admin(request)
    if not name or not name.strip():
        raise APIValueError("name", "name cannot be empty.")
    tag = Tag(name=name.strip())
    await tag.save()
    return tag
Example #48
0
	def get(self):
		user = users.get_current_user()
		key = self.request.get('key')
		if key and users.is_current_user_admin():
			e = db.get(key)
			if e:


					if e.tags:
						for tag_name in e.tags:
							tag = Tag.all().filter('name',tag_name)
							if(tag.count(1)>0):
								t = tag.get()
								if e.type == 'link':
									t.count_link -= 1
								if e.type == 'note':
									t.count_note -= 1
								if e.type == 'pic':
									t.count_pic -= 1
								t.put()
					db.delete(e)
					self.response.out.write('1')


			else:
				self.response.out.write('0')
			memcache.delete(key)
		else:
			self.response.out.write('0')
Example #49
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, 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': 'cat',
            '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
Example #50
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()
            if MYSQL_TO_KVDB_SUPPORT:
                fromid = objs[0]['id']
                endid = objs[-1]['id']
            else:
                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" %
            (getAttr('SITE_TITLE'), getAttr('SITE_SUB_TITLE'), page),
            'keywords':
            getAttr('KEYWORDS'),
            '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':
            'index',
            'fromid':
            fromid,
            'endid':
            endid,
            '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
Example #51
0
 def getTags():
     tags = []
     for tag in Tag.select():
         tags.append("'" + tag.tag.replace("'", "\\'") + "'")
     
     data = "[" + ",".join(tags) + "];"
     
     return data
Example #52
0
    def get(self, tag):
        self.response.headers['Cache-Control'] = 'max-age=14400'
        if tag is None:
            #No tag selected
            tags = Tag.get_tags()
            template = templater.get_template('templates/tags.html')
            self.response.write(templater.render({'tags':tags}))
            return

        dives = Tag.get_dives(tag.lower())
        data = {'dives': dives,
                'tag': tag}

        # TODO use Etag and/or memcache

        template = templater.get_template('templates/tag.html')
        self.response.write(template.render(data))
Example #53
0
    def post(self, feed_id, entry_id, tag_title):
        """ Create or modify tag """
        current_user = utils.get_current_user()
        
        if not current_user:
            logging.info('no user logged in')
            self.error(403)
            return

        logging.info(feed_id)
        feed = InputFeed.get_by_id(int(feed_id), parent=current_user)

        if not feed:
            logging.info('no feed found')
            self.error(404)
            return

        entry = Entry.get_by_id(int(entry_id), parent=feed)

        if not entry:
            logging.info('no entry found')
            self.error(404)
            return

        if not tag_title:
            logging.info('no tag_title provided found')
            self.error(400)
            return

        tag_title = tag_title.decode('utf-8')
        tag = Tag.all().ancestor(current_user).filter('title_lower =', tag_title.lower()).get()

        if not tag:
            logging.info('tag not found, creating new')

            tag = Tag(
                parent=current_user,
                title=tag_title,
                title_lower=tag_title.lower(),
            )

        tag.tag_entry(entry)
        self.response.headers['Content-Type'] = 'text/plain; charset=utf-8'
        self.response.headers['Access-Control-Allow-Origin'] = '*'
        self.response.out.write('ok')
Example #54
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
Example #55
0
 def get(self, id=""):
     obj = None
     if id:
         obj = Article.get_article_by_id_edit(id)
     self.echo(
         "admin_editpost.html",
         {"title": "编辑文章", "cats": Category.get_all_cat_name(), "tags": Tag.get_all_tag_name(), "obj": obj},
         layout="_layout_admin.html",
     )
Example #56
0
    def get(self, id = '', title = ''):
        tmpl = ''
        obj = Article.get_article_by_id_detail(id)
        if not obj:
            self.redirect(BASE_URL)
            return
        #redirect to right title
        try:
            title = unquote(title).decode('utf-8')
        except:
            pass
        if title != obj.slug:
            self.redirect(obj.absolute_url, 301)
            return
        #
        if obj.password and THEME == 'default':
            rp = self.get_cookie("rp%s" % id, '')
            if rp != obj.password:
                tmpl = '_pw'
        elif obj.password and BLOG_PSW_SUPPORT:
            rp = self.get_cookie("rp%s" % id, '')
            print 'rp===%s' % (str(rp))
            if rp != obj.password:
                tmpl = '_pw'

        keyname = 'pv_%s' % (str(id))
        increment(keyname)#yobin 20120701
        self.set_cookie(keyname, '1', path = "/", expires_days =1)
        self.set_header("Last-Modified", obj.last_modified)
        output = self.render('page%s.html'%tmpl, {
            'title': "%s - %s"%(obj.title, getAttr('SITE_TITLE')),
            'keywords':obj.keywords,
            'description':obj.description,
            'obj': obj,
            'cobjs': obj.coms,
            'postdetail': 'postdetail',
            'cats': Category.get_all_cat_name(),
            'tags': Tag.get_hot_tag_name(),
            'archives': Archive.get_all_archive_name(),
            'page': 1,
            'allpage': 10,
            'comments': Comment.get_recent_comments(),
            'links':Link.get_all_links(),
            'isauthor':self.isAuthor(),
            'hits':get_count(keyname),
            'Totalblog':get_count('Totalblog',NUM_SHARDS,0),
            'listtype': '',
        },layout='_layout.html')
        self.write(output)

        if obj.password and BLOG_PSW_SUPPORT:
            return output
        elif obj.password and THEME == 'default':
            return
        else:
            return output
Example #57
0
 def get(self, id = ''):
     obj = None
     if id:
         obj = Article.get_article_by_id_edit(id)
     self.echo('admin_editpost.html', {
         'title': "编辑文章",
         'cats': Category.get_all_cat_name(),
         'tags': Tag.get_all_tag_name(),
         'obj': obj
     },layout='_layout_admin.html')
Example #58
0
def getTagsProposalsForText(text):
    result = []
    tags = Tag.all()
    for tag in tags:
        if re.search(r'\b'+re.escape(tag.name)+r'\b',text):
            result.append(tag.name)
    
    result = excludeMismatches(result)
    
    return result
Example #59
0
    def get(self, id):
        post = Post.get_post_by_id(id, ignorestatus=True)
        self.datamap['category'] = Category.get_categorys()
        self.datamap['tags'] = Tag.get_tags()

        self.datamap['post'] = post

        self.datamap['chose_tag'] = [x.tag for x in post.tag]
        self.datamap['chose_category'] = [x.category for x in post.category]
        self.write(render_admin.editpost(self.datamap))
Example #60
0
def getTagLists():
  key_ = "tag_lists"
  tags = memcache.get(key_)
  if tags is not None:
    return tags
  else:
    tags_ = Tag.all()
    tags = [x for x in tags_]
    if not memcache.add(key_, tags, 3600):
      logging.error("Memcache set failed.")
    return tags