コード例 #1
0
def main():
    logging.basicConfig(level=logging.DEBUG,
        format='[%(asctime)s] [%(levelname)s] %(message)s')

    Archive.reload()
    RescrapeTask().start()
    app.run(host='0.0.0.0')
コード例 #2
0
ファイル: admin.py プロジェクト: yobin/saepy-log
    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))
コード例 #3
0
ファイル: admin.py プロジェクト: yobin/saepy-log
 def post(self, secret=''):
     arches = self.get_argument("arches", ''),
     if arches and secret:
         if secret == getAttr('MOVE_SECRET'):
             Archive.set_arches(encode_special_txt(arches[0]))
             return self.write('1')
     return self.write('0')
コード例 #4
0
ファイル: admin.py プロジェクト: yobin/saepy-log
 def post(self, secret=""):
     arches = (self.get_argument("arches", ""),)
     if arches and secret:
         if secret == getAttr("MOVE_SECRET"):
             Archive.set_arches(encode_special_txt(arches[0]))
             return self.write("1")
     return self.write("0")
コード例 #5
0
ファイル: admin.py プロジェクト: yobin/saepy-log
    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))
コード例 #6
0
ファイル: admin.py プロジェクト: yangzilong1986/saepy-log
    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
コード例 #7
0
ファイル: tasks.py プロジェクト: shaybarak/israeli-government
    def do_task(self):
        try:
            logging.info("Scraping knesset website...")
            members = KnessetScraper.scrape()
            if Archive.is_empty() or members != Archive.latest().members:
                logging.info("Got new government members! Saving them.")
                Archive.save_new(members)
            else:
                logging.info("Already got latest government members.")

        except Exception:
            logging.error("Error in rescrape task!", exc_info = True)
コード例 #8
0
def create_archive(username, category_id, tracker_id, user_id):
    """
    Archive summary of results in the database and store
    a zip archive in the data directory.
    """

    redis = worker.get_redis()
    worker.start_job()
    db_session = worker.get_session()
    found_count = 0
    not_found_count = 0
    error_count = 0

    results = (db_session.query(Result).options(subqueryload(
        Result.image_file)).filter(Result.tracker_id == tracker_id).all())
    site_count = len(results)

    # Generate zip file
    filename = re.sub('[\W_]+', '', username)  # Strip non-alphanumeric char
    zip_file_id = create_zip(filename, results, user_id)

    for result in results:
        if result.status == 'e':
            error_count += 1
        elif result.status == 'f':
            found_count += 1
        elif result.status == 'n':
            not_found_count += 1

    archive = Archive(tracker_id=tracker_id,
                      username=username,
                      category_id=category_id,
                      site_count=site_count,
                      found_count=found_count,
                      not_found_count=not_found_count,
                      error_count=error_count,
                      zip_file_id=zip_file_id,
                      user_id=user_id)

    # Write to db
    db_session.add(archive)
    db_session.commit()

    # Publish
    message = {
        'id': archive.id,
        'name': archive.username,
        'status': 'created',
        'archive': archive.as_dict(),
    }
    redis.publish('archive', json.dumps(message))
    worker.finish_job()
コード例 #9
0
ファイル: admin.py プロジェクト: yangzilong1986/saepy-log
 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
コード例 #10
0
ファイル: blog.py プロジェクト: yobin/saepy-log
    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
コード例 #11
0
ファイル: cache.py プロジェクト: fly2014/XBLOG
	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)
コード例 #12
0
ファイル: blog.py プロジェクト: yangzilong1986/saepy-log
    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
コード例 #13
0
ファイル: blog.py プロジェクト: yobin/saepy-log
    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
コード例 #14
0
ファイル: blog.py プロジェクト: Git-Host/cpedialog
 def generate(self, template_name, template_values={}):
   archiveList = Archive.list()
   archiveList.sort(lambda x,y: cmp(y["date"],x["date"]))
   values = {
     'archiveList': archiveList,
   }
   values.update(template_values)
   view.ViewPage(cache_time=0).render(self, template_name, values)
コード例 #15
0
ファイル: blog.py プロジェクト: yobin/saepy-log
    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
コード例 #16
0
ファイル: blog.py プロジェクト: yangzilong1986/saepy-log
    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
コード例 #17
0
ファイル: util.py プロジェクト: BlowBlood/blowblood
def getArchiveLists():
  key_ = "archive_lists"
  archives = memcache.get(key_)
  if archives is not None:
    return archives
  else:
    archives_ = Archive.all().order("-date")
    archives = [x for x in archives_]
    if not memcache.add(key_, archives, 3600):
      logging.error("Memcache set failed.")
    return archives
