Ejemplo n.º 1
0
    def _save_m2m(self):
        # add new tags
        tags = self.cleaned_data['tags']
        tags_qs = Tag.objects.filter(name__in=tags).all()

        new_tags = set(tags) - set(row.name for row in tags_qs)
        for t in new_tags:
            new_tag = Tag()
            new_tag.name = t
            new_tag.save()

        super(AskForm, self)._save_m2m()
Ejemplo n.º 2
0
def tags_from_names(db, tagname_list):
    tags = []
    for tagname in tagname_list:
        tag = query.tag(tagname)
        if tag:
            tags.append(tag)
        else:
            tag = Tag(name=tagname, slug=to_slug(tagname))
            db.session.add(tag)
            db.session.commit()
            tags.append(tag)
    return tags
Ejemplo n.º 3
0
def addtag():
    form = TagForm()
    if request.method == "POST":
        if form.validate() == False:
            return render_template('addtag.html', form=form)
        else:
            tag = Tag(form.tag.data)
            db.session.add(tag)
            db.session.commit()
            flash('Tag created successfully')
            return render_template('tags.html', tags=Tag.query.all())
    return render_template("addtag.html", form=form)
Ejemplo n.º 4
0
async def tag(request: Request, tag_id):
    tag = await Tag.async_first(id=tag_id)
    tag_obj = Tag(**tag)
    if not tag:
        raise HTTPException(status_code=404, detail='no such tag.')
    post_ids = [
        p['post_id'] for p in (await PostTag.async_filter(tag_id=tag_id))
    ]
    posts = await Post.async_in('id', post_ids)
    posts = [p for p in posts if p['status'] == Post.STATUS_ONLINE]
    post_objs = [Post(**p) for p in posts]
    return {'tag': tag_obj, 'posts': post_objs}
def edit_post():
    page = int(request.form['index'])
    posts = Post.query.paginate(page, POSTS_PER_PAGE, False).items
    has_next = Post.query.paginate(page, POSTS_PER_PAGE, False).has_next

    if request.form['title'] == "" or request.form['body'] == "":
        flash('You have to fill all the inputs!','error')
        return render_template('show_posts.html', posts=posts, index=page, has_next = str(has_next))

    if not session.get('logged_in'):
        abort(401)

    post = Post.query.filter_by(id = request.form['id']).first()

    entry = request.form['body']

    r=re.compile(r'.*\[code (?P<lang>.{0,10})\](?P<code>.+)\[/code\].*', re.DOTALL)
    m=r.match(entry)

    if m is not None:
        lang = m.group('lang')
        code = m.group('code')

        lexer = get_lexer_by_name(lang, stripall=True)
        code = highlight(code, lexer, HtmlFormatter())

        front = entry[:entry.find('[code')]
        back = entry[entry.find('[/code]') + 7:]
        new_entry = front + code + back

	print new_entry

	post.coded_body = new_entry
    else:
	print "Nooooooooooooooooooooooooooo"
	post.coded_body = ''

    post.title = request.form['title']
    post.body = request.form['body']

    while len(post.tags) is not 0:
        for tag in post.tags:
            post.tags.remove(tag)
    if request.form['tags'].strip() != '':
        tags = request.form['tags'].split(',')
        for tag in list(set(tags)):
            if tag.strip() == '':
	        continue
            post.tags.append(Tag(tag.strip()))
    db.session.commit()
    flash('Post was successfully edited','normal')

    return render_template('show_posts.html', posts=posts, index=page, has_next = str(has_next))
Ejemplo n.º 6
0
def POST_new_tag():
  name = request.form['name']
  # get list of id's for checked boxes
  post_ids = [int(id) for id in request.form.getlist('post')]
  # get list of post objects for each post_id
  posts = Post.query.filter(Post.id.in_(post_ids)).all()
  # creat new tag object with input name and checked posts
  new_tag = Tag(name=name, posts=posts)
  db.session.add(new_tag)
  db.session.commit()
  flash(f'{name} has been added to posts {[ p.title for p in posts]}', "success")
  return redirect('/tags')
