Esempio n. 1
0
def write_answer():
    if request.method == 'GET':
        question_id = request.args.get('question')
        link = request.args.get('link') or ''
        if question_id is not None:
            return render_template('write_answer.html', disable=True, question=Question.query.filter_by(id=question_id).first_or_404().title, link=link)
        return render_template('write_answer.html', link=link)
    else:
        question_get = request.form.get('question')
        question_desc = request.form.get('question_desc')
        link = request.form.get('link')
        desc = request.form.get('desc')
        private = request.form.get('private')  # off=None
        tags = unicode(request.form.get('tags')).split(',')

        if (question_get is None and request.args.get('question') is None) or desc is None or link is None:
            abort(403)
        author = g.user
        if question_get == u"我的快速启动":
            question = Question.query.filter_by(id=request.args.get('question'), author=author).first_or_404()
        else:
            question = Question.query.filter_by(id=request.args.get('question')).first()
        if question is None:
            question = Question(title=question_get, author=author, desc=question_desc)
            if private is None:
                g.my_theme_normal.questions.append(question)
            else:
                g.my_theme_normal.questions.append(question)
                question.private = True
            db.session.add(question)
            db.session.commit()
        else:
            if question.private and g.user.id != question.author.id:
                abort(403)
        for tag in tags:
            if tag is not None:
                Tag.get_or_create(tag).add_to_tag(question)
        if not Answer.verify_link(link):
            flash(MESSAGE_BOX_CN['link_fail'])
            return render_template('write_answer.html', question=question_get, link=link, desc=desc, question_desc=question_desc)
        if Answer.query.filter_by(link=link, question=question, desc=desc).first() is not None:
            flash(MESSAGE_BOX_CN['link_fail_same'])
            return render_template('write_answer.html', question=question_get, link=link, desc=desc, question_desc=question_desc)
        answer = Answer(link=link, desc=desc, author=author, question=question)
        db.session.add(answer)
        db.session.commit()
        if g.user.id != question.author.id:
            Message.send_message(question.author,
                                 render_template('msg/msg_item_answer.html', sender=g.user, answer=answer, question=question))
            send_email(question.author.email, MESSAGE_BOX_CN['email_prefix_new_link'], 'email/msg_answer',
                       sender=g.user, answer=answer)
        flash(MESSAGE_BOX_CN['write_success'])
        return redirect(url_for('view_question', id=answer.question.id, _anchor="answer-"+str(answer.id)))
Esempio n. 2
0
    def post(self):
        """
        headers = Token
        args = {"title": title, "text": text, "tags": tag1,tag2,tag3,...}
        """

        user = auth_token()
        if not user:
            return response_model(), 401

        req = get_json_data("title", "text", "tags")
        if not req:
            return response_model(), 400

        # author -> this is user from authentication

        # add Post object
        with db.transaction():
            try:
                p = Post(author=user, title=req['title'].encode('utf-8'), text=req['text'].encode('utf-8'))
                p.save()

                for tag in req['tags'].split(","):
                    tmp, _ = Tag.get_or_create(name=tag)
                    apat = AssociationPostAndTag(post=p, tag=tmp)
                    apat.save()
            except:
                db.rollback()
                return response_model(), 400


        return response_model(), 200
Esempio n. 3
0
    def post(self):
        """ 
        headers = Token
        args = {"new_tag_name": new_tag_name}
        """
        user = auth_token()
        if not user:
            return response_model(), 401

        req = get_json_data("old_tag_name","new_tag_name")
        if not req or not id:
            return response_model(), 400

        # get all posts with Tag.id
        posts = Post.select().join(AssociationPostAndTag).join(Tag).where(Tag.name == req['old_tag_name'])

        # remove old Post-Tag connection
        for post in posts:
            asso = AssociationPostAndTag.delete().where(AssociationPostAndTag.post == post)
            asso.execute()
        

        new_tag, _= Tag.get_or_create(name=req['new_tag_name'])
        # save Post to new Tag
        for post in posts:
            apat = AssociationPostAndTag(post=post, tag=new_tag)
            apat.save()

        # remove old tag
        t = Tag.select().where(Tag.name == req['old_tag_name']).get()
        t.delete_instance()

        return response_model(),200
