Beispiel #1
0
def view_a_post(category, year, month, title):
    passed_days, remaining_days = calculate_work_date_stats()

    posts = Posts()

    answers_form = AnswerRadioForm()

    if request.args.get('q'):return redirect(url_for('searchresults',q=request.args.get('q')))

    current_post = posts.get_by_title(title)

    post_tag_names = current_post.get_tag_names()

    related_posts = posts.get_related_posts(current_post.id)

    category = current_post.category.get().category
    site_updated = posts.site_last_updated()

    answers_form.r_answers.choices = [(answer.p_answer, answer.p_answer) for answer in current_post.answers
                                      if answer.p_answer != u'']

    return render_template('singlepost.html', user_status=users.is_current_user_admin(), siteupdated=site_updated, \
                                        daysleft=remaining_days, dayspassed=passed_days, RelatedPosts=related_posts, \
                                        Post=current_post.to_json(), posttagnames=post_tag_names, category=category,
                                        answers_field = answers_form)
Beispiel #2
0
def view_a_post(category, year, month, title):
    passed_days, remaining_days = calculate_work_date_stats()

    posts = Posts()

    answers_form = AnswerRadioForm()

    if request.args.get('q'):
        return redirect(url_for('searchresults', q=request.args.get('q')))

    current_post = posts.get_by_title(title)

    post_tag_names = current_post.get_tag_names()

    related_posts = posts.get_related_posts(current_post.id)

    category = current_post.category.get().category
    site_updated = posts.site_last_updated()

    answers_form.r_answers.choices = [(answer.p_answer, answer.p_answer)
                                      for answer in current_post.answers
                                      if answer.p_answer != u'']
    return render_template('singlepost.html', user_status=users.is_current_user_admin(), siteupdated=site_updated, \
                                        daysleft=remaining_days, dayspassed=passed_days, RelatedPosts=related_posts, \
                                        Post=current_post.to_json(), posttagnames=post_tag_names, category=category,
                                        answers_field = answers_form)
Beispiel #3
0
def newpost(request):

    postid = "wellcomes"
    post = "password"
    username = "******"

    postid = random.sample(xrange(1,10000000), 1)

    post = request.POST.get(
        'post'
        , '')
    username = request.POST.get(
        'username'
        , '')
    request.session['postid'] = postid
    request.session['post'] = post
    request.session['username'] = username
    if username == "":
        return render(request, 'login.html')
    elif username == "guestuser":
        return render(request, 'login.html')
    elif post != "":
     dream = Posts(
        postid=postid,
        post=post,
        username=username,
     )
     dream.save()
    objects = Posts.objects.all()
    comments = Comment.objects.all()
    return render(request, 'post.html',{"username": username, "objects": objects, "comments": comments})
Beispiel #4
0
def sumar_post(request, slug):
    template = 'temas/nuevo_post.html'
    if request.method == "POST":
        form = FormNuevoPost(request.POST)
        if form.is_valid():
            texto = form.cleaned_data.get('texto')
            perfil_usuario = Perfiles.objects.get(usuario=request.user)
            tema_contenedor = get_object_or_404(Temas, slug=slug)
            post = Posts(texto=texto, creador=perfil_usuario,
                         tema=tema_contenedor)
            post.save()

            perfil_usuario.numero_de_posts = perfil_usuario.numero_de_posts + 1
            perfil_usuario.save()

            # calcular nivel actividad y de popularidad del Tema
            popularidad_actividad_tema(tema_contenedor, "positivo")

            return HttpResponseRedirect(reverse('temas:index_tema',
                                        kwargs={'slug': tema_contenedor.slug, 'queryset': u'recientes'}))

    form_nuevo_post = FormNuevoPost()
    tema_contenedor = get_object_or_404(Temas, slug=slug)

    context = {'form_nuevo_post': form_nuevo_post, 'tema': tema_contenedor}
    return render(request, template, context)