コード例 #18
0
ファイル: util.py プロジェクト: honten/diary
def getArchiveList():
    key_ = "blog_monthyear_key"
    try:
        monthlist = memcache.get(key_)
    except Exception:
        monthlist = None
    if monthlist is None:
        monthlist = Archive.gql('ORDER BY date desc').fetch(100)
        memcache.add(key=key_, value=monthlist, time=3600)
    else:
        logging.debug("getMonthYearList from cache. ")
    return monthlist
コード例 #19
0
ファイル: util.py プロジェクト: woodenbrick/wedding
def getArchiveList():
    key_ = "blog_monthyear_key"
    try:
        monthlist = memcache.get(key_)
    except Exception:
        monthlist = None
    if monthlist is None:
        monthlist = Archive.all().order('-date')
        memcache.add(key=key_, value=monthlist, time=3600)
    else:
        logging.debug("getMonthYearList from cache. ")
    return monthlist
コード例 #20
0
def apply_action(mails):
    # we are going to do actions  according to this list
    # actions = ["Mark as read", "mark as unread", "Archive message", "Add label"]
    print("Enter your action: ")
    for i, value in enumerate(actions):
        print("For " + value.upper() + " Enter " + str(i))
    action_choice = int(raw_input("Enter your choice number: "))
    if action_choice == 0:
        # mark as read
        for x in mails:
            label_objects = session.query(Label).filter_by(mail_id=x.mail_id)
            for label in label_objects:
                if label.mail_label == "UNREAD":
                    session.delete(label)
                    session.commit()

    elif action_choice == 1:
        # mark as unread
        for x in mails:
            label_objects = session.query(Label).filter_by(mail_id=x.mail_id)
            applied = False
            for label in label_objects:
                if label.mail_label == "UNREAD":
                    applied = True
            if not applied:
                # if contrast label is not available, let's add this to file
                new_label_object = Label(mail_label="UNREAD",
                                         mail_id=x.mail_id)
                session.add(new_label_object)
                session.commit()
    elif action_choice == 2:
        # archieved message
        for x in mails:
            newArcheiveObj = Archive(mail_id=x.mail_id,
                                     mail_time=x.mail_time,
                                     mail_from=x.mail_from,
                                     mail_to=x.mail_to,
                                     subject=x.subject,
                                     text_of_body=x.text_of_body)
            session.add(newArcheiveObj)
            session.commit()
            # let's delete from mail file
            session.delete(x)
            session.commit()
    elif action_choice == 3:
        # add label
        label = raw_input("Enter your label name: ")
        for x in mails:
            newObj = Label(mail_label=label, mail_id=x.mail_id)
            session.add(newObj)
            session.commit()
    print("Congratulation, It has been applied. Aregorn")
コード例 #21
0
ファイル: rpc.py プロジェクト: Git-Host/cpedialog
 def RefreshArchive(self,request):
     archive = Archive.get_by_id(int(request.get("id")))
     query = db.GqlQuery("select * from Weblog where monthyear=:1 and entrytype = 'post'order by date desc",archive.monthyear)
     if query:
         archive.weblogcount = query.count()
         archive.put()
     archiveJson = {}
     archiveJson["id"] =  str(archive.key().id())
     archiveJson["key"] = str(archive.key())
     archiveJson["monthyear"] = str(archive.monthyear)
     archiveJson["weblogcount"] = archive.weblogcount
     archiveJson["date"] = archive.date.strftime('%m/%d/%y')
     return archiveJson
コード例 #22
0
ファイル: blog.py プロジェクト: yobin/saepy-log
    def get(self):
        try:
            objs = Article.get_post_for_homepage()
        except:
            self.redirect('/install')
            return
        if objs:
            if MYSQL_TO_KVDB_SUPPORT:
                fromid = objs[0]['id']
                endid = objs[-1]['id']
                #totalblog = Article.get_totalnum_arti()
                totalblog = get_count('Totalblog',NUM_SHARDS,0)
            else:
                fromid = objs[0].id
                endid = objs[-1].id
                totalblog = get_count('Totalblog',NUM_SHARDS,0)
        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"%(getAttr('SITE_TITLE'),getAttr('SITE_SUB_TITLE')),
            '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': 1,
            'allpage': allpage,
            'listtype': 'index',
            'fromid': fromid,
            'endid': endid,
            'comments': Comment.get_recent_comments(),
            'links':Link.get_all_links(),
            'isauthor':self.isAuthor(),
            'Totalblog':totalblog,
        },layout='_layout.html')
        self.write(output)
        return output
