コード例 #1
0
def save_post(request):
    cur_user = request.user
    if request.method == 'POST':
        subject = request.POST['subject']
        content = request.POST['content']
        new_post = Post(user_id=cur_user, subject=subject, content=content)
        new_post.save()
        redirect('home')

    return redirect('home')
コード例 #2
0
def send_message(title, body, image, video, user_post):
    import uuid
    nameFile = str(uuid.uuid4())[:12]
    user_postv = User.objects.get(username=user_post)
    imgstr = re.search(r'base64,(.*)', image).group(1)
    # path = default_storage.save('%s.png' % nameFile, ContentFile(imgstr))
    img_file = open("media/%s.png" % nameFile, 'wb')
    img_file.write(base64.b64decode(imgstr))
    img_file.close()

    # user_postv = User.objects.get(username=user_post)
    post = Post()
    post.title = title
    post.body = body
    # post.image = default_storage.save('%s.png' % nameFile, ContentFile(imgstr))
    post.image = nameFile
    post.video = video
    # post.audio = audio
    post.user_post = user_postv
    post.save()

    user_post = str(user_post)

    r = redis.StrictRedis()

    if user_post:
        r.publish(
            "".join(["/"]),
            json.dumps({
                "timestamp": dateformat.format(post.date_post, 'U'),
                "image": nameFile,
                "user_post": user_post,
                "title": title,
                "id": post.id
            }))
コード例 #3
0
ファイル: views.py プロジェクト: UA-girl/DjangoApp
def add_post(request):
    token = request.META.get('HTTP_AUTHORIZATION', " ").split(' ')[1]
    payload = jwt_decode_handler(token)
    user_id = payload['user_id']
    try:
        user = User.objects.get(pk=user_id)
        post = Post(user=user,
                    title=request.data['title'],
                    text=request.data['text'])
        post.save()
        return Response('Success', status=status.HTTP_201_CREATED)
    except Exception:
        return Response('Error', status.HTTP_401_UNAUTHORIZED)
コード例 #4
0
    def post(self):
        """ Actions to post, edit, and update comments on the post. """

        user_name = self.user.name
        # Post a comment
        if self.request.get('comment'):
            comment = self.request.get('comment')  # comment content
            author = user_name
            post_id = self.request.get('post_id')
            post = Post.by_id(int(post_id))
            comment = Comment(author=author, comment=comment, parent=post.key)
            comment.put()
            self.redirect('/post?post_id=' + post_id)
        # Delete an existing comment
        elif self.request.get('delete'):
            post_id = self.request.get('post_id')
            post = Post.by_id(int(post_id))
            comment_id = int(self.request.get('delete'))
            comment_to_delete = Comment.get_by_id(comment_id, parent=post.key)
            comment_to_delete.key.delete()
            self.redirect('/post?post_id=' + post_id)
        # Edit an existing comment
        elif self.request.get('edit'):
            post_id = self.request.get('post_id')
            post = Post.by_id(int(post_id))
            comment_id = int(self.request.get('edit'))
            comment_to_edit = Comment.get_by_id(comment_id, parent=post.key)
            if self.user.name == comment_to_edit.author:  # Verify user is author
                self.render('editcomment.html',
                            comment=comment_to_edit,
                            user_name=user_name,
                            comment_id=comment_id,
                            post_id=post_id)
                return
            else:
                self.redirect('/post?post_id=' +
                              post_id)  # Wish I could flash error msg

        elif self.request.get('update'):
            post_id = self.request.get('post_id')
            post = Post.by_id(int(post_id))
            comment_id = int(self.request.get('update'))
            comment_to_update = Comment.get_by_id(comment_id, parent=post.key)
            updated_comment_contents = self.request.get('updated-comment')
            updated_comment_contents = cgi.escape(updated_comment_contents)
            comment_to_update.comment = updated_comment_contents
            comment_to_update.put()
            self.redirect('/post?post_id=' + post_id)
        else:
            self.redirect('/')
コード例 #5
0
    def setUp(self):
        self.now = datetime.datetime.utcnow().replace(tzinfo=utc)
        self.timedelta = datetime.timedelta(15)
        author = User.objects.get(pk=1)

        for count in range(1, 11):
            post = Post(title="Test Post %d Title" % count,
                        text="foo", author=author)

            if count < 6:
                pubdate = self.now - self.timedelta * count
                post.published_date = pubdate

            post.save()