Beispiel #5
0
def newPost():
    error = None
    form = PostsForm(CombinedMultiDict((request.files, request.form)))
    if request.method == 'POST' and form.validate_on_submit():
        if form.photo.data:
            photo = form.photo.data
            caption = form.caption.data
            if photo.filename == '':
                error = 'No selected file'
            if photo and allowed_file(photo.filename):
                filename = secure_filename(photo.filename)
                newpost = Posts(user_id=current_user.id,
                                image_URI=photo,
                                caption=caption)
                photo.save(os.path.join(newpost.image_URI, filename))
                db.session.add(newpost)
                db.session.commit()
                return jsonify({'messages': 'Photo Post successfully'})
            else:
                error = 'File not allowed'
                return jsonify({'errors': error})
        else:
            caption = form.caption.data
            newpost = Posts(user_id=current_user.id, caption=caption)
            db.session.add(newpost)
            db.session.commit()
            return jsonify({'messages': 'Post successfully'})
    else:
        return jsonify({'errors': form_errors(form)})
Beispiel #6
0
 def get(self, page):
     if page == None or int(page) == 0:
         prevPage = None
         nextPage = '1'
     elif int(page) == 1:
         prevPage = '0'
         nextPage = str(int(page) + 1)
     elif int(page) > 1:
         prevPage = str(int(page) - 1)
         nextPage = str(int(page) + 1)
     numPosts = Posts.select().count()
     numPages = math.ceil(numPosts / 5)
     categories = Posts.select(Posts.category).distinct()
     posts = Posts.select().order_by(Posts.created.desc()).paginate(
         int(nextPage), 5)
     if self.current_user:
         loggedInUser = self.current_user
         return self.render_template(
             "home.html", {
                 'posts': posts,
                 "categories": categories,
                 "numPages": str(numPages),
                 "prevPage": prevPage,
                 "nextPage": nextPage,
                 'loggedInUser': loggedInUser
             })
     return self.render_template(
         "home.html", {
             'posts': posts,
             "categories": categories,
             "numPages": str(numPages),
             "prevPage": prevPage,
             "nextPage": nextPage
         })
Beispiel #7
0
def recent_feed():
    feed = AtomFeed('Recent Articles',
                    feed_url=request.url, url=request.url_root)
    posts = Posts()
    feed = posts.add_to_feed(feed, request.url)

    return feed.get_response()
Beispiel #8
0
def recent_feed():
    feed = AtomFeed('Recent Articles',
                    feed_url=request.url,
                    url=request.url_root)
    posts = Posts()
    feed = posts.add_to_feed(feed, request.url)

    return feed.get_response()
Beispiel #9
0
 def form_valid(self, form):
     name               = form.cleaned_data['name']
     description        = form.cleaned_data['description']
     new_obj            = Posts()
     new_obj.name       = name
     new_obj.decription = description
     new_obj.save()
     self.set_message(u'Должность успешно добавлена.')
     return super(AddPostView, self).form_valid(form)
Beispiel #10
0
def _get_posts_by_page():
    """

    :return:posts, page
    """
    total = Posts.count_all()
    page = Page(total, _get_page_index(), 10)
    posts = Posts.find_by('order by post_date desc limit ?,?', page.offset, page.limit)
    return posts, page
Beispiel #11
0
 def post(self, slug):
     post = Posts.select().where(Posts.id == slug)
     if post:
         post = Posts.select().where(Posts.id == slug).get()
         user = self.current_user
         # Only allow the creator of the post access to edit
         if post.user_id == user.id:
             post.delete_instance(recursive=True, delete_nullable=True)
     return self.redirect("/")
Beispiel #12
0
 def get(self, slug):
     post = Posts.select().where(Posts.id == slug)
     if post:
         post = Posts.select().where(Posts.id == slug).get()
         user = self.current_user
         # Only allow the creator of the post access to edit
         if post.user_id == user.id:
             return self.render_template("edit_post.html", {'post': post})
     return self.redirect("/")
Beispiel #13
0
def edit_a_post_view(postkey=None):

    form = PostForm()
    posts = Posts()
    uploadform = UploadForm()
    passed_days, remaining_days = calculate_work_date_stats()
    site_updated = posts.site_last_updated()
    return render_template('posts.html',user_status=users.is_current_user_admin(),siteupdated=site_updated,\
                           daysleft=remaining_days,dayspassed=passed_days,
                           codeversion=CODEVERSION, form=form, uploadform=uploadform)