Esempio n. 4
0
def log_hours():
    logging.basicConfig(level=logging.INFO)
    
    categories = settings.HAMSTER_TO_DP.keys()
    tag_logged = Tag.get_or_create(name = '_logged_in_dp_')
    

    already_tagged = [ft.fact.id for ft in FactTag.filter(tag=tag_logged).distinct()]
    

    #get all facts that belong to exportable categories, finished, and
    # not previously posted
    facts = Fact.filter(
                Q(activity__category__name__in=categories) & 
                ~Q(end_time__is=None) &
              # ~Q(fact_tags_set__tag=tag_logged)     # * see note
                ~Q(id__in=already_tagged)
            )

    # NOTE
    # I want to exclude Facts tagged with ``tag_logged``, . but that ~Q() condition
    # only exclude the facts that are ONLY tagged with ``tag_logged``.
    
    # the last Q is a workaround but imply a nested select.
    # How I should write this query?

    if not facts.exists():
        logging.info("You're up to date! There is no unsynced tasks")
        return
        

    br = DotProjectBot(settings.DP_BASE_URL)
    br.login(settings.DP_USERNAME, settings.DP_PASSWORD)


    for f in facts:
        #process data
        tags = ', '.join([ft.tag.name for ft in f.fact_tags_set])

        if tags and f.description:
            description = '%s %s: %s' % (f.activity.name, tags, f.description)
        elif tags:
            description = '%s %s' % (f.activity.name, tags)
        elif f.description:
            description = '%s %s' % (f.activity.name, f.description)
        else:
            description = f.activity.name

        dp_task_id = settings.HAMSTER_TO_DP[f.category.name]

        #and post the fact into dotproject!
        br.log_task(dp_task_id, f.start_time, f.duration, description)

        #then mark the fact as logged.
        ft = FactTag(fact=f, tag=tag_logged)
        ft.save()
Esempio n. 5
0
def admin_tag_save():

    tags = request.form.get('tags')
    edit_id = request.form.get('tag-edit-id')

    tags = [tag_json["value"]
            for tag_json in json.loads(tags)] if tags else None
    if tags:
        if edit_id:
            try:
                tag_to_edit = Tag.get(Tag.id == edit_id)
                tag_to_edit.name = tags[0]
                tag_to_edit.save()
                flash("Tag edited", "success")

            except Tag.DoesNotExist:
                abort(404)

        else:
            successes = []
            for tag in tags:
                t, created = Tag.get_or_create(name=tag)
                successes.append(created)

            if successes.count(True) == 1:
                flash(
                    "Tag \"" + ", ".join([
                        tag for tag, success in zip(tags, successes)
                        if success == True
                    ]) + "\" created!", "success")
            elif successes.count(True) > 1:
                flash(
                    "Tags \"" + ", ".join([
                        tag for tag, success in zip(tags, successes)
                        if success == True
                    ]) + "\" created!", "success")

            if successes.count(False) == 1:
                flash(
                    "Tag \"" + ", ".join([
                        tag for tag, success in zip(tags, successes)
                        if success == False
                    ]) + "\" already existed!", "danger")
            elif successes.count(False) > 1:
                flash(
                    "Tags \"" + ", ".join([
                        tag for tag, success in zip(tags, successes)
                        if success == False
                    ]) + "\" already existed!", "danger")
    else:
        flash("No tag names", "danger")
    return redirect(url_for('admin_tag_list'))
Esempio n. 6
0
def write_question():
    if request.method == 'GET':
        return render_template('write_question.html')
    else:
        title = request.form.get('title')
        desc = request.form.get('desc')
        tags = unicode(request.form.get('tags')).split(',')
        if title is None or desc is None:
            abort(403)
        if Question.query.filter_by(title=title).first() is not None:
            flash(MESSAGE_BOX_CN['question_fail_same'])
            return render_template('write_question.html', title=title, desc=desc)
        question = Question(title=title, desc=desc, author=g.user)
        g.my_theme_normal.questions.append(question)
        g.my_theme_question.questions.append(question)
        for tag in tags:
            if tag is not None:
                Tag.get_or_create(tag).add_to_tag(question)
        db.session.add(question)
        db.session.commit()
        question = Question.query.filter_by(title=title, desc=desc, author=g.user).first()
        flash(MESSAGE_BOX_CN['question_success'])
        return redirect(url_for('view_question', id=question.id))
Esempio n. 7
0
    def put(self, id=None):
        """
        headers = Token
        args = {"title": title, "text": text, "tags": tag1,tag2,...}
        """

        user = auth_token()
        if not user:
            return response_model(), 401

        req = get_json_data("title", "text", "tags")
        if not req or not id:
            return response_model(), 400

        # author -> this is user from authentication

        # get Post object and modify
        try:
            p = Post.select().where(Post.id == id).get()
            p.title = req['title']
            p.text = req['text']
            p.save()
        except:
            return response_model(), 404 # NOT FOUND

        # remove old Post-Tag records
        old_tags = AssociationPostAndTag.delete().where(AssociationPostAndTag.post == p)
        old_tags.execute()

        # get Tag objects list
        for tag in req['tags'].split(","):
            tmp, created = Tag.get_or_create(name=tag)
            apat = AssociationPostAndTag(post=p, tag=tmp)
            apat.save()

        return response_model(), 200