コード例 #6
0
ファイル: routes.py プロジェクト: sanix-sandel/EkoBFinal
def Newpost(title, category):
    if not current_user.is_publisher():
        flash('You have to contact the admin for access', 'danger')
        return redirect(url_for('main.home'))
    tags = Tag.query.all()

    if request.method == 'POST':
        content = request.form.get('summernote')
        if content == "":
            flash('The post must have a content', 'danger')
            return redirect(url_for('main.home'))
        else:
            post = Post(title=title.title(),
                        content=content,
                        author=current_user,
                        category=category)

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

            flash(
                'Your post has been created and saved ! But you have to select some tags please',
                'succes')
            return redirect(url_for('posts.tagin', post_id=post.id))
    return render_template('new_post.html', title='New Post', tags=tags)
コード例 #7
0
ファイル: routes.py プロジェクト: sridvana/flaskblog
def index():
    form = PostForm()
    if form.validate_on_submit():
        language = guess_language(form.post.data)
        if language == 'UNKNOWN' or len(language) > 5:
            language = ''
        post = Post(body=form.post.data,
                    author=current_user,
                    language=language)
        db.session.add(post)
        db.session.commit()
        flash(_('Your post is now live!'))
        return redirect(url_for('index'))
    page = request.args.get('page', 1, type=int)
    posts = current_user.followed_posts().paginate(
        page, app.config['POSTS_PER_PAGE'], False)
    next_url = url_for('index', page=posts.next_num) \
        if posts.has_next else None
    prev_url = url_for('index', page=posts.prev_num) \
        if posts.has_prev else None
    return render_template('index.html',
                           title=_('Home'),
                           form=form,
                           posts=posts.items,
                           next_url=next_url,
                           prev_url=prev_url)
コード例 #8
0
def index():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(body=form.post.data, author=current_user)
        db.session.add(post)
        db.session.commit()
        flash('Your post is now live!')
        return redirect(url_for('main.index'))
    # page is used by SQLAlchemy object to retrieve next set
    # of data
    page = request.args.get('page', 1, type=int)
    if current_user.is_authenticated:
        posts = current_user.followed_posts().paginate(
            page, current_app.config['POSTS_PER_PAGE'], False)
    else:
        posts = Post.query.order_by(Post.timestamp.desc()).paginate(
            page, current_app.config['POSTS_PER_PAGE'], False)

    next_url = url_for('main.index', page=posts.next_num) \
        if posts.has_next else None
    prev_url = url_for('main.index', page=posts.prev_num) \
        if posts.has_prev else None

    return render_template('index.html',
                           title='Home',
                           form=form,
                           posts=posts.items,
                           next_url=next_url,
                           prev_url=prev_url)
コード例 #9
0
ファイル: routes.py プロジェクト: Hadas-edX/microblog
def new_post():
    form = PostForm()
    if form.validate_on_submit():
        p = Post(title = form.title.data, body = form.body.data,\
            subject = form.subject.data, user_id = current_user.id)
        db.session.add(p)
        db.session.commit()
        return redirect(url_for('index'))
    return render_template('new_post.html', form=form)
コード例 #10
0
def write():
	form = PostForm()
	if form.validate_on_submit():
		post = Post(title=form.title.data,content = form.content.data,user_id = current_user.id)
		db.session.add(post)
		db.session.commit()
		flash('Your post is now live!')
		return redirect(url_for('index'))
	return render_template('write.html',title='Write',form=form)
コード例 #11
0
ファイル: views.py プロジェクト: shabaz9786/Online-Chess
def add_posts(request):
    if request.method == 'POST':

        try:
            payload = json.loads(request.body)
            post_id = uuid.uuid4().hex[:10]
            title = payload['title']
            body = payload['body']
            posted_by = payload['posted_by']
            posted_date = int(time.time())
            post = Post(post_id, title, body, posted_by, posted_date,
                        posted_by, posted_date)
            post.save()
            response = json.dumps([{'success': 'Post added successfully!'}])
        except:
            response = json.dumps([{'error': 'Post could not be added!'}])
        return HttpResponse(response, content_type='text/json')
    else:
        response = json.dumps([{'error': 'Post could not be added!'}])
        return HttpResponse(response, status='404', content_type='text/json')