Beispiel #14
0
def edit_a_post_view(postkey=None):

    form = PostForm()
    posts = Posts()

    passed_days, remaining_days = calculate_work_date_stats()
    site_updated = posts.site_last_updated()
    return render_template('posts.html',user_status=users.is_current_user_admin(),siteupdated=site_updated,\
                           daysleft=remaining_days,dayspassed=passed_days,
                           codeversion=CODEVERSION, form=form)
Beispiel #15
0
def post(request):
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            post_body=form.cleaned_data['post_body']
            p=Posts(body=post_body,time=datetime.now(),user=request.user)
            p.save()
    return redirect('index')

    def like(request):
        p=Posts(body=post_body,time=datetime.now(),user=user)
        p.save()
    return redirect('index')
Beispiel #16
0
	def post(self):
		title = self.request.get("subject");
		text = self.request.get("content");
		title = self.removeSpaces(title);
		text = self.removeSpaces(text);
		if not self.validatePost(title,text):
			self.writeForm(error=True,title=title,text=text);
		else:
			post = Posts(title=title,text=text);
			post.put();
			released_url = week3_permalink_url.replace('(\d+)',str( post.key.id() ) )
			time.sleep(1);
			self.redirect(released_url);
Beispiel #17
0
    def post(self):
        checkLoggedInAndRegistered(self)

        profile = users.get_current_user()

        post = Posts(title=self.request.get('title-first-ln'),
                     description=self.request.get('description-second-ln'),
                     owner=profile.nickname(),
                     phone=self.request.get('phone-number'),
                     complexity=self.request.get('post-type'))
        post_key = post.put()
        self.response.write("Posts created: " + str(post_key) + "<br>")
        self.response.write("<a href='/'>Home</a> | ")
        self.response.write("<a href='/profileposts'>My posts</a>")
Beispiel #18
0
    def post(self):
        checkLoggedInAndRegistered(self)

        profile = users.get_current_user()

        post = Posts(
            title=self.request.get('title-first-ln'),
            description=self.request.get('description-second-ln'),
            owner=profile.nickname(),
            phone=self.request.get('phone-number'),
            complexity=self.request.get('post-type'),
        )
        post_key = post.put()
        self.redirect("/profileposts")
Beispiel #19
0
def search(page=1):
    q = request.args['keyword'].split('/page')[0]
    ids = Posts.search_keyword(q)
    print ids
    if ids:
        mess = Posts.search_news_by_page(page,ids)
        pageCount = Posts.get_per_count(len(ids))
        pageurl = "/search?keyword="+q+"/page="
        return render_template('Home/index.html', msgs=mess, currentPage=page, pageCount=pageCount,pageurl=pageurl)
    else:
        id = 0
        mess = Posts.get_a_post(id)
        pageurl = "/search?keyword="+q+"/page="
        return render_template('Home/index.html', msgs=mess, currentPage=1, pageCount=1,pageurl=pageurl)
Beispiel #20
0
def newpost():
    if not session.get('logged_in'):
        return redirect(url_for('login'))
    userid = session.get('userid')
    rannew = time.time()
    if request.method == 'POST':
        title = request.form['title']
        date = request.form['date']
        local = request.form['local']
        tags = request.form['tags']
        rannew = request.form['rannew']
        content = request.form['content']
        Posts.add_a_post(title, date, local, tags, content, userid, rannew)
        return redirect(url_for('index'))
    return render_template('New/index.html', rannew=rannew)
Beispiel #21
0
def searchsite():

    query_string = request.args.get('query', '')
    try:

        results = query_search_index(query_string)
        posts_ids = find_posts_from_index(results)
        posts = Posts()
        posts.filter_matched(posts_ids)
        data = posts.to_json()
    except Exception as e:
        logging.error("error while searching {}".format(e))
        data = "something went wrong while searching"

    return jsonify(data=data)
Beispiel #22
0
def searchsite():

    query_string = request.args.get('query', '')
    try:

        results = query_search_index(query_string)
        posts_ids = find_posts_from_index(results)
        posts = Posts()
        posts.filter_matched(posts_ids)
        data = posts.to_json()
    except Exception as e:
        logging.error("error while searching {}".format(e))
        data = "something went wrong while searching"

    return jsonify(data=data)