Ejemplo n.º 7
0
def add_new_tag():
    tag_name = request.form['name']

    if not tag_name:
        flash('Name field cannot be blank')
        return redirect('/tags/new')
    else:
        new_tag = Tag(name=tag_name)
        db.session.add(new_tag)
        db.session.commit()

        return redirect('/tags')
Ejemplo n.º 8
0
    def setUp(self):
        """Add test User and associated Post ."""

        db.drop_all()
        db.create_all()

        # User.query.delete()
        Post.query.delete()
        Tag.query.delete()

        #  Create User
        user = User(first_name="Joe",
                    last_name="Blow",
                    image_url="http://www.profile.com")
        db.session.add(user)
        db.session.commit()

        self.user_id = user.id

        # Create two posts and associate them with user 1
        post = Post(title="Post 1",
                    content="This is the content for Post 1",
                    user_id=self.user_id)

        # post2 = Post(title = "Post 2",
        #             content = "This is the content for Post 2",
        #             user_id = self.user_id)

        tag1 = Tag(name='Awesome')
        tag2 = Tag(name='Wow!')

        post.tags.append(tag1)
        post.tags.append(tag2)

        db.session.add(post)
        db.session.commit()

        # import pdb; pdb.set_trace()
        self.post_id = post.id
        self.tag_id = tag1.id
Ejemplo n.º 9
0
    def setUp(self):

        self.au1 = Author(name='Author 1')
        self.au1.save()
        self.au2 = Author(name='Author 2')
        self.au2.save()
        # Create a couple of Articles.
        self.a1 = Article(headline='Article 1',
                          pub_date=datetime(2005, 7, 26), author=self.au1)
        self.a1.save()
        self.a2 = Article(headline='Article 2',
                          pub_date=datetime(2005, 7, 27), author=self.au1)
        self.a2.save()
        self.a3 = Article(headline='Article 3',
                          pub_date=datetime(2005, 7, 27), author=self.au1)
        self.a3.save()
        self.a4 = Article(headline='Article 4',
                          pub_date=datetime(2005, 7, 28), author=self.au1)
        self.a4.save()
        self.a5 = Article(headline='Article 5',
                          pub_date=datetime(2005, 8, 1, 9, 0),
                          author=self.au2)
        self.a5.save()
        self.a6 = Article(headline='Article 6',
                          pub_date=datetime(2005, 8, 1, 8, 0),
                          author=self.au2)
        self.a6.save()
        self.a7 = Article(headline='Article 7',
                          pub_date=datetime(2005, 7, 27), author=self.au2)
        self.a7.save()
        # Create a few Tags.
        self.t1 = Tag(name='Tag 1')
        self.t1.save()
        self.t1.articles.add(self.a1, self.a2, self.a3)
        self.t2 = Tag(name='Tag 2')
        self.t2.save()
        self.t2.articles.add(self.a3, self.a4, self.a5)
        self.t3 = Tag(name='Tag 3')
        self.t3.save()
        self.t3.articles.add(self.a5, self.a6, self.a7)