コード例 #12
0
 def get(self, user_name=''):
     error = ''
     if self.request.get('error'):
         error = self.request.get('error')
     posts = Post.query()
     posts = posts.order(-Post.created)
     posts = posts.fetch(10)
     name = ""
     if self.user:
         user_name = self.user.name
     self.render('home.html', posts=posts, user_name=user_name, error=error)
コード例 #13
0
ファイル: tests.py プロジェクト: sridvana/flaskblog
    def test_follow_posts(self):
        # create four users
        u1 = User(username='******', email='*****@*****.**')
        u2 = User(username='******', email='*****@*****.**')
        u3 = User(username='******', email='*****@*****.**')
        u4 = User(username='******', email='*****@*****.**')
        db.session.add_all([u1, u2, u3, u4])

        # create four posts
        now = datetime.utcnow()
        p1 = Post(body="post from john",
                  author=u1,
                  timestamp=now + timedelta(seconds=1))
        p2 = Post(body="post from susan",
                  author=u2,
                  timestamp=now + timedelta(seconds=4))
        p3 = Post(body="post from mary",
                  author=u3,
                  timestamp=now + timedelta(seconds=3))
        p4 = Post(body="post from david",
                  author=u4,
                  timestamp=now + timedelta(seconds=2))
        db.session.add_all([p1, p2, p3, p4])
        db.session.commit()

        # setup the followers
        u1.follow(u2)  # john follows susan
        u1.follow(u4)  # john follows david
        u2.follow(u3)  # susan follows mary
        u3.follow(u4)  # mary follows david
        db.session.commit()

        # check the followed posts of each user
        f1 = u1.followed_posts().all()
        f2 = u2.followed_posts().all()
        f3 = u3.followed_posts().all()
        f4 = u4.followed_posts().all()
        self.assertEqual(f1, [p2, p4, p1])
        self.assertEqual(f2, [p2, p3])
        self.assertEqual(f3, [p3, p4])
        self.assertEqual(f4, [p4])
コード例 #14
0
    def post(self):
        subject = self.request.get('subject')
        content = self.request.get('content')
        img_url = self.request.get('img_url')
        img_url_hash = self.request.get('img_url_hash')
        s_error = ''
        c_error = ''
        img_error = hasher.check_img_url_hash(
            img_url, img_url_hash)  # returns empty string if no error

        # Valid form data
        if (subject and content and img_url and not img_error):
            content = cgi.escape(content)
            content = content.replace('\n', '<br>')
            author = str(self.user.name)
            post = Post(parent=blog_key(),
                        subject=subject,
                        content=content,
                        author=author,
                        img_url=img_url,
                        like_count=0)
            post_key = post.put()
            post_id = post_key.id()
            self.redirect('/post?post_id=' + str(post_id))

        # Erroneous form data
        else:
            if not subject:
                s_error = "Please include a subject for your submission"
            if not content:
                c_error = "Please include content with your submission"
            if img_error:
                self.write(img_error)
            self.render('newpost.html',
                        s_error=s_error,
                        c_error=c_error,
                        subject=subject,
                        content=content,
                        img_url=img_url,
                        img_url_hash=img_url_hash)
コード例 #15
0
def new_post():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(title=form.title.data,
                    content=form.content.data,
                    author=current_user)
        db.session.add(post)
        db.session.commit()
        flash('your post has been created!', 'success')
        return redirect(url_for('home'))
    return render_template('create_post.html',
                           title='New post',
                           form=form,
                           legend='Update Post')
コード例 #16
0
 def post(self):
     """ Form action for likes. """
     post_id = self.request.get('liked')
     post = Post.by_id(int(post_id))
     if not self.user.name == post.author:  # Must not be author
         if not self.already_liked(post):
             self.like(post)
             self.redirect('/')
         else:
             error = "You already liked that item."
             self.redirect('/?error=' + error)
     else:
         error = "You can't like your own posts."
         self.redirect('/?error=' + error)