Beispiel #23
0
	def get(self,ids):
		ID = int(ids);
		self.post = Posts.get_by_id(ID);
		if self.post:
			self.writeForm();
		else:
			self.redirect(week3_blog_url);
Beispiel #24
0
 def post(self):
     print("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&")
     postid = self.request.get("postid")
     post = Posts.get_by_id(int(postid))
     post.key.delete()
     print(self.request.get("postid"))
     self.redirect("/profileposts")
Beispiel #25
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"
Beispiel #26
0
def get_selected_post(id):
    if id and is_number(id):
        q = Post.select().where(Post.id == int(id))
        selected_post = [u for u in q][0]
    else:
        selected_post = None
    return selected_post
Beispiel #27
0
def newpost():
    if request.method == 'POST':
        title = request.form['title']
        body = request.form['body']
        title_error = ''
        body_error = ''
        bad_field = 0
        if empty(body) == False:
            body_error = 'Please fill in the body.'
            bad_field += 1
        if empty(title) == False:
            title_error = 'Please fiil in the title.'
            bad_field += 1
        if bad_field > 0:
            return render_template('newpost.html',
                                   title=title,
                                   body=body,
                                   title_error=title_error,
                                   body_error=body_error)
        owner = Users.query.filter_by(user=session['user']).first()
        author = session['user']
        new_post = Posts(title, body, owner, author)
        db.session.add(new_post)
        db.session.commit()
        return render_template('viewpost.html', post=new_post)
    if session['user']:
        return render_template('newpost.html')
    else:
        return redirect('/login')
def get_posts_by_user_id(id):
    with sqlite3.connect("./rare.db") as conn:
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        # Use a ? parameter to inject a variable's value
        # into the SQL statement.
        db_cursor.execute(
            """
        SELECT
            p.id,
            p.user_id,
            p.category_id,
            p.title,
            p.publication_date,
            p.content
        FROM posts p
        WHERE p.user_id = ?
        """, (id, ))

        posts = []

        #convert rows into a python list
        dataset = db_cursor.fetchall()

        #Iterate through list of data returned
        for row in dataset:

            post = Posts(row["id"], row["user_id"], row["category_id"],
                         row["title"], row["publication_date"], row["content"])

            #add post to posts
            posts.append(post.__dict__)

        return json.dumps(posts)
 def POST(self):
     data = web.input()
     post = Posts.Posts()
     data.username = session_data["user"]["username"]
     new_post = post.insert_post(data)
     if new_post:
         return 'success'
def get_all_posts():
    with sqlite3.connect("./rare.db") as conn:
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        db_cursor.execute("""
        SELECT  
            p.id,
            p.user_id,
            p.category_id,
            p.title,
            p.publication_date,
            p.content
        FROM posts p
        """)

        posts = []

        #convert rows into a python list
        dataset = db_cursor.fetchall()

        #Iterate through list of data returned
        for row in dataset:

            post = Posts(row["id"], row["user_id"], row["category_id"],
                         row["title"], row["publication_date"], row["content"])

            #add post to posts
            posts.append(post.__dict__)

        return json.dumps(posts)
def get_single_post(id):
    with sqlite3.connect("./rare.db") as conn:
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        # Use a ? parameter to inject a variable's value
        # into the SQL statement.
        db_cursor.execute(
            """
        SELECT
            p.id,
            p.user_id,
            p.category_id,
            p.title,
            p.publication_date,
            p.content
        FROM posts p
        WHERE p.id = ?
        """, (id, ))

        # Load the single result into memory
        data = db_cursor.fetchone()

        # Create an post instance from the current row
        post = Posts(data["id"], data["user_id"], data["category_id"],
                     data["title"], data["publication_date"], data["content"])

    return json.dumps(post.__dict__)
