Example #1
0
def edit_post(id):

    form = PostForm()
    if users.is_current_user_admin() and form.validate_on_submit():
        try:
            tags = Tags()

            categories = Categories()

            updating_post = BlogPost.get(int(id))

            title = request.json['title']
            body = request.json['body']
            raw_category = request.json['category']
            editing_tags = request.json['tags']
            raw_summary = request.json['summary']

            tags_keys = tags.update(editing_tags, updating_post)

            category_key = categories.update(raw_category,
                                             updating_post.category)

            updating_post.edit(title,
                               body,
                               datetime.now(),
                               tags_keys,
                               category_key,
                               raw_summary,
                               raw_answers=request.json['answers'])
        except AttributeError:
            abort(500)

        return jsonify(updating_post.to_json())  # dangerous
Example #2
0
def api_modify_blog(blog_id):
    check_admin()
    blog = Blogs.get(blog_id)
    if not blog:
        raise APIValueError(blog_id, 'blog is not exist.')
    i= ctx.request.input(title='', tags='', content='')
    title = i['title'].strip()
    tags = i['tags'].strip()
    content = i['content'].strip()
    if not title:
        raise APIValueError('title', 'title can not be empty.')
    if not content:
        raise APIValueError('content', 'content can not be empty.')
    summary = _get_summary(content)
    blog.title = title
    blog.summary = summary
    blog.content = content
    blog.tags = tags
    blog.update()
    db.execute('delete from `tags` where `blog`=?', blog_id)
    if tags:
        for tag in tags.split(','):
            tag = Tags(tag=tag, blog=blog_id)
            tag.insert()
    return dict(id=blog_id)
Example #3
0
async def album_process(event):
    msg_caption = None

    for message in event.messages:
        if not util.check_tags(message):
            continue
        else:
            msg_caption = message
            break

    if not msg_caption:
        return

    response = await boards.new_card(**util.extract_card_info(msg_caption))

    Tags.create(chat_id=event.chat_id,
                message_id=msg_caption.id,
                user_id=event.from_id,
                card_id=response['id'],
                short_url=response['shortUrl'])

    logging.info(
        f"{event.from_id} uploaded a new issue {response['shortUrl']} " +
        "with Photo Album")

    for message in event.messages:
        if not util.check_media(message):
            return

        stream = await message.download_media(file=bytes)

        await boards.attach_card(response['id'], stream,
                                 str(message.id) + message.file.ext,
                                 message.file.mime_type)
Example #4
0
def formCreateDish():
    tags = Tags()
    allTags = tags.list_tags()
    countTags = len(allTags)
    return render_template('formCreateDish.html',
                           tags=allTags,
                           countTags=countTags)
Example #5
0
def edit_post(id):

    form = PostForm()
    if users.is_current_user_admin() and form.validate_on_submit():

        tags = Tags()

        categories = Categories()

        updating_post = BlogPost.get(int(id))

        title = request.json['title']
        body = request.json['body']
        raw_category = request.json['category']
        editing_tags = request.json['tags']
        raw_summary = request.json['summary']

        tags_keys = tags.update(editing_tags, updating_post)

        category_key = categories.update(raw_category, updating_post.category)

        updating_post.edit(title, body, datetime.now(), tags_keys,
                           category_key, raw_summary, raw_answers=request.json['answers'])

        return jsonify(updating_post.to_json())  # dangerous
Example #6
0
File: views.py Project: qiankai/cms
def insert(request):
    status = None
    if request.method == 'POST':
        # save new post
        Usr_Name = request.POST.get('name', '')
        Usr_Mobile = request.POST.get('mobile', '')
        Usr_Remark = request.POST.get('remark', '')
        tags = request.POST.get('tags', '')
        pre_id = request.POST.get('pre_id', '')
        p_uuid = uuid.uuid1()
        p = People(
            Usr_Name=Usr_Name,
            Usr_Mobile=Usr_Mobile,
            Usr_Remark=Usr_Remark,
            active=0,
            isdel=0,
            uuid=p_uuid,
        )
        p.save()

        for tag in tags.replace(u',', ',').split(','):
            try:
                t = Tags.objects.get(tag=tag)
            except Tags.DoesNotExist:
                newtag = Tags(tag=tag)
                newtag.save()
                p.tags.add(newtag)
                p.save()
            else:
                p.tags.add(t)
                p.save()
        if request.user.is_superuser:
            status = "ok"
            p.Cluster_id = 0
            p.save()
            return render_to_response('usernet/index.html', {
                'status': status,
            },
                                      context_instance=RequestContext(request))
        if pre_id == '':
            pre_id = request.user
        if pre_id != '':
            try:
                pre = People.objects.filter(Usr_Mobile=pre_id, active=1)
            except People.DoesNotExist:
                print "error"
            else:
                p.Prev_Usr = pre[0]
                p.Cluster_id = pre[0].Cluster_id
                p.save()
        status = "ok"
    # Get all posts from DB
    return render_to_response('usernet/index.html', {
        'status': status,
    },
                              context_instance=RequestContext(request))