コード例 #23
0
ファイル: blog.py プロジェクト: yobin/saepy-log
    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
コード例 #24
0
ファイル: rpc.py プロジェクト: Git-Host/cpedialog
 def DeleteArchive(self,request):
     archive = Archive.get_by_id(int(request.get("id")))
     archive.delete()
     return True
コード例 #25
0
def index():
    return render_template('howmany.html', how_many = len(Archive.latest().members))
コード例 #26
0
ファイル: admin.py プロジェクト: honten/diary
 def get(self):
     archives = Archive.all().order("-date")
     template_values = {"archives": archives}
     self.generate("admin/admin_archives.html", template_values)
コード例 #27
0
ファイル: blog.py プロジェクト: yobin/saepy-log
    def get(self):
        try:
            objs = Article.get_post_for_homepage()
        except:
            self.redirect('/install')
            return
        if objs:
            if MYSQL_TO_KVDB_SUPPORT:
                fromid = objs[0]['id']
                endid = objs[-1]['id']
                #totalblog = Article.get_totalnum_arti()
                totalblog = get_count('Totalblog', NUM_SHARDS, 0)
            else:
                fromid = objs[0].id
                endid = objs[-1].id
                totalblog = get_count('Totalblog', NUM_SHARDS, 0)
        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" % (getAttr('SITE_TITLE'), getAttr('SITE_SUB_TITLE')),
            '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':
            1,
            'allpage':
            allpage,
            'listtype':
            'index',
            'fromid':
            fromid,
            'endid':
            endid,
            'comments':
            Comment.get_recent_comments(),
            'links':
            Link.get_all_links(),
            'isauthor':
            self.isAuthor(),
            'Totalblog':
            totalblog,
        },
                             layout='_layout.html')
        self.write(output)
        return output
コード例 #28
0
ファイル: admin.py プロジェクト: yobin/saepy-log
    def post(self):
        self.set_header('Content-Type', 'application/json')
        rspd = {'status': 201, 'msg': 'ok'}

        secret = self.get_argument("s", "")

        if secret <> getAttr('MOVE_SECRET'):
            user = False
            rspd['status'] = 403
            rspd['msg'] = 'secret code err.'
            self.write(json.dumps(rspd))
            return

        try:
            tf = {'true': 1, 'false': 0}
            timestamp = int(time())
            #print timestamp
            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", 'false'),
                'password': self.get_argument("p", ''),
                'add_time': self.get_argument("addtime", timestamp),
                'edit_time': self.get_argument("edit_time", timestamp),
                'archive': self.get_argument("archive", genArchive()),
                'pv': int(self.get_argument("pv", 0)),
            }
            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)
            print '====================='
            print post_dic['pv']
            post_dic['closecomment'] = tf[post_dic['closecomment'].lower()]
        except:
            rspd['status'] = 500
            rspd['msg'] = 'Para err.'
            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))
            Archive.add_postid_to_archive(post_dic['archive'], str(postid))
            keyname = 'pv_%s' % (str(postid))
            set_count(keyname, 0, post_dic['pv'])
            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'] = 'Unknown err.'
            self.write(json.dumps(rspd))
            return
コード例 #29
0
ファイル: admin.py プロジェクト: yobin/saepy-log
    def post(self):
        self.set_header("Content-Type", "application/json")
        rspd = {"status": 201, "msg": "ok"}

        secret = self.get_argument("s", "")

        if secret <> getAttr("MOVE_SECRET"):
            user = False
            rspd["status"] = 403
            rspd["msg"] = "secret code err."
            self.write(json.dumps(rspd))
            return

        try:
            tf = {"true": 1, "false": 0}
            timestamp = int(time())
            # print timestamp
            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", "false"),
                "password": self.get_argument("p", ""),
                "add_time": self.get_argument("addtime", timestamp),
                "edit_time": self.get_argument("edit_time", timestamp),
                "archive": self.get_argument("archive", genArchive()),
                "pv": int(self.get_argument("pv", 0)),
            }
            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)
            print "====================="
            print post_dic["pv"]
            post_dic["closecomment"] = tf[post_dic["closecomment"].lower()]
        except:
            rspd["status"] = 500
            rspd["msg"] = "Para err."
            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))
            Archive.add_postid_to_archive(post_dic["archive"], str(postid))
            keyname = "pv_%s" % (str(postid))
            set_count(keyname, 0, post_dic["pv"])
            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"] = "Unknown err."
            self.write(json.dumps(rspd))
            return