コード例 #17
0
 def post(self):
     # This POST option to edit is only exposed if logged-in user is author
     # See template viewpost.html
     if self.request.get('edit'):
         post_id = self.request.get('edit')
         post = Post.by_id(int(post_id))
         user_name = ""
         author = ""
         user_name = self.user.name
         if user_name == post.author:  # Double checks user is author
             post.content = post.content.replace('<br>', '')  # remove <br>s
             self.render('editpost.html', post=post)
         else:
             self.redirect('/')
     # This POST option to delete is only exposed if logged-in user is author
     # See template viewpost.html
     elif self.request.get('delete'):
         post_id = self.request.get('delete')
         post = Post.get_by_id(int(post_id), parent=blog_key())
         post.key.delete()
         self.redirect('/')
     # POST request to cancel editing (from editpost.html)
     elif self.request.get('cancel'):
         post_id = self.request.get('cancel')
         self.redirect('/post?post_id=' + post_id)
     # POST request to update post (from editpost.html)
     elif self.request.get('update'):
         post_id = self.request.get('update')
         post = Post.get_by_id(int(post_id), parent=blog_key())
         subject = self.request.get('subject')
         content = self.request.get('content')
         content = cgi.escape(content)
         content = content.replace('\n', '<br>')
         post.subject = subject
         post.content = content
         post.put()
         self.redirect('/post?post_id=' + post_id)
コード例 #18
0
def create_post():
    if request.method == "POST":
        title = request.form['title']
        body = request.form['body']
        try:
            post = Post(title=title, body=body)
            db.session.add(post)
            db.session.commit()
        except:
            print('Something wrong')

        return redirect(url_for('posts.index'))

    form = PostForm()
    return render_template('posts/create_post.html', form=form)
コード例 #19
0
ファイル: app.py プロジェクト: pitypec/flask-app-example
def create_post(current_user):
    if current_user is not None:
        if request.method == 'POST':
            parsejson = request.get_json()
            postdata = {
                "postbody": parsejson['body'],
                "post_image": parsejson['post_image']
            }
            user = User.query.get(current_user.id)
            post = Post(post_body=postdata['postbody'],
                        post_image=postdata['post_image'],
                        userposts=user)
            db.session.add(post)
            db.session.commit()
    return jsonify({"Message": "post successful"})
コード例 #20
0
def save_posts(request):
    count = Post.objects.count()
    html = "Add data in databse process started \n"
    res = []
    
    for i in range(1,501):
        res.append(Post(name="test"+str(i),description="test"+str(i),price=i))
    
    Post.objects.bulk_create(
        res
    )

    html += "Data addedd successfullyy!!!"

    return HttpResponse(html)    
コード例 #21
0
def post():
    """
    記事をポストするページ
    """
    form = PostForm()
    if form.validate_on_submit():
        article = Post(title=form.title.data,
                       author=current_user,
                       tag=form.tag.data,
                       body=form.body.data,
                       published_on=datetime.now())
        db.session.add(article)
        db.session.commit()
        print("post success")
        flash('Successfully posted')
        return redirect(url_for('index'))
    return render_template('post.html', form=form)
コード例 #22
0
 def get(self, **kw):
     post_id = self.request.get('post_id')
     post = Post.by_id(int(post_id))
     comments = Comment.query(ancestor=post.key)
     comments = comments.order(-Comment.created)
     comments = comments.fetch(5)
     user_name = ""
     user_is_author = False
     if self.user:
         user_name = self.user.name
         if post.author and user_name == post.author:
             user_is_author = True
     self.render('viewpost.html',
                 post=post,
                 user_name=user_name,
                 user_is_author=user_is_author,
                 comments=comments,
                 **kw)
コード例 #23
0
ファイル: views.py プロジェクト: roctbb/DjangoDiaryExample
def index(request):
    if not request.user.is_authenticated:
        return redirect('/login')

    if request.method == "GET":
        posts = Post.objects.filter(user=request.user).all()
        return render(request, 'index.html', {'posts': posts})
    else:
        post = Post()
        post.text = request.POST.get('text')
        post.user = request.user
        post.save()

        return redirect('/')
コード例 #24
0
 def test_string_representation(self):
     expected = "This is a title"
     p1 = Post(title=expected)
     actual = str(p1)
     self.assertEqual(expected, actual)