Example #7
0
def next():
    if request.method == "POST":
        # TODO: helper
        tags = set(map(unicode.lower, request.form.getlist("tags")))

        Cluster.objects(pk=request.form["_id"]).update_one(
            push__tags=ShredTags(
                user=g.user.id,
                tags=list(tags),
                recognizable_chars=request.form.get("recognizable_chars", ""),
                angle=int(request.form.get("angle", 0))),
            inc__users_count=1,
            add_to_set__users_processed=g.user.id)

        User.objects(pk=g.user.id).update_one(
            inc__processed=1, inc__tags_count=len(tags),
            add_to_set__tags=list(tags))

        session["processed"] = session.get("processed", 0) + 1

        for tag in tags:
            Tags.objects(pk=tag).update_one(
                set_on_insert__is_base=False,
                set_on_insert__created_by=g.user.id,
                set_on_insert__created_at=Tags().created_at,
                inc__usages=1,
                add_to_set__shreds=request.form["_id"],
                upsert=True)

        start = datetime.strptime(request.form["tagging_start"],
                                  '%Y-%m-%d %H:%M:%S.%f')
        end = datetime.utcnow()
        TaggingSpeed.objects.create(
            user=g.user.id,
            cluster=request.form["_id"],
            tags_count=len(tags),
            msec=(end - start).total_seconds() * 1000)

    cluster = Cluster.next_for_user(g.user, app.config['USERS_PER_SHRED'])

    auto_tags = cluster and cluster.get_auto_tags() or []
    return render_template(
        "_shred.html",
        cluster=cluster,
        auto_tags=auto_tags,
        all_tags=get_tags(),
        tagging_start=datetime.utcnow(),

        # TODO: move to context processor
        processed_per_session=session.get("processed", 0),
        processed_total=User.objects(id=g.user.id).first()["processed"],
        rating=list(User.objects.order_by(
            "-processed").values_list("id")).index(g.user.id) + 1
    )
Example #8
0
def tag_add():
    input_list = request.form.getlist('create_tag')

    if input_list[0] != '':
        tag = Tags(tag=input_list[0])
    else:
        return redirect("/tags")

    post_ids = [int(num) for num in input_list[1:] if num != '']
    tag.posts = Posts.query.filter(Posts.id.in_(post_ids)).all()

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

    return redirect("/tags")
Example #9
0
def deleteTag():
    tags = Tags()
    params = {}
    if request:
        # params["tag"] = request.args.get('tag', '')
        params['tag_id'] = request.args.get('tag_id', '')
        print(params)
        tags.delete_tag(params)
        tags.__del__
        del (tags)
        # return redirect(url_for('getTags'), msg='Tag created')
        return redirect(url_for('getTags'))
        # return "{0}".format(params)
    else:
        return "Fehler"
def registerTag(requestjson, created_by):
    """create a new user"""
    new_Tags = requestjson
    if len(created_by) > 30:
        user = Operator.verify_auth_token(created_by)
        created_by = user.get().clean_data()['email']
    # TODO: get authenticated operator and assignee to new Tags
    # new_Tags["created_by"] = authenticated_oprator
    try:
        new_Tags['created_by'] = created_by  #g.user.get().clean_data()['_id']
        comment = Tags(**new_Tags)
        comment.save()
        return jsonify({"response": "success", 'user': comment.clean_data()})
    except Exception as error:
        return jsonify({"error": str(error)}), 400
Example #11
0
def formEditDish():
    """ Zeigt ein Formular zur bearbeitung eines Gerichts an. Parameter: dish_id """

    # Abfragen, ob Daten übergeben wurden
    if request:
        dish_id = request.args.get('dish_id', '')
    else:
        return "Error"

    # Falls dish_id als String übergeben wurde -> in Integer umwandeln

    if type(dish_id) == str:
        dish_id = int(dish_id)

    # Gericht & Tags mit Namen laden
    dishes = Dishes()
    dish = dishes.getDish(dish_id)[0]
    taggedDishes = TaggedDishes()
    tag_for_dish = taggedDishes.list_with_names(dish['dish_id'])
    dish['tags'] = tag_for_dish

    # Allgemeine Tags laden
    tags = Tags()
    allTags = tags.list_tags()
    countTags = len(allTags)

    # Zutaten für das Gericht laden
    ingredientsAll = Ingredients()
    ingredients = ingredientsAll.list(dish_id)

    # Alle Namen und Einheiten der Zutaten laden
    suggestions = ingredientsAll.get_suggestions()
    # print(suggestions)

    # Tags selektieren
    for index in range(len(allTags)):
        for tag2 in tag_for_dish:
            if allTags[index]['tag_id'] == tag2['tag_id']:
                allTags[index]['selected'] = " selected"

    # Template füllen und zurückgeben
    return render_template('formEditDish.html',
                           allTags=allTags,
                           countTags=countTags,
                           dish=dish,
                           ingredients=ingredients,
                           ingredientsCount=len(ingredients),
                           suggestions=suggestions)
Example #12
0
def main():

    if users.is_current_user_admin():
        if request.method == 'GET':  #all entitites
            posts = Posts()

            return jsonify(posts.to_json())

        elif request.method == "POST":

            form = PostForm()
            if form.validate_on_submit():  #new entity
                posts = Posts()
                categories = Categories()
                tags = Tags()

                raw_post = request.get_json()
                raw_category = raw_post["category"]
                editing_tags = raw_post["tags"]
                raw_summary = raw_post["summary"]

                tag_keys = tags.update(editing_tags)
                category_key = categories.update(raw_category)

                post_id = posts.add(raw_title=raw_post["title"],
                                    raw_body=raw_post["body"],
                                    category_key=category_key,
                                    tags_ids=tag_keys,
                                    summary=raw_summary,
                                    answers=raw_post["answers"]).id()
                post = BlogPost.get(post_id)
                if "images" in raw_post.keys() and raw_post["images"]:
                    for img in raw_post["images"]:
                        image_base64 = img["url"].split("base64,")[-1]
                        mime_type = img["url"].split("base64,")[0].replace(
                            'data:', '').replace(';', '')
                        image_filename = img["filename"].split("\\")[-1]

                        if allowed_file(image_filename):
                            image_filename = secure_filename(image_filename)
                            post.add_blob(base64.b64decode(image_base64),
                                          image_filename, mime_type)

                return jsonify(post.to_json())  #  Needs check
            else:
                return jsonify(msg="missing token")
    else:
        return jsonify({})