def add_post():
    form = CreatePost()
    if request.method == 'POST' and form.validate_on_submit():
        """ Get image info """
        if (form.image.data):
            image = form.image.data
            """ Create new file name """
            old_filename, extension = os.path.splitext(image.filename)
            filename = str(int(calendar.timegm(time.gmtime()))) + extension
            """ Check directory """
            directory = os.path.join(app.config['UPLOAD_FOLDER'],
                                     str(g.user.get_id()))
            if not os.path.exists(directory):
                os.makedirs(directory)
            """ Save image """
            image.save(os.path.join(directory, filename))
        else:
            filename = None
        """ Add post to DB """
        new_post = Posts(user_id=g.user.get_id(),
                         title=form.title.data,
                         text=form.text.data,
                         pub_date=form.date.data,
                         img=filename,
                         public=form.public.data)
        db.session.add(new_post)
        db.session.commit()
        """ Success message """
        flash('Done')
        return (redirect(url_for("index")))
    return render_template('addpost.html', title='Create new post', form=form)
    def POST(self):
        data = web.input()
        data.username = session_data['user']['username']

        post_model = Posts.Posts()
        post_model.insert_post(data)
        return "success"
Beispiel #34
0
def add_posts(user_id):
    pForm = NewPostForm()
    uFolder = app.config['UPLOAD_FOLDER']
    
    myid = int(user_id)
    
    if request.method == "POST" and pForm.validate_on_submit():
        caption = request.form['caption']
        pic = request.files['photo']
        
        filename = secure_filename(pic.filename)
        pic.save(os.path.join(uFolder, filename))
        
        now = datetime.datetime.now()
        created = "" + format_date_joined(now.year, now.month, now.day)
        
        myPost = Posts(myid, filename, caption, created)
        
        db.session.add(myPost)
        db.session.commit()
        
        info = {'message': 'Successfully created a new post'}
        
        return jsonify(info=info)
    else:
        errors = form_errors(pForm)
        
        return jsonify(errors=errors)
Beispiel #35
0
def get_selected_post(id):
    if id and is_number(id): 
        q = Post.select().where(Post.id == int(id))
        selected_post = [u for u in q][0]
    else: 
        selected_post = None 
    return selected_post
def add_post(user_id):
    form = PostForm()
    if request.method == "POST":
        if form.validate_on_submit():
            userid = user_id
            caption = request.form['caption']
            photo  = request.files['postimage']
            post_date = datetime.datetime.now()
            
            post_photo = secure_filename(photo.filename)
            post = Posts(user_id = userid, postimage = post_photo, caption = caption, created_on = post_date)
            
            db.session.add(post)
            db.session.commit()
            
            photo.save(os.path.join(filefolder, post_photo))
            return jsonify({'message':"Successfully created a new post"})
            
    elif request.method == "GET":
        user = Users.query.filter_by(id = user_id).first()
        if not user:
            return jsonify({'message': "no user found"})
        user_posts = Posts.query.filter_by(user_id = user_id).all()
        
        userposts = []
        for user_post in user_posts:
            post_data = {'id':user_post.id,'user_id': user_post.user_id,'postimage': user_post.post_photo,'caption': user_post.caption,'created_on': user_post.post_date}
            userposts.append(post_data)
        return jsonify(data = userposts)
    error_msgs = form_errors(form)
    error = [{'errors': error_msgs}]
    return jsonify(errors = error)
Beispiel #37
0
def api_get_post(post_id):
    post_data = Posts.get(post_id)
    if post_data:
        print post_data
        print 'api'
        return dict(name=post_data.post_name, excerpt=post_data.post_excerpt, content=post_data.post_content)
    raise APIResourceNotFoundError('post')
Beispiel #38
0
 def post(self, slug):
     post = Posts.select().where(Posts.id == slug)
     if post:
         post = Posts.select().where(Posts.id == slug).get()
         loggedInUser = self.current_user
         print(post.id, 'post id')
         # Only allow the creator of the post access to edit
         if post.user_id == loggedInUser.id:
             title = self.get_body_argument('title')
             category = self.get_body_argument('category')
             post = self.get_body_argument('post')
             # Edit Post
             Posts.update(title=title, category=category,
                          post=post).where(Posts.id == slug).execute()
             return self.redirect("/post/" + slug)
     return self.redirect("/")
Beispiel #39
0
def api_delete_post(post_id):
    check_admin()
    post_data = Posts.get(post_id)
    if not post_data:
        raise APIResourceNotFoundError('blog')
    post_data.delete()
    return dict(post_id=post_id)