コード例 #25
0
def add_post(request):
    p = Post(header = request.POST['header'], text = request.POST['text'])
    p.save()
    return redirect('index')
コード例 #26
0
#!/usr/bin/env python
from datetime import datetime
from myapp import db
from myapp.models import User, Post

u1 = User(nickname='John', email='*****@*****.**')
u2 = User(nickname='Susan', email='*****@*****.**')
db.session.add(u1)
db.session.add(u2)

p1 = Post(body='My first post', timestamp=datetime.utcnow(), author=u1)
p2 = Post(body='My second post', timestamp=datetime.utcnow(), author=u1)
p3 = Post(body='The weather is hot', timestamp=datetime.utcnow(), author=u2)
p4 = Post(body='I need ice-cream', timestamp=datetime.utcnow(), author=u2)

db.session.add(p1)
db.session.add(p2)
db.session.add(p3)
db.session.add(p4)

db.session.commit()
コード例 #27
0
ファイル: seed.py プロジェクト: alvahdean/django-app-template
    def handle(self, *args, **options):
        # now do the things that you want with your models here
        password = "******"
        exp_posts = 50
        exp_users = 20
        avg_votes_per_post = 5
        avg_comments_per_post = 3

        # Post.objects.all().delete()

        rootExists = User.objects.filter(username="******").count()
        if (rootExists < 1):
            self.stdout.write("Creating root user")
            User.objects.create_superuser("root", "*****@*****.**", password)

        num_posts = Post.objects.all().count()
        num_users = User.objects.all().count()
        num_votes = Vote.objects.all().count()
        num_comments = Comment.objects.all().count()

        faker = Faker()

        self.stdout.write("Default password: "******"Number of posts: " + str(num_posts))
        self.stdout.write("Number of votes: " + str(num_votes))
        self.stdout.write("Number of comments: " + str(num_comments))
        self.stdout.write("Number of users: " + str(num_users))

        if (num_users < exp_users):
            self.stdout.write("Creating " + str(exp_users - num_users) +
                              " Users")
            for x in range(num_users + 1, exp_users + 1):
                username = faker.name().replace(" ", ".")
                email = username + "@test.com"
                User.objects.create_superuser(username, email, password)
                self.stdout.write("   " + username)
            num_users = User.objects.all().count()

        if (num_posts < exp_posts):
            self.stdout.write("Creating " + str(exp_posts - num_posts) +
                              " Posts")
            for x in range(num_posts + 1, exp_posts + 1):
                day_offset = randint(1, 364)
                pub_date = timezone.now() - datetime.timedelta(days=day_offset)
                u = self.randomUser()
                title = faker.text()
                self.stdout.write("   [" + u.username + "] " + title)
                rec = Post()
                rec.author = u
                rec.title = title
                rec.text = faker.text()
                rec.created_date = pub_date
                rec.published_date = pub_date
                rec.save()
            num_posts = Post.objects.all().count()

        self.stdout.write("Voting...")
        while (num_votes < avg_votes_per_post * num_posts):
            user = self.randomUser()
            post = self.randomPost()
            voted = Vote.objects.all().filter(post=post, author=user).count()
            if (post.author != user and voted == 0):
                rec = Vote()
                rec.author = user
                rec.post = post
                rec.created_date = self.randomDate(post.created_date,
                                                   timezone.now())
                rec.save()
                num_votes = Vote.objects.all().count()
                self.stdout.write(
                    str(num_votes) + ": " + user.username + " voted for [" +
                    post.title + "]")

        self.stdout.write("Commenting...")
        while (num_comments < avg_comments_per_post * num_posts):
            user = self.randomUser()
            post = self.randomPost()
            rec = Comment()
            rec.author = user
            rec.post = post
            rec.contents = faker.text()
            rec.created_date = self.randomDate(post.created_date,
                                               timezone.now())
            rec.save()
            num_comments = Comment.objects.all().count()
            self.stdout.write(
                str(num_comments) + ": " + user.username + " commented on [" +
                post.title + "]")
コード例 #28
0
 def save(self):
     request = self.request
     record = Post(title=request.POST.get('title'), content=request.POST.get('content'), photo=request.FILES['photo'].name)
     self.handle_uploaded_file(request.FILES['photo'])
     record.save()