Example #13
0
def api_edit_blog(request, *, id, name, description, summary, content,
                  category_id, tags):
    check_admin(request)
    if not name or not name.strip():
        raise APIValueError('name', 'name can not be empty')
    if not summary or not summary.strip():
        raise APIValueError('summary', 'summary can not be empty')
    if not content or not content.strip():
        raise APIValueError('content', 'content can not 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())
    blog = yield from Blog.find(id)
    if not blog:
        raise APIValueError('id', 'request path error, id : {}'.format(id))

    category = yield from Category.find(category_id)
    if category:
        #raise APIValueError('category', 'can not find category, category_id:{}'.format(category_id))
        category_id = category.id
        category_name = category.name
    else:
        category_name = ''

    tag_ids = []
    if len(tags) > 0:
        for tag in tags:
            if tag["key"]:
                rs = yield from Tags.find(tag["key"])
                if rs:
                    tag_ids.append(rs.id)
            else:
                rs = yield from Tags.find_all("name=?", [tag["value"]])
                if len(rs) > 0:
                    tag_ids.append(rs[0].id)
                else:  #create new tag
                    tag = Tags(name=tag["value"])
                    rows, lastrowid = yield from tag.save()
                    tag_ids.append(lastrowid)

    blog.name = name
    blog.description = description
    blog.summary = summary
    blog.content = content
    blog.category_id = category_id
    blog.category_name = category_name
    blog.tags = ",".join([str(id) for id in tag_ids])
    blog.updated_at = time.time()
    yield from blog.update()
    return blog
Example #14
0
def create_tag():
    tags = Tags()
    params = {}
    if request:
        params["tag"] = request.args.get('tag', '')
        if len(params["tag"]) == 0:
            return redirect(url_for('getTags'))

        tag_id = tags.create_tag(params)
        print(tag_id)
        # return "yay {0}".format(params["tag"])
        # return redirect(url_for('getTags', msg='Tag {0} wurde hinzugefügt.'.format(params['name'])))
        return redirect(url_for('getTags'))
    else:
        return "Fehler"
    return "Fehler"
Example #15
0
def submit_tag_form():
    tag_name = request.form["tag_name"]
    new_tag = Tags(name=tag_name)
    db.session.add(new_tag)
    db.session.commit()

    return redirect('/tags')
Example #16
0
def make_posts():
    if request.method == "GET":
        user = g.user.nickname
        email = g.user.email
        image = g.user.image
        user_id = g.user.id
        return render_template('make_posts.html',
                               user=user,
                               email=email,
                               image=image,
                               id=user_id)
    elif request.method == "POST":
        content = request.form["post_content"]
        user_id = request.form['id']
        list_of_tags = json.loads(request.form['tags'])
        list_of_tags.append(
            user_id)  # little hacky way, doing because of shortage of time
        # first insert the post, get the post id and then insert in the tag table
        post_obj = Posts(post_content=content,
                         source_user=user_id,
                         created_at=datetime.datetime.now())
        db.session.add(post_obj)
    db.session.commit()

    post_id = post_obj.id
    # now make tags
    for tag in list_of_tags:
        tag_obj = Tags(source_user=user_id, end_user=tag, post_id=post_id)
        db.session.add(tag_obj)
        db.session.commit()
    return "Success"
Example #17
0
def tags_cloud():
    '''Get dict of tags, numbers.'''
    tags = Tags.all()
    tags_dict = []
    for tag in tags:
        tags_dict.append({'name': tag.name, 'size': tag.count * 10})
    return tags_dict
Example #18
0
def get_tag_synonyms():
    mapping = {}
    for t in Tags.objects(synonyms__exists=True):
        for s in t["synonyms"]:
            mapping[s] = t["title"]

    return mapping
Example #19
0
def request_json(**kwargs):
    if request.json:
        global r
        r = Resource()
        for k, v in kwargs.iteritems():
            r.rid = v  # Now automatically updated
        r.title = request.json['title']
        r.link = str(request.json['link'])
        # Insert Tags to Tags Object
        r.tags = []
        for item in request.json['tags']:
            t = Tags()
            t.tag_name = item['tag_name']
            r.tags.append(t)
        r.description = request.json['description']
        r.save(upsert=True)
Example #20
0
    def _blog_fetch_callback(self, rpc):

        content = rpc.get_result().content
        d = feedparser.parse(StringIO(content))
        s = Signatures.get_single()
        signatures_and_times = dict(zip(s.hashes, s.times))
        posts = []

        tags_entity = Tags.get_single()
        tags = set(tags_entity.available)

        for entry in d['entries']:
            blog_post = BlogPost.blog_post_from_feed_entry(entry)
            signature_time = signatures_and_times.get(blog_post.signature)
            if signature_time:
                signature_time = datetime.datetime.fromtimestamp(signature_time).strftime('%m/%d/%Y %H:%M')
            posts.append((blog_post, signature_time))

            for tag in blog_post.tags:
                tags.add(tag.lower())

        template_values = {"posts":posts}

        tags_entity.available = list(tags)
        tags_entity.save()

        template = jinja_environment.get_template('moderate.html')
        self.response.out.write(template.render(template_values))
Example #21
0
 def get(self):
     feed = Feeds.get_by_id(int(self.request.get('feed')))
     tag  = Tags.get_by_id(int(self.request.get('tag')))
     if users.get_current_user() == feed.user:
         feed.tags.remove(tag.key)
         feed.put()
     self.redirect(self.request.referer) 
Example #22
0
def request_json(**kwargs):
    if request.json:
        global r
        r = Resource()
        for k, v in kwargs.iteritems():
            r.rid = v  # Now automatically updated
        r.title = request.json['title']
        r.link = str(request.json['link'])
        # Insert Tags to Tags Object
        r.tags = []
        for item in request.json['tags']:
            t = Tags()
            t.tag_name = item['tag_name']
            r.tags.append(t)
        r.description = request.json['description']
        r.save(upsert=True)
Example #23
0
def edit(article_id):
    user_id=flask.session.get('id')
    if user_id:
        article=Articles.query.filter(Articles.id==article_id).first()
        tag=Tags.query.filter(Tags.id==article.tag_id).first()
        if flask.request.method=='GET':
            context={
                'article': article,
                'tag':tag
            }
            print(article.content)
            return flask.render_template('edit.html',**context)
        else:
            title=flask.request.form.get('title')
            content=flask.request.form.get('content')
            tagname=flask.request.form.get('tagname')
            id = flask.request.form.get('id')
            tag=Tags.query.filter(Tags.tagname==tagname).first()
            if tag:
                tag_id=tag.id
            else:
                tag=Tags(tagname=tagname)
                db.session.add(tag)
                db.session.commit()
                tag_id=Tags.query.filter(Tags.tagname==tagname).first().id
            article.id=id
            article.title=title
            article.content=content
            article.tag_id=tag_id
            db.session.commit()
            return flask.redirect(flask.url_for('index'))
    else:
        return flask.redirect(flask.url_for('login'))
Example #24
0
def addTags():
    from models import User, Tags, db
    user = User.query.filter_by(email=session.get('emailId')).first_or_404()
    print(user.email)
    tag = request.form['done_btn1']

    print(tag.split(","))
    tags = tag.split(",")
    for tag in tags:
        db.session.add(Tags(tag_name=tag, user=user))
    db.session.commit()
    userTags1 = user.tags.all()

    for usertags in userTags1:
        print(usertags.tag_name + ", ")

    people = []
    for user1 in User.query.all():
        if user1.email != user.email:
            people.append(user1)

    return render_template('tagsAdded.html',
                           user=user,
                           tagsAdded=userTags1,
                           people=people)
Example #25
0
def tags_cloud():
    '''Get dict of tags, numbers.'''
    tags = Tags.all()
    tags_dict = []
    for tag in tags:
        tags_dict.append({'name': tag.name, 'size': tag.count * 10})
    return tags_dict
Example #26
0
def get_tag_synonyms():
    mapping = {}
    for t in Tags.objects(synonyms__exists=True):
        for s in t["synonyms"]:
            mapping[s] = t["title"]

    return mapping
    def run(self):
        headers = [
            self.FIELD_TITLE[f] if f in self.FIELD_TITLE else f
            for f in self.FIELDS
        ]
        rows = [headers]

        for user in Beneficiary.objects().order_by('+last_name', '+first_name',
                                                   '-age'):
            row = []
            for field in self.FIELDS:
                value = getattr(user, field)
                if field in self.tag2v.keys():
                    if ObjectId.is_valid(value):
                        tg = Tags.objects(id=value)
                        if tg:
                            row.append(tg.get().clean_data()['ro'])
                        else:
                            row.append(value)
                    else:
                        row.append(value)
                elif isinstance(value, bool):
                    row.append(1 if value else 0)
                else:
                    row.append(value)
            rows.append(row)

        return rows
Example #28
0
def next():
    if request.method == "POST":
        tags = set(map(unicode.lower, request.form.getlist("tags")))
        Shreds.objects(pk=request.form["_id"]).update_one(
            push__tags=ShredTags(user=g.user.id, tags=list(tags),
                                 recognizable_chars=request.form
                                 .get("recognizable_chars", "")),
            inc__users_count=1,
            add_to_set__summarized_tags=list(tags),
            add_to_set__users_processed=g.user.id)

        User.objects(pk=g.user.id).update_one(
            inc__processed=1, inc__tags_count=len(tags),
            add_to_set__tags=list(tags))

        session["processed"] = session.get("processed", 0) + 1

        for tag in tags:
            Tags.objects(pk=tag.capitalize()).update_one(
                set_on_insert__is_base=False,
                set_on_insert__created_by=g.user.id,
                set_on_insert__created_at=Tags().created_at,
                inc__usages=1,
                add_to_set__shreds=request.form["_id"],
                upsert=True)

        start = datetime.strptime(request.form["tagging_start"],
                                  '%Y-%m-%d %H:%M:%S.%f')
        end = datetime.utcnow()
        TaggingSpeed.objects.create(
            user=g.user.id,
            shred=request.form["_id"],
            tags_count=len(tags),
            msec=(end - start).total_seconds() * 1000)

    shred = get_next_shred()
    return render_template("shred.html",
                           shred=shred,
                           auto_tags=get_auto_tags(shred),
                           all_tags=get_tags(),
                           tagging_start=datetime.utcnow(),
                           processed_per_session=session.get("processed", 0),
                           processed_total=User.objects(id=g.user.id)\
                                .first()["processed"],
                           rating=list(User.objects.order_by("-processed")\
                                .values_list("id")).index(g.user.id) + 1
                           )
Example #29
0
File: views.py Project: qiankai/cms
def update(request):
    if request.method == 'GET':
        pid = request.GET.get('id')
        p = People.objects.get(id=pid)
        tags = p.tags.all()
        tag = []
        ta = ''
        for i in tags:
            tag.append(i.tag)
            ta = ta + i.tag + ','
        return render_to_response('usernet/update.html', {
            'person': p,
            'tags': tag,
            'ta': ta,
        },
                                  context_instance=RequestContext(request))
    if request.method == 'POST':
        pid = request.POST.get('id')
        Usr_Name = request.POST.get('name', '')
        Usr_Mobile = request.POST.get('mobile', '')
        Usr_Remark = request.POST.get('remark', '')
        tags = request.POST.get('tags', '')
        pre_id = request.POST.get('pre_id', '')

        p = People.objects.get(id=pid)
        p.Usr_Name = Usr_Name
        p.Usr_Mobile = Usr_Mobile
        p.Usr_Remark = Usr_Remark
        for tag in tags.replace(u',', ',').split(','):
            try:
                t = Tags.objects.get(tag=tag)
            except Tags.DoesNotExist:
                newtag = Tags(tag=tag)
                newtag.save()
                p.tags.add(newtag)
                p.save()
            else:
                p.tags.add(t)
                p.save()

        status = "Update " + p.Usr_Name + " successfully!"
        status_code = 1
        return render_to_response('usernet/message.html', {
            'status': status,
            'status_code': status_code,
        },
                                  context_instance=RequestContext(request))
Example #30
0
def getTags():
    has_message = False
    if request:
        if request.args.get('msg', ''):
            has_message = request.args.get('msg', '')
        # return redirect(url_for('listDishes'))
    else:
        has_message = False
        return "Fehler! <br /><a href\"" + url_for(
            'listDishes') + "\">Liste</a>"
    tags = Tags()
    allTags = tags.list_tags()
    # if len(allTags) > 0:
    #     for tag in allTags:
    #         print(tag)

    return render_template('tags.html', tags=allTags, has_message=has_message)
Example #31
0
def api_get_blog(*, id):
    blog = yield from Blog.find(id)

    tags = []
    if blog.tags:
        for tag_id in blog.tags.split(","):
            tag = yield from Tags.find(tag_id)
            if tag:
                tags.append({"key": tag.id, "value": tag.name})

    blog.tags = tags
    blog.alltags = [{
        "key": tag.id,
        "value": tag.name
    } for tag in (yield from Tags.find_all())]

    return blog
Example #32
0
File: views.py Project: qiankai/cms
def insert(request):
    status=None
    if request.method == 'POST':
       # save new post
       Usr_Name = request.POST.get('name','')
       Usr_Mobile = request.POST.get('mobile','')
       Usr_Remark = request.POST.get('remark','')
       tags = request.POST.get('tags','')
       pre_id = request.POST.get('pre_id','')
       p_uuid = uuid.uuid1()
       p = People(Usr_Name = Usr_Name,Usr_Mobile = Usr_Mobile,Usr_Remark=Usr_Remark,active = 0,isdel = 0,uuid = p_uuid,)
       p.save()

       for tag in tags.replace(u',',',').split(','):
           try:
               t = Tags.objects.get(tag = tag)
           except Tags.DoesNotExist:
               newtag = Tags(tag=tag)
               newtag.save()
               p.tags.add(newtag)
               p.save()
           else:
               p.tags.add(t)
               p.save()
       if request.user.is_superuser:
           status="ok"
           p.Cluster_id = 0
           p.save()
           return render_to_response('usernet/index.html', {'status':status,},
                              context_instance=RequestContext(request))
       if pre_id =='':
           pre_id = request.user
       if pre_id != '':
           try:
               pre = People.objects.filter(Usr_Mobile = pre_id,active = 1)
           except People.DoesNotExist:
               print "error"
           else:
               p.Prev_Usr=pre[0]
               p.Cluster_id = pre[0].Cluster_id
               p.save()
       status="ok"
    # Get all posts from DB
    return render_to_response('usernet/index.html', {'status':status,},
                              context_instance=RequestContext(request))
Example #33
0
def api_create_blog():
    check_admin()
    i= ctx.request.input(title='', tags='', content='')
    title = i['title'].strip()
    tags = i['tags'].strip()
    content = i['content'].strip()
    if not title:
        raise APIValueError('title', 'title can not be empty.')
    if not content:
        raise APIValueError('content', 'content can not be empty.')
    summary = _get_summary(content)
    blog = Blogs(title=title, tags=tags, summary=summary, content=content)
    id = blog.insert_id()
    if tags:
        for tag in tags.split(','):
            tag = Tags(tag=tag, blog=id)
            tag.insert()
    return dict(id=id)
Example #34
0
def index(*, page='1'):
    '''
    summary = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'
    blogs = [
        Blog(id='1', name='Test blog', summary = summary, created_at = time.time()-120),
        Blog(id='2', name='Javascript IT', summary = summary, created_at = time.time()-3600),
        Blog(id='3', name='Learn Swift', summary = summary, created_at = time.time()-7200),
        Blog(id='4', name='Test blog', summary = summary, created_at = time.time()-120),
        Blog(id='5', name='Javascript IT', summary = summary, created_at = time.time()-3600),
        Blog(id='6', name='Learn Swift', summary = summary, created_at = time.time()-7200),
    ]
    '''
    page_index = get_page_index(page)
    num = yield from Blog.find_number('count(id)',
                                      where='name!=? and enabled=?',
                                      args=['__about__', True])
    page = Page(num, page_index)
    if num <= 0:
        blogs = []
    else:
        blogs = yield from Blog.find_all(where='name!=? and enabled=?',
                                         args=['__about__', True],
                                         order_by='created_at desc',
                                         limit=(page.offset, page.limit))
        for blog in blogs:
            blog.html_summary = markdown2.markdown(
                blog.summary,
                extras=[
                    'code-friendly', 'fenced-code-blocks', 'highlightjs-lang',
                    'tables', 'break-on-newline'
                ]).replace("<table>", "<table class=\"ui celled table\">")
            #comments_count = yield from Comment.find_number(select_field='count(id)', where='blog_id=?', args=[blog.id])
            comments_count = yield from CommentAnonymous.find_number(
                select_field='count(id)', where='blog_id=?', args=[blog.id])
            blog.comments_count = comments_count

            #get blog tags
            tags = []
            if blog.tags:
                for tag_id in blog.tags.split(","):
                    tag = yield from Tags.find(tag_id)
                    if tag:
                        tags.append({
                            "key": tag.id,
                            "value": tag.name,
                            "color": COLORS[tag.id % len(COLORS)]
                        })
            blog.tags = tags
    return {
        '__template__': 'blogs.html',
        'page': page,
        'blogs': blogs,
        'meta': {
            "keywords": configs.web_meta.keywords,
            "description": configs.web_meta.description
        }
    }
Example #35
0
def delete_post(id):

    if users.is_current_user_admin():
        posts = Posts()

        tags = Tags()

        categories = Categories()

        updating_post = BlogPost.get(int(id))

        categories.delete(updating_post.category)

        posts.delete(updating_post.key)

        tags.update(updating_post.get_tag_names())

    return jsonify(msg="OK")
Example #36
0
def delete_post(id):

    if users.is_current_user_admin():
        posts = Posts()

        tags = Tags()

        categories = Categories()

        updating_post = BlogPost.get(int(id))

        categories.delete(updating_post.category)

        posts.delete(updating_post.key)

        tags.update([])

    return jsonify(msg="OK")
Example #37
0
    def get(self):

        tags = Tags.get_single()

        template_values = {"tags_enabled":tags.enabled,
                           "tags_available":tags.available}

        template = jinja_environment.get_template('tags.html')
        self.response.out.write(template.render(template_values))
Example #38
0
 def get(self):
     bm = Bookmarks.get_by_id(int(self.request.get('bm')))
     tag = Tags.get_by_id(int(self.request.get('tag')))
     # if users.get_current_user() == bm.user:
     bm.tags.remove(tag.key)
     bm.put()
     template = jinja_environment.get_template('tags.html')
     values = {'bm': bm} 
     tags = template.render(values)
     self.response.write(tags)
Example #39
0
 def get(self):
     feed = Feeds.get_by_id(int(self.request.get('feed')))
     tag  = Tags.get_by_id(int(self.request.get('tag')))
     if users.get_current_user() == feed.user:
         if tag in feed.tags:
             pass
         else:
             feed.tags.append(tag.key)
             feed.put()
     self.redirect(self.request.referer)
Example #40
0
 def get(self):
     bm = Bookmarks.get_by_id(int(self.request.get('bm')))
     tag = Tags.get_by_id(int(self.request.get('tag')))
     # if users.get_current_user() == bm.user:
     bm.tags.remove(tag.key)
     bm.put()
     template = jinja_environment.get_template('tags.html')
     values = {'bm': bm}
     tags = template.render(values)
     self.response.write(tags)
Example #41
0
 def get(self, tag):
     tags_entity = Tags.get_single()
     if tag in tags_entity.available:
         if tag not in tags_entity.enabled:
             tags_entity.enabled.append(tag)
             tags_entity.save()
         else:
             tags_entity.enabled.remove(tag)
             tags_entity.save()
     self.redirect("/admin/tags")
Example #42
0
    def rpc_get_indexes_for_tag(self, tag):
        """
        Get search strings for the specified tag.

        @argument tag
        @returns 
        """
        indexes = Tags.get_indexes(tag)
        if not indexes:
            return {}
        return indexes
Example #43
0
def import_tags(drop=False):
    if drop:
        Tags.objects(is_base=True).delete()

    added = 0
    updated = 0

    with open("fixtures/base_tags.json", "r") as f:
        tags = json.load(f)
        for tag in tags:
            _, created = Tags.objects.get_or_create(
                title=tag["title"], defaults=tag)
            if created:
                added += 1
            else:
                updated += 1

    Tags.ensure_index(["is_base", "usages", "category"])

    return added, updated
Example #44
0
File: views.py Project: qiankai/cms
def update(request):
    if request.method == 'GET':
        pid = request.GET.get('id')
        p = People.objects.get(id = pid)
        tags = p.tags.all()
        tag=[]
        ta = ''
        for i in tags:
            tag.append(i.tag)
            ta = ta+ i.tag+','
        return render_to_response('usernet/update.html',{'person':p ,'tags':tag,'ta':ta,},
                              context_instance=RequestContext(request))
    if request.method == 'POST':
        pid = request.POST.get('id')
        Usr_Name = request.POST.get('name','')
        Usr_Mobile = request.POST.get('mobile','')
        Usr_Remark = request.POST.get('remark','')
        tags = request.POST.get('tags','')
        pre_id = request.POST.get('pre_id','')


        p = People.objects.get(id = pid)
        p.Usr_Name =Usr_Name
        p.Usr_Mobile = Usr_Mobile
        p.Usr_Remark = Usr_Remark
        for tag in tags.replace(u',',',').split(','):
           try:
               t = Tags.objects.get(tag = tag)
           except Tags.DoesNotExist:
               newtag = Tags(tag=tag)
               newtag.save()
               p.tags.add(newtag)
               p.save()
           else:
               p.tags.add(t)
               p.save()

        status = "Update " + p.Usr_Name  + " successfully!"
        status_code = 1
        return render_to_response('usernet/message.html',{'status':status,'status_code':status_code,},
                              context_instance=RequestContext(request))
Example #45
0
def shred(cluster_id):
    cluster = Cluster.objects.get(id=cluster_id)
    if not cluster:
        abort(404)

    if request.method == "POST":
        # TODO: helper
        tags = set(map(unicode.lower, request.form.getlist("tags")))

        user_tags = cluster.get_user_tags(g.user)
        if not user_tags:
            abort(404)

        user_tags.tags = list(tags)
        user_tags.recognizable_chars = request.form.get(
            "recognizable_chars", "")
        user_tags.angle = int(request.form.get("angle", 0))
        cluster.save()

        User.objects(pk=g.user.id).update_one(
            add_to_set__tags=list(tags))

        for tag in tags:
            Tags.objects(pk=tag).update_one(
                set_on_insert__is_base=False,
                set_on_insert__created_by=g.user.id,
                set_on_insert__created_at=Tags().created_at,
                inc__usages=1,
                add_to_set__shreds=request.form["_id"],
                upsert=True)

        return render_template("_shred_snippet.html", cluster=cluster)
    else:
        return render_template(
            "_shred.html",
            cluster=cluster,
            auto_tags=cluster.get_auto_tags(),
            all_tags=get_tags(),
            user_data=cluster.get_user_tags(g.user),
            edit=True,
        )
Example #46
0
def post(request, slug):
    try:
        db_blog = Posts.objects.get(slug=slug)
    except:
        db_blog = None
    if db_blog:
        db_blog.tag_set.all().delete()
    form = PostsForm(request.POST, instance=db_blog)
    ##print( "content %s" % request.POST.get("content"))
    if form.is_valid():
        blog_post = form.save(commit=False)
        blog_post.mark_down = blogContentRender(blog_post.content)
        tags = blog_post.tags.split(',')
        blog_post.save()
        for tag in tags:
            t = Tags()
            t.post = Posts.objects.get(slug=blog_post.slug)
            t.name = tag.strip()
            t.save()
        form.save_m2m()
        return HttpResponseRedirect("/")
    c = {"form": form, "slug": slug}
    c.update(csrf(request))
    t = get_template("publish.html")
    return HttpResponse(t.render(Context(c)))
Example #47
0
def main():

    if users.is_current_user_admin():
        if request.method=='GET':  #all entitites
            posts = Posts()

            return jsonify(posts.to_json())

        elif request.method == "POST":

            form = PostForm()
            if form.validate_on_submit():  #new entity
                posts = Posts()
                categories = Categories()
                tags = Tags()

                raw_post = request.get_json()
                raw_category = raw_post["category"]
                editing_tags = raw_post["tags"]
                raw_summary = raw_post["summary"]


                tag_keys = tags.update(editing_tags)
                category_key = categories.update(raw_category)

                post_id = posts.add(raw_title=raw_post["title"],
                            raw_body=raw_post["body"],
                            category_key=category_key,
                            tags_ids=tag_keys,
                            summary=raw_summary,
                            answers=raw_post["answers"]).id()
                post = BlogPost.get(post_id)
                return jsonify(post.to_json()) #  Needs check
            else:
                return jsonify(msg="missing token")
    else:
        return jsonify({})
Example #48
0
    def test_has_some_tasks(self):
        self.create_user_and_login("user")

        self.client.post(url_for("fixtures.create_shreds"))

        res = self.client.get(url_for("next"))
        self.assert200(res)
        body = res.get_data(as_text=True)

        self.assertTrue("shred_id" in body)
        self.assertTrue(url_for("next") in body)

        for tag in Tags.objects(is_base=True):
            self.assertTrue(
                tag.title.capitalize().encode('unicode-escape') in body)
Example #49
0
    def test_incr_decr_string(self):
        Tags.objects.all().delete()

        Tags.incr('foo, bar')
        Tags.incr('foo , baz')
        Tags.decr('bar, baz')

        foo = Tags.objects.get(name='foo')
        self.assertEqual(foo.count, 2)
        bar = Tags.objects.get(name='bar')
        self.assertEqual(bar.count, 0)
Example #50
0
    def test_incr_decr_list(self):
        Tags.objects.all().delete()

        Tags.incr(['foo', 'bar'])
        Tags.incr(['foo', 'baz'])
        Tags.decr(['bar', 'baz'])

        foo = Tags.objects.get(name='foo')
        self.assertEqual(foo.count, 2)
        bar = Tags.objects.get(name='bar')
        self.assertEqual(bar.count, 0)
Example #51
0
 def get(self):
     user = users.get_current_user()
     tag_str = self.request.get('tag')
     if user:
         tag = Tags.query(Tags.user == user, Tags.name == tag_str).get()
         if tag is None:
             newtag = Tags()
             newtag.name = tag_str
             newtag.user = user 
         else:
             newtag = tag
         newtag.put()
Example #52
0
    def test_index_logged(self):
        self.create_user_and_login("user")

        res = self.client.get(url_for("index"))

        self.assert200(res)
        body = res.get_data(as_text=True)

        self.assertFalse("warm-welcome" in body)
        self.assertFalse(url_for("social.auth", backend="facebook") in body)
        self.assertFalse(url_for("social.auth", backend="twitter") in body)
        self.assertFalse(
            url_for("social.auth", backend="google-oauth2") in body)
        self.assertFalse(
            url_for("social.auth", backend="vk-oauth2") in body)

        for tag in Tags.objects(is_base=True):
            self.assertTrue(tag.title.lower() in body.lower())
            self.assertTrue(tag.category.lower() in body.lower())
            if tag.hotkey:
                self.assertTrue(tag.hotkey in body.lower())
Example #53
0
 def get_all_tags(self,id):
     '''
     Returns all tags for specified user
     '''
     #get users tags
     tags_query = Tags.query(ancestor=helper.trip_key(id))
     tags = tags_query.fetch(1)
     if tags:
         tags = tags[0]
         location = [str(x) for x in tags.location]
         type = [str(x) for x in tags.type]
         season = [str(x) for x in tags.season]
     else:
         location = []
         type = []
         season = []
     tags = []
     tags.append(location)
     tags.append(type)
     tags.append(season)
     return tags
Example #54
0
    def test_user_tags_in_task(self):
        self.create_user_and_login("user")

        self.client.post(url_for("fixtures.create_shreds"))

        user = User.objects.get(username="******")
        admin = User.objects.get(username="******")
        user_tag = "foobar"
        another_user_tag = "barfoo"

        Tags.objects.create(title=user_tag, is_base=False,
                            created_by=user)
        Tags.objects.create(title=another_user_tag, is_base=False,
                            created_by=admin)

        user.tags = [user_tag]
        admin.tags = [another_user_tag]
        user.save()
        admin.save()

        res = self.client.get(url_for("next"))
        self.assert200(res)
        body = res.get_data(as_text=True)

        self.assertTrue(
            user_tag.capitalize().encode('unicode-escape') in body)
        pos = body.index(user_tag.capitalize().encode('unicode-escape'))

        self.assertFalse(
            another_user_tag.capitalize().encode('unicode-escape') in body)

        for tag in Tags.objects(is_base=True):
            tag = tag.title.capitalize().encode('unicode-escape')
            self.assertTrue(tag in body)

            self.assertTrue(body.index(tag) < pos)
Example #55
0
 def post(self):
     
     _,id,_,_ = self.get_user()
     
     #get specific trip     
     trip_key = self.request.get('trip_id')
     tripk = ndb.Key(urlsafe=trip_key)
     trip = tripk.get()    
     
     #get new values
     new_name = self.request.get('trip_name')
     if new_name:         
         trip.trip_name = new_name
     new_description = self.request.get('description')
     if new_description:
         trip.description = new_description
         
     new_cities =  self.get_cities(self.request.get('cities'))
     if new_cities:
         trip.cities = new_cities
         
     new_avatar = self.request.get('img')
     if  new_avatar:
         trip.trip_avatar = new_avatar
     
     new_from_date = self.request.get('from_date') 
     if new_from_date:
         try:
             new_from_date = datetime.strptime( new_from_date, '%d/%m/%Y')  
         except:
             try:
                 new_from_date = datetime.strptime( new_from_date, '%Y-%m-%d')  
             except:
                     new_from_date = datetime.strptime( '2000-01-01', '%Y-%m-%d')  
         trip.from_date = new_from_date
     
     new_to_date = self.request.get('to_date')
     if new_to_date:
         try:
             new_to_date = datetime.strptime( new_to_date, '%d/%m/%Y')  
         except:
             try:
                 new_to_date = datetime.strptime( new_to_date, '%Y-%m-%d')  
             except:
                 new_to_date = datetime.strptime( '2000-01-01', '%Y-%m-%d')  
         trip.to_date = new_to_date
     
     if self.request.get('visibility') == 'True':
         trip.visibility = True
     else:
         trip.visibility = False 
     
     #crete tags for trip
     locationl = helper.creatList(self.request.get('location'))
     typel = helper.creatList(self.request.get('type'))
     seasonl = helper.creatList(self.request.get('season'))
     trip.trip_tags = Tags(location=locationl,type=typel,season=seasonl)
     
     #put new tags in users tags
     tags_query = Tags.query(ancestor=helper.trip_key(id))
     tags = tags_query.fetch(1)
     if tags:
         tags = tags[0]
         tags.location = helper.union(tags.location,locationl)
         tags.type = helper.union(tags.type,typel)
         tags.season = helper.union(tags.season,seasonl)
                   
     else:
         new_loc_tags = locationl
         new_type_tags = typel
         new_seasion_tags = seasonl
         tags = Tags(parent=helper.trip_key(id),location=new_loc_tags,type=new_type_tags,season=new_seasion_tags)
     
     tags.put()
     
     trip.put()
     
    
     self.redirect('/tripmanager/onetrip?trip_id='+ tripk.urlsafe())
Example #56
0
 def post(self):
     '''
     Adds trip to datastore
     '''
     
     _,id,_,_ = self.get_user()
     
     #TODO some checking      
     trip = Trip(parent=helper.trip_key(id))
     trip.trip_name = self.request.get('trip_name')
     
     trip.description = self.request.get('description')
     trip.cities =  self.get_cities(self.request.get('cities'))
     avatar = self.request.get('img')
     if  avatar:
         trip.trip_avatar = avatar
     
     
     try:
         trip.from_date = datetime.strptime( self.request.get('from_date'), '%d/%m/%Y')  
         trip.to_date = datetime.strptime(self.request.get('to_date'), '%d/%m/%Y')
     except:
         try:
             trip.from_date = datetime.strptime( self.request.get('from_date'), '%Y-%m-%d')  
             trip.to_date = datetime.strptime(self.request.get('to_date'), '%Y-%m-%d')
         except:
             trip.from_date = datetime.strptime( '2000-01-01', '%Y-%m-%d')  
             trip.to_date = datetime.strptime('2000-01-01', '%Y-%m-%d')
     
     if self.request.get('visibility') == 'True':
         trip.visibility = True
     else:
         trip.visibility = False
     
     #create statistic for trip 
     trip.trip_statistic = TrackStatistic(name="Trip Stat",total_distance=0,total_time="",
                                          avr_speed=0,total_climb=0,max_elev=-100)
     
     #crete tags for trip
     locationl = helper.creatList(self.request.get('location'))
     typel = helper.creatList(self.request.get('type'))
     seasonl = helper.creatList(self.request.get('season'))
     trip.trip_tags = Tags(location=locationl,type=typel,season=seasonl)
     
     trip.put()
            
     #put new tags in users tags
     tags_query = Tags.query(ancestor=helper.trip_key(id))
     tags = tags_query.fetch(1)
     if tags:
         tags = tags[0]
         tags.location = helper.union(tags.location,locationl)
         tags.type = helper.union(tags.type,typel)
         tags.season = helper.union(tags.season,seasonl)
                   
     else:
         new_loc_tags = locationl
         new_type_tags = typel
         new_seasion_tags = seasonl
         tags = Tags(parent=helper.trip_key(id),location=new_loc_tags,type=new_type_tags,season=new_seasion_tags)
     
     tags.put()
     
     #redirect to mytrips because showing all tips will only be consistent in scope of user
     # and only eventually consistent for whole datastore  
     self.redirect('/tripmanager')
Example #57
0
def get_tags():
    return set([unicode(t["title"]).lower()
                for t in Tags.objects(is_base=True).order_by("-usages")] +
               map(lambda x: unicode(x).lower(), g.user.tags))