Beispiel #40
0
def posts(user_id):
    error=None
    form = PostsForm()
    if request.method =='POST':
        if form.validate_on_submit():
            photo = form.photo.data
            caption = form.caption.data
            filename = secure_filename(photo.filename)
            added_on=datetime.datetime.now()
            newpost=Posts(user_id=user_id,photo=filename,caption=caption,created_on=added_on)
            photo.save(os.path.join(uploadfolder, filename))
            db.session.add(newpost)
            db.session.commit()
            return jsonify(response="Your post was added successfully")
        else:
            return jsonify({'errors':form_errors(form)})
    if request.method=='GET':
        def following(user_id):
            isfollower=Follows.query.filter_by(follower_id=session['userid'],user_id=user_id).first()
            if isfollower:
                return True
            else:
                return False
        user=Users.query.filter_by(id=user_id).first()
        if not user:
            return jsonify(error={'error':'User does not exist'});
        else:
            userinfo={'userid':user.id,'username':user.username,'first_name':user.first_name,'last_name':user.last_name,'location':user.location,'photo':uploadfolder+user.profile_photo,'biography':user.biography,'membersince':user.joined_on.strftime("%B %Y")}
            posts=[{'photo':uploadfolder+x.photo,'caption':x.caption} for x in Posts.query.filter_by(user_id=user_id).all()]
            follows=Follows.query.filter_by(user_id=user_id).all()
            return jsonify(response={'userinfo':userinfo,'posts':posts,'numposts':len(posts),'numfollowers':len(follows),'following':following(user_id)})
Beispiel #41
0
def respuesta(request, slug, post_id):
    # Maneja la respuesta del usuario a un post. Cualquier post, sea respuesta o en video.
    tema = Temas.objects.get(slug=slug)
    if request.method == "POST":
        form = FormNuevoPost(request.POST)
        if form.is_valid():
            texto = form.cleaned_data.get('texto')
            perfil_usuario = Perfiles.objects.get(usuario=request.user)
            post_padre = Posts.objects.get(id=post_id)
            # Si es una respuesta a un post en un video
            if post_padre.video is not None:
                post_respuesta = Posts(texto=texto, es_respuesta=True,
                                       creador=perfil_usuario, tema=tema, video=post_padre.video)
            else:
                post_respuesta = Posts(texto=texto, es_respuesta=True,
                                       creador=perfil_usuario, tema=tema)

            post_respuesta.save()

            # Respuesta object
            respuesta_db = Respuestas(post_respuesta=post_respuesta,
                                      post_padre=post_padre)
            respuesta_db.save()

            #Notificacion respuesta
            if perfil_usuario != post_padre.creador:
                notificacion_respuesta = Notificacion(actor=perfil_usuario, target=post_padre.creador,
                                                      objeto_id=post_padre.id, tipo_objeto="post",
                                                      tipo_notificacion="comment")
                notificacion_respuesta.save()

            # Redirige a la pagina del post_video si pertenece a un video
            if post_padre.video is not None:
                return HttpResponseRedirect(reverse('videos:post_video',
                                                    kwargs={
                                                        'video_id': post_padre.video.id, 'slug': tema.slug,
                                                        'post_id': post_id,
                                                        'queryset': u'recientes'}))
            # Redirige a la pagina del post.
            else:
                return HttpResponseRedirect(reverse('temas:post',
                                                    kwargs={'slug': tema.slug, 'post_id': post_id,
                                                            'queryset': u'recientes'}))
    else:
        return HttpResponseRedirect(reverse('temas:post',
                                            kwargs={'slug': tema.slug, 'post_id': post_id,
                                                    'queryset': u'recientes'}))
def search_all(query, delta):
    #convert delta to int/check if its unicode
    # if its unicode then no time filter was set
    #anticipating an error if delta is passed as None, because no time filter is set
    try:
        delta = int(delta)
        check_delta = True
    except ValueError:
        check_delta = False
    if check_delta:
        # if delta is an int search this way
       results = Posts.search_by_time_delta(Posts.search_all, delta, query)
       flash("searched by time delta")
    else:
        results = Posts.search_all(query)
        flash("searched all posts")
    return render_template('all_results.html', results=results)
Beispiel #43
0
 def get(self):
     path = os.path.join(os.path.dirname(__file__), '../templates/view.html')
     post_query = Posts.Post().query().order(-Posts.Post.date)
     posts = post_query.fetch()
     template_values = {
         'posts': posts
     }
     self.response.out.write(template.render(path, template_values))