Esempio n. 8
0
    return [keyword[0].decode('utf-8') + u'__' + str(keyword[1]).decode('utf-8') for keyword in keywords]

  @classmethod
  def add_keyword(cls, word):
    word_utf8 = to_unicode(word)
    key = '%s%s' %(TAG_CACHE_KEY, word_utf8)
    if not cls.is_keyword(word):
      cache.incr(key, amount=1)

if __name__ == '__main__':
  file = open('data/content', 'r')
  content = ''.join([unicode(line, 'utf-8') for line in file.readlines()])
  file.close()

  keywords = WordSeg.parse(content)

  originals = [keyword.split('__')[0] for keyword in keywords]
  friends = []
  for o in originals:
    tag = Tag.get_or_create(o)
    friends.extend(tag.friends)

  friends = sum_list(friends)

  print("Original tags")
  for k in keywords:
    print(k)

  print("Friends tags")
  for f in friends:
    print(to_unicode(f[0]) + u'__' + unicode(f[1]))
Esempio n. 9
0
def admin_save_post():

    edit_id = request.form.get('post-edit-id')
    title = request.form.get('post-form-title')
    slug = util.slugify(title)
    content = request.form.get('post-form-content')
    description = request.form.get('post-form-description')
    tags = request.form.get('post-form-tags')
    publish = request.form.get('post-form-publish')

    tags = [tag_json["value"]
            for tag_json in json.loads(tags)] if tags else None
    publish = True if publish == 'on' else False

    if title or content or description:
        if edit_id:
            try:
                post = Post.get(Post.id == edit_id)
                post.title = title
                post.content = content
                post.slug = slug
                post.description = description
                post.updated_at = datetime.datetime.now()
                post.published = publish
                post.save()

                if tags is not None:
                    for tag_name in tags:
                        tag, _ = Tag.get_or_create(name=tag_name)
                        posttag, _ = PostTag.get_or_create(post=post, tag=tag)

                old_tags = Tag.select().join(PostTag).join(Post).where(
                    Post == post).order_by(Tag.name)
                for old_tag in old_tags:
                    if not old_tag in tags:
                        PostTag.get(PostTag.post == post,
                                    PostTag.tag == old_tag).delete_instance()

                flash("Post edited!", "success")

            except Post.DoesNotExist:
                abort(404)

        else:
            try:
                post = Post(title=title,
                            content=content,
                            slug=slug,
                            description=description,
                            published=publish)
                post.save()
                postuser = PostUser(post=post, user=current_user.id)
                postuser.save()

                if tags is not None:
                    for tag_name in tags:
                        tag, _ = Tag.get_or_create(name=tag_name)
                        posttag, _ = PostTag.get_or_create(post=post, tag=tag)

                if publish:
                    flash("Post published!", "success")
                elif not publish:
                    flash("Post saved as draft!", "success")

            except peewee.IntegrityError:
                print("peewee.IntegrityError")
                abort(400)
    else:
        flash("Empty post", "danger")

    return redirect(url_for('admin_post_list'))
Esempio n. 10
0
from models.db import db
from models import (
    TGUser,
    Message,
    Tag,
    TGUserToMessage,
    TGUserToTag,
    MessageToTags,
)

db.connect()
db.create_tables([
    TGUser,
    Message,
    Tag,
    TGUserToMessage,
    TGUserToTag,
    MessageToTags,
])

for tag in [ONE_DORM, TWO_DORMS, THREE_DORMS]:
    Tag.get_or_create(tag=tag)

grabber = ElDiaGrabber(ONE_DORM)
grabber.grab()
grabber = ElDiaGrabber(TWO_DORMS)
grabber.grab()
grabber = ElDiaGrabber(THREE_DORMS)
grabber.grab()
Esempio n. 11
0
 def _new_tag(self, tag):
     name = tag.get('term') or tag.get('label')
     clean_name = self._sanitize_title(name)
     tag, is_new = Tag.get_or_create(name=clean_name)
     print('Saved tag "{}": new={}'.format(clean_name, is_new))
     return tag
Esempio n. 12
0
 def _new_tag(self, tag):
     name = tag.get('term') or tag.get('label')
     clean_name = self._sanitize_title(name)
     tag, is_new = Tag.get_or_create(name=clean_name)
     print('Saved tag "{}": new={}'.format(clean_name, is_new))
     return tag