Ejemplo n.º 1
0
 def save_model(self, request, obj, form, change):
     obj.creator_name = request.user.username
     obj.creator_id = request.user.id
     obj.disabled = "N"
     if not change:
         obj.archive_date = time.strftime("%Y年%m月", time.localtime())
     if obj.content.find("</p>") == -1:
         obj.short_content = obj.content
     else:
         obj.short_content = obj.content[: obj.content.find("</p>") + 4]
     obj.save()
     if not change:
         category = obj.category
         category.id_num = category.id_num + 1
         category.save()
         acount = Archive.objects.filter(
             creator_name=request.user.username, archive_date=obj.archive_date, disabled="N"
         ).count()
         if acount == 0:
             archive = Archive()
             archive.archive_date = obj.archive_date
             archive.archive_num = 1
             archive.creator_id = request.user.id
             archive.creator_name = request.user.username
             archive.disabled = "N"
         else:
             archive = Archive.objects.filter(
                 creator_name=request.user.username, archive_date=obj.archive_date, disabled="N"
             )[0]
             archive.archive_num = archive.archive_num + 1
         archive.save()
Ejemplo n.º 2
0
    def save(self):
        if self.obj is None:
            post = Post()
        else:
            post = self.obj

        # make slug
        title = self.title.data
        if (self.slug.data is None) or (self.slug.data.strip()
                                        == "") or (self.slug.data.strip()
                                                   == u""):
            slug = pretty_slug(title)
        else:
            slug = slugify(self.slug.data.strip())

        # category
        if (self.category.data.strip() is "") or (self.category.data.strip() is
                                                  u""):
            category = None
        else:
            category = ndb.Key(urlsafe=self.category.data.strip())

        # tag
        tag = []
        for word in self.tag.data.split(","):
            word = word.strip()
            if not word == "":
                t = Tag(id=pretty_slug(word).lower())
                t.title = word
                key = t.put()
                tag.append(key)

        t = datetime.now()
        archive = Archive(id=t.strftime("%Y_%m"))
        archive.time = date(year=t.year, month=t.month, day=1)
        archive_key = archive.put()

        post.title = title
        post.slug = slug
        post.text = self.text.data

        post.category = category
        post.tag = tag
        post.archive = archive_key

        post.order = self.order.data
        post.status = self.status.data
        post.allowComment = self.allowComment.data
        post.allowPing = self.allowPing.data
        post.allowFeed = self.allowFeed.data

        post.put()
        app.config["LATEST"] = datetime.now()
Ejemplo n.º 3
0
    def full_archive(self, activity, delete_after_saved=False):
        pk = activity.id
        REDIS_KEY_RUN = 'game:{}:run'.format(pk)
        REDIS_KEY_START = 'game:{}:start'.format(pk)
        REDIS_KEY_END = 'game:{}:end'.format(pk)
        REDIS_KEY_USER = '******'.format(pk)
        REDIS_KEY_FINAL = 'game:{}:final'.format(pk)

        records = []
        runs = self.redis.hgetall(REDIS_KEY_RUN)
        starts = self.redis.hgetall(REDIS_KEY_START)
        ends = self.redis.hgetall(REDIS_KEY_END)
        users = self.redis.hgetall(REDIS_KEY_USER)
        scores = self.redis.hgetall(REDIS_KEY_FINAL)
        for run_id, uid in iteritems(runs):
            record = {
                'run_id': run_id,
                'uid': uid,
                'start': starts.get(run_id),
                'end': ends.get(run_id),
                'game': pk
            }
            user = users.get(uid)
            if user:
                userinfo = json.loads(user)
            else:
                userinfo = {}
            record.update({
                'info_field_1': userinfo.get('info_field_1'),
                'info_field_2': userinfo.get('info_field_2'),
                'info_field_3': userinfo.get('info_field_3')
            })
            score = scores.get(run_id, 0)
            record.update({'score': int(score)})
            records.append(record)

        if records:
            records = sorted(records, key=lambda r: r.get('score'), reverse=True)
            Archive.delete().where(Archive.game == activity).execute()
            with db.database.atomic():
                for idx in range(0, len(records), 100):
                    Archive.insert_many(records[idx:idx + 100]).execute()

        if delete_after_saved:
            self.redis.delete(REDIS_KEY_RUN)
            self.redis.delete(REDIS_KEY_START)
            self.redis.delete(REDIS_KEY_END)
            self.redis.delete(REDIS_KEY_USER)
            self.redis.delete(REDIS_KEY_FINAL)
Ejemplo n.º 4
0
def archive_processor():
    if app.config["SITE_SIDEBAR_SHOW_ARCHIVE"]:
        mem = memcache.get('ARCHIVES')
        if mem is None:
            archives = []
            for archive in Archive.query().order(Archive.time).fetch():
                archives.append({
                    "post_count":
                    archive.post_count,
                    "year":
                    archive.time.strftime("%Y"),
                    "month":
                    archive.time.strftime("%m"),
                    "format_time":
                    archive.time.strftime(
                        app.config["SITE_SIDEBAR_ARCHIVE_DATE_FORMAT"])
                })
            memcache.add(key="ARCHIVES",
                         value=json.dumps(archives, encoding="utf-8"),
                         time=app.config["SITE_MEMCACHED_TIME"])
        else:
            archives = json.loads(mem, encoding="utf-8")
    else:
        archives = []
    return dict(archives=archives)