Beispiel #44
0
def createPost(postObj):
    print "in"
    try:
        user = Sngusers.objects.get(user=postObj.user)
    except:
        user=None
    posts = Posts(tag=postObj.tag,
                  title=postObj.title,
                  user = user,
                  content = postObj.content,
                  image = postObj.image,
                  
                               )
    if posts.save():
        return True
    else:
        return False
Beispiel #45
0
 def get(self, slug):
     post = Posts.select().where(Posts.id == slug)
     if post:
         post = Posts.select().where(Posts.id == slug).get()
         comments = Comments.select().where(
             Comments.post_id == slug).order_by(Comments.created.desc())
         # number of likes
         likes = Likes.select().where(Likes.post_id == slug).count()
         loggedInUser = self.current_user
         return self.render_template(
             "post.html", {
                 'post': post,
                 'comments': comments,
                 'likes': likes,
                 'loggedInUser': loggedInUser
             })
     return self.redirect("/")
Beispiel #46
0
def posts_create():
    form = forms.PostForm(request.form)
    if request.method == 'POST' and form.validate():
        content = form.content.data
        post = Posts(content=content)
        db.session.add(post)
        db.session.commit()
    return render_template('posts/show.html', post=post)
Beispiel #47
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")
Beispiel #48
0
def post_view(post_id):
    post_data = Posts.get(post_id)
    if post_data is None:
        raise notfound()
    post_data.post_content = markdown.markdown(post_data.post_content, extensions=['markdown.extensions.nl2br', 'markdown.extensions.fenced_code', 'markdown.extensions.codehilite', 'markdown.extensions.toc'], extension_configs={'markdown.extensions.codehilite':{
        'linenums':True
    }})
    # logging.info(post_data.post_content)
    # print post_data.post_content
    return dict(post=post_data, user=ctx.request.user)
Beispiel #49
0
def manage_posts_edit(post_id):
    """
    博客编辑页
    :param post_id:
    :return:
    """
    post_data = Posts.get(post_id)
    if post_data is None:
        raise notfound()
    return dict(id=post_id, action='/api/posts/%s' % post_id, redirect='/manage/posts', user=ctx.request.user)
 def show_main(self):
     """
     Show the main page
     """
     posts = Posts.get_posts(10)
     logging.info(self.current_user)
     args = dict(current_user=self.current_user,
                 facebook_app_id=self.app.config.get("FACEBOOK_APP_ID", ""),
                 posts=posts)
     logging.info(str(args))
     self.response.out.write(self.template.render(args))
Beispiel #51
0
def api_create_post():
    """
    博客创建
    :return:
    """
    check_admin()
    i = ctx.request.input(name='', excerpt='', content='')
    name = i.name.strip()
    excerpt = i.excerpt.strip()
    content = i.content.strip()
    if not name:
        raise APIValueError('name', 'name cannot be empty.')
    if not excerpt:
        raise APIValueError('excerpt', 'excerpt cannot be empty.')
    if not content:
        raise APIValueError('content', 'content cannot be empty.')
    user = ctx.request.user
    posts = Posts(post_name=name, post_excerpt=excerpt, post_content=content, post_author=user.user_name)
    print posts
    posts.insert()
    return posts
Beispiel #52
0
def new_thread(request):
    page_title       = 'new_thread'
    new_post_text    = request.POST['post_text']
    new_username     = request.POST['username']
    new_thread_title = request.POST['title']
    new_date_posted  = datetime.datetime.now()

    if new_post_text.strip() == "" or new_username.strip() == "" or new_thread_title.strip() == "":
        return HttpResponseRedirect(reverse('new_thread_error'))
    
    # Create the thread 
    new_thread = Threads(thread_title = new_thread_title, username = new_username, date_posted = new_date_posted) 
    new_thread.save()    

    # Create the dummy post. This post is the parent of all the top level
    # posts in this thread.  Being a dummy post, it contains no text
    dummy_post = Posts(parent_id = 0, date_posted = new_date_posted, thread_id = new_thread.thread_id, deleted = False, username = new_username)
    dummy_post.save()
    
    # Set the new thread's first post to the dummy post
    new_thread.first_post_id = dummy_post.post_id
    new_thread.save()
    
    # Insert the actual first post into the table
    first_post = Posts(parent_id = dummy_post.thread_id, username = new_username, post_text = new_post_text, date_posted = new_date_posted, thread_id = new_thread.thread_id, deleted = False )
    first_post.save()
  
    return HttpResponseRedirect(reverse('index'))