Ejemplo n.º 10
0
    def mutate(root, args, context, info):
        decoded = decode(context.headers.get('Authorization'))[0]
        if decoded is None or not (is_admin(decoded)):
            return CreateNewPost(success=False, link=None)
        userId = decoded['sub']
        user = User.get_query(context).get(userId)

        # begin creating the post
        try:
            new_post = Post(title=args['title'],
                            content=args['content'],
                            author=user,
                            excerpt=args['excerpt'])
            if 'link' in args:
                link = args['link']
            if link is None or link == '':
                link = args['title'].replace(' ', '-')
            new_post.link = link
            # resolve visibility. default public
            new_post.visibilityId = args[
                'visibilityId'] if 'visibilityId' in args else 1

            # resolve tags
            tags = args['tags'] if 'tags' in args else []
            tagList = []
            for tag in tags:
                t = Tag.query.filter_by(name=tag).first()
                if t is None:
                    t = Tag(name=tag)  # create new tag if none exist
                tagList.append(t)
            new_post.tags = tagList

            # resolve category
            if 'category' in args:
                category = Category.query.filter_by(
                    name=args['category']).first()
                if category:
                    new_post.category = category

            # check if there exist other post with given name
            pre_post_num = Post.query.filter_by(
                link=new_post.link, category=new_post.category).count()
            if (pre_post_num):
                new_post.link += '-{}'.format(uuid())

            # save the post to database
            db_session.add(new_post)
            db_session.commit()
            return CreateNewPost(success=True, link=new_post.link)

        except:
            return CreateNewPost(success=False, link=None)
def get_all_posts():
    with sqlite3.connect("./rare.db") as conn:
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        db_cursor.execute("""
        SELECT
            id,
            user_id,
            category_id,
            title,
            publication_date,
            image_url,
            content,
            approved
        FROM Posts
        """)

        dataset = db_cursor.fetchall()

        posts = []

        for row in dataset:
            post = Post(row['id'], row['user_id'], row['category_id'],
                        row['title'], row['publication_date'],
                        row['image_url'], row['content'], row['approved'])

            db_cursor.execute(
                """
                SELECT 
                    t.id,
                    t.label 
                FROM Tags t
                JOIN PostTags pt
                    ON t.id = pt.tag_id
                WHERE pt.post_id = ?
                """, (row['id'], ))

            post_tags = db_cursor.fetchall()

            tags = []

            for row in post_tags:
                tag = Tag(row['id'], row['label'])

                tags.append(tag.__dict__)

            post.tags = tags

            posts.append(post.__dict__)

    return json.dumps(posts)
Ejemplo n.º 12
0
def createNewTag(body, user_guid):
    tag = Tag(user_id=user_guid,
              name=body['name'],
              picture=body['picture'],
              active=body['active'])
    session.add(tag)
    session.commit()
    return {
        "id": tag.id,
        "external_id": tag.external_id,
        "name": tag.name,
        "picture": tag.picture
    }
Ejemplo n.º 13
0
def tags_new():
    """Handle form submission for creating a new tag
    """

    post_ids = [int(num) for num in request.form.getlist("posts")]
    posts = Post.query.filter(Post.id.in_(post_ids)).all()
    new_tag = Tag(name=request.form['name'], posts=posts)

    db.session.add(new_tag)
    db.session.commit()
    flash(f"Tag '{new_tag.name}' added.")

    return redirect("List_Tag.html")
Ejemplo n.º 14
0
def add_tag():
    """Add a tag"""
    if request.method == 'POST':
        name = request.form.get('name')
        print('tag name', name)
        tag = Tag(name=name)

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

        return redirect('/tags')

    return render_template('tags/new.html')
Ejemplo n.º 15
0
def create_or_assign_tag(tag_title):

    slugified_title = slugify(tag_title)
    try:
        tag = session.query(Tag).filter_by(title=slugified_title).one()
    except:
        tag = Tag(title=slugified_title)
        session.add(tag)
        session.commit()

    print(tag.id)

    return tag
Ejemplo n.º 16
0
def create_tag():
    '''create new tag and save to database'''
    name = request.form['tag_name']

    try:
        tag = Tag(name=name)
        db.session.add(tag)
        db.session.commit()
        flash('Created new tag!', 'success')
        return redirect('/tags')
    except:
        flash('Unable to add tag!', 'error')
        return redirect('/tags')
Ejemplo n.º 17
0
def add_new_tag():
  # Add new tag to DB and redirect to list of tags
  name = request.form['tagName'].strip().capitalize()
  post_ids = [int(num) for num in request.form.getlist("posts")]
  posts = Post.query.filter(Post.id.in_(post_ids)).all()
  new_tag = Tag(name = name, posts = posts)

  db.session.add(new_tag)
  db.session.commit()
  tags = Tag.query.all()

  flash(f"'{new_tag.name}' tag was successfully created.", 'success')
  return redirect('/tags')