Ejemplo n.º 5
0
def store_archive_info(url, timestamp, archive_folder, token):
    ''' Stores details about an archived repository into the archive table if not exists.
	Returns None if invalid github slug '''
    slug = re.sub(r"http(s)?://github\.com/", '', url).replace('.git',
                                                               '').strip()

    try:
        owner, name = slug.split('/')
    except ValueError:
        return None

    language = get_repo_language(slug, token)

    relative_folder = os.path.join(*archive_folder.rsplit(
        os.path.sep, 3)[-3:])  # last 3 parts of archive path
    relative_folder = os.path.join(
        relative_folder, str(timestamp))  # last 3 parts of archive path

    exists = db.session.query(Archive).filter_by(
        archive_folder=archive_folder).first()
    if not exists:
        archive = Archive(url=url, name=name, owner=owner, github_slug=slug, \
         language=language, timestamp=str(timestamp), archive_folder=relative_folder)
        db.session.add(archive)

    db.session.commit()
    return slug
Ejemplo n.º 6
0
def archive_metadata(sc_id, metafile):
    # cd_tree: coverage description tree extracted from the
    #          metadata XML file
    cd_tree = base_xml_parse(metafile, True)
    wcseo_type = determine_wcseo_type(cd_tree)

    coverage_id = extract_eoid(cd_tree, wcseo_type)

    if IE_DEBUG > 1:
        logger.info("Sc_id " + ` sc_id ` + ": Archiving meta for " +
                    ` cd_tree.tag ` + ", cid='" + coverage_id + "'.")

    cd_tree = None

    scenario = Scenario.objects.get(id=int(sc_id))

    archive_record = Archive(scenario=scenario, eoid=coverage_id)

    archive_record.save()

    return True
Ejemplo n.º 7
0
def delete(request, key):
    if not admin():
        return HttpResponseRedirect(users.create_login_url("/blogs"))
    blog = Blog.get(key)
    Comment.batch_delete(blog.comment_set)
    archive = Archive.all().filter("year", blog.year).filter("month", blog.month).fetch(1)
    archive[0].weblog_count -= 1
    archive[0].put()
    if archive[0].weblog_count == 0:
        archive[0].delete()
    blog.delete()
    if blog.category and blog.category.blog_set.count() == 0:
        blog.category.delete()
    return HttpResponseRedirect("/blogs")
Ejemplo n.º 8
0
def archive_metadata(sc_id, metafile):
    # cd_tree: coverage description tree extracted from the
    #          metadata XML file
    cd_tree = base_xml_parse(metafile, True)
    wcseo_type = determine_wcseo_type(cd_tree)

    coverage_id = extract_eoid(cd_tree, wcseo_type)

    if IE_DEBUG > 1:
        logger.info("Sc_id " + `sc_id` + ": Archiving meta for " + `cd_tree.tag`+
                    ", cid='"+coverage_id+"'.")

    cd_tree = None

    scenario = Scenario.objects.get(id=int(sc_id))

    archive_record = Archive(
        scenario = scenario,
        eoid     = coverage_id)

    archive_record.save()

    return True
Ejemplo n.º 9
0
def archive():
    title = request.args.get('title', None)
    url = request.args.get('url', None)

    archived = Archive.query.filter_by(article_link=url).first()
    if archived:
        flash('Article already archived')
        return redirect(url_for('archives'))

    new_archive = Archive(user_id=current_user.id,
                          article_title=title,
                          article_link=url)
    db.session.add(new_archive)
    db.session.commit()
    return redirect(url_for('archives'))
Ejemplo n.º 10
0
def base_context():
    context = Context({
        'current_user':current_user(),
        'admin':admin(),
        'login_url':users.create_login_url('/blogs'),
        'logout_url':users.create_logout_url('/blogs'),
        'recent_comments':Comment.all().order('-date').fetch(5),
        'categories':Category.all(),
        'blogs_count':Blog.all().count(),
        'archives':Archive.all().order('-year').order('-month'),
        'friendlyURLs':FriendlyURL.all()
    })
    configuration=Configuration.all().fetch(1)
    if configuration:
        context.configuration=configuration[0]
    return context
Ejemplo n.º 11
0
def base_context():
    context = Context(
        {
            "current_user": current_user(),
            "admin": admin(),
            "login_url": users.create_login_url("/blogs"),
            "logout_url": users.create_logout_url("/blogs"),
            "recent_comments": Comment.all().order("-date").fetch(5),
            "categories": Category.all(),
            "blogs_count": Blog.all().count(),
            "archives": Archive.all().order("-year").order("-month"),
            "friendlyURLs": FriendlyURL.all(),
        }
    )
    configuration = Configuration.all().fetch(1)
    if configuration:
        context.configuration = configuration[0]
    else:
        context.configuration = False
    return context
Ejemplo n.º 12
0
def archive(year, month):
    a = Archive.query(Archive.time == date(year=int(year), month=int(month), day=1)).get()
    posts = Post.query(Post.archive == a.key, Post.status == Post.STATUS_PUBLISHED).order(-Post.modified).fetch()
    return render_template('archive.html', posts=posts, archive=a)