Beispiel #53
0
def new_post(request):


    new_username    = request.POST['username']
    new_post_text   = request.POST['post_text'] 
    new_date_posted = datetime.datetime.now()
    new_parent_id   = request.POST['parent_id']
    new_thread_id   = request.POST['thread_id']
   
   
    if new_username.strip() == "" or new_post_text.strip() == "":
        template = loader.get_template('forum/new_post_error.html')
        title    = "Error creating thread"
        context  = RequestContext(request,{"title":title,"thread_id":new_thread_id})
        return HttpResponse(template.render(context))  
   
    post = Posts(username = new_username, post_text = new_post_text, date_posted = new_date_posted, parent_id = new_parent_id, deleted = False, thread_id = new_thread_id)
    post.save()
    
    response = redirect('view_thread')
    response['Location'] += '?thread_id='+str(new_thread_id)
    return response
def search_community_results(community, query, delta):
    #same thing as above, check if delta is an int or unicode
    try:
        delta = int(delta)
        check_delta = True
    except ValueError:
        check_delta = False
    c = Community.query.filter_by(name=community).first()
    if check_delta:
        # same thing, if time filter is present search by time delta
       results = Posts.search_by_time_delta(Posts.search_by_community, delta, query, c)
       flash("searched by time delta")
    else:
        results = Posts.search_by_community(query, c)
        flash("searched all posts")
    kwargs = {
        'community': community,
        'c': c,
        'results': results,
        'query': query
    }
    return render_template('community_results.html', **kwargs)
    def post(self):
        """
        
        Save the Posts for the given User, and delete old Posts
        
        :param str channel: User name, which posts we will save
        """
        channel = self.request.get('channel')
        graph = facebook.GraphAPI(self.current_user.access_token)
        profile = graph.get_object("me")
        logging.info(str(profile))

        posts = None
        try:
            posts = graph.get_object(channel+"/posts", limit=20)
        except Exception as e:
            logging.info(str(e))
#         else:
#             logging.info(posts["data"])
        Posts.refresh_db(posts["data"])

        self.show_main()
 def post(self):
     if self.session.get("username"):
         form = PostsForm(self.request.POST)
         # Get the userID in order to associate it with the post
         username = self.session.get("username")
         user = db.GqlQuery("SELECT * FROM User WHERE username='******'"
                            % username)
         userID = user.get()
         userID = userID.key().id()
         # if the form is valid add the post to the datastore and then
         # redirect to the detail View of the post.
         if form.validate():
             newPost = Posts(title=form.title.data,
                             content=form.content.data,
                             accessLevel=form.accessLevel.data,
                             author=userID)
             newPost.put()
             self.redirect("/post/%s" % newPost.key().id())
         else:
             self.render("newPost.html", form=form,
                         username=self.session.get("username"))
     else:
         self.redirect("/register")
Beispiel #57
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({})
Beispiel #58
0
def api_update_post(post_id):
    """
    博客修改
    :param post_id:
    :return:
    """
    check_admin()
    i = ctx.request.input(name='', excerpt='', content='')
    name = i.name.strip()
    excerpt = i.excerpt.strip()
    content = i.content.strip()
    if not name:
        raise APIValueError('name', 'name cannot be empty.')
    if not excerpt:
        raise APIValueError('excerpt', 'excerpt cannot be empty.')
    if not content:
        raise APIValueError('content', 'content cannot be empty.')
    post_data = Posts.get(post_id)
    post_data.post_name = name
    post_data.post_excerpt = excerpt
    post_data.post_content = content
    post_data.post_modified = time.time()
    post_data.update()
    return post_data
Beispiel #59
0
def promote(id):
    app.logger.debug("getting to promote post, id is %s" % id)
    if ('username' in session):
        q = Post.update(promoted=True).where(Post.id == id)
        q.execute()
    return redirect(url_for('show_posts_beta'))