コード例 #30
0
ファイル: admin.py プロジェクト: yobin/saepy-log
    def post(self):
        self.set_header('Content-Type', 'application/json')
        rspd = {'status': 201, 'msg': 'ok'}

        try:
            tf = {'true': 1, 'false': 0}
            timestamp = int(time())
            content = self.get_argument("con")
            if getAttr('MARKDOWN'):
                #content = markdown.markdown(parse_text(content))
                content = content.encode("utf-8")
            post_dic = {
                'category': self.get_argument("cat"),
                'title': self.get_argument("tit"),
                'content': content,
                '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 MYSQL_TO_KVDB_SUPPORT:
                post_dic['comment_num'] = '0'

            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']), 'post_list_index',])
            clear_all_cache()  #yobin 20160921

            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
コード例 #31
0
ファイル: admin.py プロジェクト: Git-Host/cpedialog
 def get(self):
       archives = Archive.all().order('-date')
       template_values = {
         'archives':archives,
         }
       self.generate('admin/admin_archives.html',template_values)
コード例 #32
0
ファイル: blog.py プロジェクト: yobin/saepy-log
class PostDetail(BaseHandler):
    @pagecache('post', POST_CACHE_TIME, lambda self, id, title: id)
    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 Exception, e:
            print 'PostDetail()', e

        if MYSQL_TO_KVDB_SUPPORT:
            obj_slug = obj['slug']
            obj_absolute_url = obj['absolute_url']
            obj_password = obj['password']
            obj_last_modified = obj['last_modified']
            obj_title = obj['title']
            obj_keywords = obj['keywords']
            obj_description = obj['description']
            obj_coms = obj['coms']
        else:
            obj_slug = obj.slug
            obj_absolute_url = obj.absolute_url
            obj_password = obj.password
            obj_last_modified = obj.last_modified
            obj_title = obj.title
            obj_keywords = obj.keywords
            obj_description = obj.description
            obj_coms = obj.coms

        if title != obj_slug:
            #self.redirect(obj_absolute_url, 301)
            #return
            print title
            print obj_slug

        #
        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, '')
            if rp != obj_password:
                tmpl = '_pw'

        keyname = 'pv_%s' % (str(id))
        increment(str(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
コード例 #33
0
ファイル: admin.py プロジェクト: yangzilong1986/saepy-log
    def post(self):
        self.set_header('Content-Type','application/json')
        rspd = {'status': 201, 'msg':'ok'}

        secret = self.get_argument("s","")

        if secret <> getAttr('MOVE_SECRET'):
            user = False
            rspd['status'] = 403
            rspd['msg'] = 'secret code err.'
            self.write(json.dumps(rspd))
            return

        try:
            tf = {'true':1,'false':0}
            timestamp = int(time())
            #print timestamp
            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",'false'),
                'password': self.get_argument("p",''),
                'add_time': self.get_argument("addtime",timestamp),
                'edit_time': self.get_argument("edit_time",timestamp),
                'archive': self.get_argument("archive",genArchive()),
                'pv': int(self.get_argument("pv",0)),
            }
            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)
            print '====================='
            print post_dic['pv']
            post_dic['closecomment'] = tf[post_dic['closecomment'].lower()]
        except:
            rspd['status'] = 500
            rspd['msg'] = 'Para err.'
            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))
            Archive.add_postid_to_archive(post_dic['archive'], str(postid))
            keyname = 'pv_%s' % (str(postid))
            set_count(keyname,0,post_dic['pv'])
            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'] = 'Unknown err.'
            self.write(json.dumps(rspd))
            return
コード例 #34
0
ファイル: admin.py プロジェクト: yobin/saepy-log
    def post(self):
        self.set_header("Content-Type", "application/json")
        rspd = {"status": 201, "msg": "ok"}

        try:
            tf = {"true": 1, "false": 0}
            timestamp = int(time())
            content = self.get_argument("con")
            if getAttr("MARKDOWN"):
                # content = markdown.markdown(parse_text(content))
                content = content.encode("utf-8")
            post_dic = {
                "category": self.get_argument("cat"),
                "title": self.get_argument("tit"),
                "content": content,
                "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 MYSQL_TO_KVDB_SUPPORT:
                post_dic["comment_num"] = "0"

            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']), 'post_list_index',])
            clear_all_cache()  # yobin 20160921

            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