Ejemplo n.º 18
0
def create_tag():
    """This view function creates a new in the blogly db"""

    tag_name = request.form["tag_name"]
    post_ids = [int(num) for num in request.form.getlist("posts")]
    posts = Post.query.filter(Post.id.in_(post_ids)).all()

    tag = Tag(tag_name=tag_name, posts=posts)

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

    return redirect("/tags")
Ejemplo n.º 19
0
def create_tag():
    """Create new tag or display form"""

    if request.method == "POST":
        name = request.form['name']

        tag = Tag(name=name)
        db.session.add(tag)
        db.session.commit()

        return redirect("/tags")
    else:
        return render_template("new_tag.html")
Ejemplo n.º 20
0
def new_tag():

    if request.method == 'GET':
        return render_template("newtag.html")

    name = request.form['tagName']

    new_tag = Tag(name=name)

    db.session.add(new_tag)
    db.session.commit()

    return redirect('/tags')
Ejemplo n.º 21
0
def add_tag():
    """Show form to add a new tag (GET).
    Process submitted form data (POST)."""

    if request.method == 'POST':
        name = request.form["name"]
        new_tag = Tag(name=name)
        db.session.add(new_tag)
        db.session.commit()
        flash(f'Tag {new_tag.name} was created.')
        return redirect('/tags')
    else:
        return render_template('/tags/add-tag.html')
Ejemplo n.º 22
0
def render_tag_form():
    """ Render Tag Form """
    if request.method == "POST":
        if request.form["name"] == "":
            flash("Please fill in the form completely")
            return redirect('/tags/new')
        tag = request.form["name"]
        new_tag = Tag(name=tag)
        db.session.add(new_tag)
        db.session.commit()
        return redirect('/tags')
    else:
        return render_template('tag-form.j2')
Ejemplo n.º 23
0
 def getTopTag(self, request):
     query = request.title
     tags = query.split('+')
     topics = None
     key = None
     if len(tags) == 1:
         key = 'top:tag:' + tags[0]
         topics = memcache.get(key)
     if not topics:
         q = Topic.query()
         for tag in tags:
             q = q.filter(Topic.tags == tag)
         q = q.order(-Topic.vote)
         if request.limit > 50:
             limit = 50
         else:
             limit = request.limit
         q = q.fetch(limit)
         topics = [self._copyTopicToForm(t) for t in q]
         sum_tags = [
             self._copyTagToForm(Tag(tag=t[0], score=t[1]))
             for t in self._sumTag(topics)
         ]
         if len(tags) == 1 and key:
             memcache.set(key, topics)
             memcache.set('tag' + key, sum_tags)
     else:
         sum_tags = None
         if len(tags) == 1 and key:
             sum_tags = memcache.get('tag' + key)
         if not sum_tags:
             sum_tags = [
                 self._copyTagToForm(Tag(tag=t[0], score=t[1]))
                 for t in self._sumTag(topics)
             ]
             if len(tags) == 1 and key:
                 memcache.set('tag' + key, sum_tags)
     n = len(topics)
     return TopicForms(topics=topics, length=n, tags=sum_tags)
Ejemplo n.º 24
0
def tag_controller(id):
    desc = request.values.get('desc')

    if id:
        if request.method == 'GET':
            tag = Tag.query.get(id)
            if tag:
                tag = tag.dto()
            if request.values.get('json'):
                return json.dumps(dict(tag=tag))
            else:
                return render_template('tag_view.html', tag = tag)
        elif request.method == 'PUT':
            tag_item = Tag.query.get(id)
            tag_item.desc = desc
            db.session.add(tag_item)
            db.session.commit()
            return 'updated'
        elif request.method == 'DELETE':
            tag_item = Tag.query.get(id)
            db.session.delete(tag_item)
            db.session.commit()
            return 'deleted'
        else:
            return 'Method Not Allowed'
    else:
        if request.method == 'GET':
            tag_list = Tag.query.all()
            if tag_list:
                entries = [tag.dto() for tag in tag_list]
            else:
                entries=None
            if request.values.get('json'):
                return json.dumps(dict(tag=entries))
            else:
                return render_template('tag.html',tag_entries = entries, title = "Tag List")
        elif request.method == 'POST':
            new_tag = Tag(
                            desc = desc
                            )

            db.session.add(new_tag)
            db.session.commit()
            if request.values.get('json'):
                url = '/tag/json=true'
            else:
                url = '/tag/'
            return redirect(url)
        else:
            return 'Method Not Allowed'
Ejemplo n.º 25
0
def create_tag():
    title = request.form['title'] # Tag title
    description = request.form['desc'] # Tag desc

    # Create the new tag
    new_tag = Tag(tag_title=title, task_desc=description)

    # Try to add to db
    try:
        db.session.add(new_tag)
        db.session.commit()
        return True # Return True if commit is successful
    except:
        return False
Ejemplo n.º 26
0
def community_create():
    form = CommunityCreateForm()

    form.tags.choices = [
        (t.title, t.title)
        for t in Tag.select(Tag.title).order_by(Tag.title).distinct()
    ]

    if form.validate_on_submit() and current_user.karma >= 50:
        community = Community()

        community.name = slugify(form.name.data)
        community.description = form.description.data
        community.maintainer = User.get(User.id == current_user.id)

        community.update_search_index()

        user = User.get(User.id == current_user.id)
        user.karma -= 50
        user.save()

        success = True

        try:
            community.save()

        except peewee.IntegrityError:
            flash(gettext('This name is already in use.'), 'error')
            success = False

        else:
            try:
                for element in form.tags.data.split(','):
                    if not element:
                        continue

                    tag = Tag()
                    # FIXME: slugify?
                    tag.title = element
                    tag.community = community
                    tag.save()

            except peewee.IntegrityError:
                flash(gettext('Unable to add tags.'), 'error')
                success = False

        if success:
            return redirect(url_for('community', community=community.name))

    return render_template('community_create.html', form=form)
Ejemplo n.º 27
0
def update_resource_from_form(form, resource):
    resource.name = form.name.data
    resource.date = form.date.data
    resource.start_time = form.start_time.data
    resource.end_time = form.end_time.data
    tag_keys = []
    for tag_str in form.tags.data.split(","):
        tag = tag_exists(tag_str)
        if tag is None:
            tag = Tag(name=tag_str)
            tag.put()
        tag_keys.append(tag.key)
    resource.tag_keys = tag_keys
    return resource
Ejemplo n.º 28
0
    def post(self):
        """
        Adds a new tag.
        """
        data = api.payload
        name = data.get('name')

        if Tag.query.filter_by(name=name).first() is not None:
            return {'message': "The tag\'s name already exists!"}, 400

        tag = Tag(name=name)
        db.session.add(tag)
        db.session.commit()
        return {'element': tag.to_json()}, 201
Ejemplo n.º 29
0
def add_tag():
    """Adds new tag and returns tag list page"""

    tag_name = request.form["name"]

    if not tag_name:
        flash("Please enter tag name")
        return redirect("/tags/new")

    tag = Tag(name=tag_name)
    db.session.add(tag)
    db.session.commit()

    return redirect("/tags")
Ejemplo n.º 30
0
    def setUp(self):
        """Add sample tag."""

        db.create_all()
        user = User(first_name="Steve", last_name="Rogers")
        tag = Tag(name="Marvel")
        post = Post(title="Avengers",
                    content="We're coming for you, Thanos.",
                    user=user)
        tag.posts.append(post)
        db.session.add_all([user, tag, post])
        db.session.commit()

        self.tag = tag