def view(): from models import User, Post if request.method == 'POST': form = AddPostForm(request.form) if form.validate(): post = Post(title=form.data['title'], content=form.data['content'], user=current_user) post.is_visible = True print("{} is creating a new {}'th post!".format( post.user.username, len(post.user.posts.all()) + 1)) print post.id db.session.add(post) db.session.commit() flash('Post created!') else: flash('Form is not valid! Post was not created.') else: form = AddPostForm() posts = Post.query.filter_by(is_visible=True).all() return render_template('home.html', form=form, posts=posts)
def publish(user_id): form = PublishBlogForm() posts = Post() if form.validate_on_submit(): blog_body = request.form.get("body") if not len(strip(blog_body)): flash("The content is necessray!") return redirect(url_for("publish", user_id=user_id)) posts.body = blog_body posts.timestamp = datetime.datetime.now() posts.user_id = user_id try: db.session.add(posts) db.session.commit() except: flash("Database error!") return redirect(url_for("publish", user_id=user_id)) flash("Publish Successful!", "success") return redirect(url_for("publish", user_id=user_id)) return render_template( "publish.html", form=form)
def feed_update(id=None): # Manual update of one or all feeds now if request.json['action'] == 'refresh': # Call refresh routine # TODO: RSS worker functions in separate package # TODO: Need to capture return status if id is None: rss_spawn() # Update all feeds else: try: feed = Feed.get(Feed.id == id) except Feed.DoesNotExist: return jsonify(**FEED_NOT_FOUND) rss_worker(feed) # Update single feed # return JSON status OK return jsonify(**STATUS_OK) # Mark one or all feeds read elif request.json['action'] == 'markread': if id is None: # Mark all posts read query = Post.update(is_read=True) else: # Mark posts in current feed read query = Post.update(is_read=True).where(Feed.id == id) query.execute() # return JSON status OK return jsonify(**STATUS_OK)
def delete(user, id): post = Post.find_by_id(id) if post: Post.delete(user,id) return redirect('/home') else: abort(404)
def profile(): form = CreatePostForm() # session gets the encrypted ID and hashes it to get the value i.e. the username user = User.query.filter_by(username = session['username']).first() if user is None: return redirect(url_for('signin')) else: if request.method == 'POST': if form.validate() == False: return render_template('profile.html', form=form,communityform=CreateCommunityForm()) else: newpost = Post(form.text.data, session['userID'], form.categoryID) db.session.add(newpost) file = request.files[form.image.name] if file: filename = secure_filename(file.filename) # flush to ge the postID to be used as filename db.session.flush() filename = str(newpost.postID) + os.path.splitext(filename)[1] newpost.imageURI = filename file.save(os.path.join(APP_UPLOADS, filename)) flash(filename+" uploaded!") db.session.commit() flash("posted!") return redirect(url_for('profile')) elif request.method == 'GET': # posts = Post.query.filter_by(username = session['username']).first() return render_template('profile.html', form=form, communityform=CreateCommunityForm())
def show_page(num): p = Page(num, per_page, Post.find().count()) p.urlfunc = lambda num: url_for("blog.show_page", num=num) if not p.exists: abort(404) posts = Post.find({"is_published": True}).order_by("-timestamp")[p.slice()] return render_template("blog/index.html", posts=posts, page=p)
def edit_or_create_post(request): try: user = TestProfile.objects.get(email=request.user.email) post = Post.objects.get(user=user) provided, type = json.loads(post.provided), json.loads(post.house_type) except Post.DoesNotExist: post = None type = None provided = None except TestProfile.DoesNotExist: user = None if request.POST.get('add'): if user is not None and post is None: user.num_posts += 1 post = Post(user=user, region=user.region, sub_region='Berkeley', distance='', title=request.POST.get('title'), house_type=json.dumps(request.POST.getlist('housing_type[]')), provided=json.dumps(request.POST.getlist('provided[]')), proximity='10 minute walk', num_people=1, notes=request.POST.get('notes')) post.save() provided, type = json.loads(post.provided), json.loads(post.house_type) print(provided) elif request.POST.get('delete'): if user.num_posts > 0: user.num_posts -= 1 if post is not None: post.delete() user.save() context = {'user': user, 'post': post, 'type': type, 'provided': provided} return render(request, 'temporary_housing/edit_or_create_post.html', context)
def get_context_data(self, *args, **kwargs): ctx = super(PostList, self).get_context_data(*args, **kwargs) page = self.request.GET.get('p', 1) if self.request.user.is_authenticated(): objects = Post.all().order("-post_date") else: objects = Post.published().order("-post_date") pager = Paginator(objects, PAGE_SIZE) try: page_obj = pager.page(page) except InvalidPageException: raise Http404 ctx.update({ 'paginator': pager, 'page_obj': page_obj, }) return ctx
def fetch(request): if request.method != 'GET': raise Http404 params = {} for k in ('since_id', 'until_id', 'count'): if k in request.GET: params[k] = request.GET[k] since_post = None until_post = None if 'since_id' in params: since_post = Post.get_by_id(int(params['since_id'])) elif 'until_id' in params: until_post = Post.get_by_id(int(params['until_id'])) count = 8 if 'count' in params and re.match('\d+', params['count']): count = int(params['count']) if not (count >= 1 and count <= 8): count = 8 posts = Post.fetch(**{ 'since_post' : since_post, 'until_post' : until_post, 'count' : count }) return util.respond(True, [post.to_dict() for post in posts])
def publications(request): if request.method == 'POST': # save new post title = request.POST['title'] authors = request.POST['authors'] publisher = request.POST['publisher'] papertype = request.POST['papertype'] page_num = request.POST['page_num'] additional_info = request.POST['additional_info'] # selectedpublication = request.POST['selectedpublication'] str_date_published = request.POST['date_published'] post = Post(title=title) # post.date_published = datetime.datetime.now() post.date_published = datetime.fromtimestamp(mktime(time.strptime(str_date_published, "%b %d %Y"))) post.authors = authors post.papertype = papertype post.page_num = page_num post.additional_info = additional_info post.publisher = publisher if request.POST.get('selectedpublication', True): post.selectedpublication = True; post.save() # Get all posts from DB posts = Post.objects return render_to_response('admin/publications.html', {'Posts': posts}, context_instance=RequestContext(request))
def test_comment_approved(self): post = Post(author=self.me, title="Hi", created_date=timezone.now()) post.save() comment = Comment(author=self.me.username, post=post) comment.approve() comment.save() assert comment in post.approved_comments()
def test_left_join(self): User.create(name='jack', email='*****@*****.**') User.create(name='amy', email='*****@*****.**') Post.create(name='Hello world', user_id=1) query = User.left_join(Post).select(User.name) result = query.execute() assert result.count == 2
def sign(request): form = PostForm(request.POST) if form.is_valid(): post = Post(author=form.cleaned_data["author"], message=form.cleaned_data["message"]) post.put() return HttpResponseRedirect("/")
def new_thread(request, directory_id): form = NewThreadForm(request.POST) if request.method == 'POST': if form.is_valid(): title = form.cleaned_data['title'] body = form.cleaned_data['body'] directory = Directory.objects.get(pk=directory_id) new_thread = Thread(name=title, creator=request.user, directory=directory) new_thread.save() new_post = Post(body=body, creator=request.user, index=1, thread=new_thread) #new_thread.latest_post_ref = new_post new_post.save() new_thread.directory = directory new_thread.latest_post = new_post new_thread.post_count = 1 new_thread.save() return HttpResponseRedirect(reverse('main:view_thread', args=[new_thread.pk])) return render(request, 'main/new_thread.html', {'form': form, 'directory_id': directory_id})
def save(self): topic_post = False if not self.topic: topic_type = self.cleaned_data['topic_type'] if topic_type: topic_type = TopicType.objects.get(id=topic_type) else: topic_type = None self.qvod_address = self.cleaned_data['qvod_address'] topic = Topic(forum=self.forum, posted_by=self.user, subject=self.cleaned_data['subject'], need_replay=self.cleaned_data['need_replay'], need_reply_attachments=self.cleaned_data['need_reply_attachments'], topic_type=topic_type, qvod_address=self.qvod_address, has_qvod = has_qvod ) topic_post = True topic.save() else: topic = self.topic post = Post(topic=topic, posted_by=self.user, poster_ip=self.ip, message=self.cleaned_data['message'], topic_post=topic_post) post.save() if topic_post: topic.post = post topic.save() attachments = self.cleaned_data['attachments'] post.update_attachments(attachments) return post
def new_thread(request): """ create a new thead """ if request.method == 'POST': thread = Thread( creator = request.user, site = Site.objects.get_current(), ) post = Post( thread = thread, creator = request.user, posted_from = get_client_ip(request) ) thread_form = forms.ThreadForm(request.POST, instance = thread) post_form = forms.PostForm(request.POST, instance = post) if thread_form.is_valid() and post_form.is_valid(): thread = thread_form.save() post.thread = thread post_form = forms.PostForm(request.POST, instance = post) post_form.save() request.posting_users.add_to_set(request.user.id) return HttpResponseRedirect(reverse('list-threads')) else: thread_form = forms.ThreadForm() post_form = forms.PostForm() return render_to_response("board/new_thread.html",{ 'thread_form' : thread_form, 'post_form' : post_form, }, context_instance = RequestContext(request))
def add_post(request): if request.method == "POST": post_form = PostForm(request.POST, request.FILES) if post_form.is_valid(): title = post_form.cleaned_data['title'] keywords = post_form.cleaned_data['keywords'] description = post_form.cleaned_data['description'] image = post_form.cleaned_data['image'] text = post_form.cleaned_data['text'] slug = title new_post = Post(title=title, userid=request.user, slug=slug, keywords=keywords, image=image, text=text, description=description, date=datetime.now()) new_post.save() post_form = PostForm() return render(request, 'blog/add_post.html', {'post_form': post_form}) else: post_form = PostForm() ctx = {'post_form': post_form} return render(request, 'blog/add_post.html', ctx, )
def index(): from models import User, Post post_form_class = model_form(Post, base_class=Form, db_session=db.session) if request.method == 'POST': form = post_form_class(request.form) if form.validate(): post = Post(**form.data) post.is_visible = True print("{} is creating a new {}'th post!".format( post.user.username, len(post.user.posts.all()) + 1)) db.session.add(post) db.session.commit() flash('Post created!') else: flash('Form is not valid! Post was not created.') else: form = post_form_class() posts = Post.query.filter_by(is_visible=True).all() return render_template('home.html', form=form, posts=posts)
def test_parse_post(self): response = '''{"comments": {"can_post": 0, "count": 4}, "date": 1298365200, "from_id": 55555, "geo": {"coordinates": "55.6745689498 37.8724562529", "place": {"city": "Moskovskaya oblast", "country": "Russian Federation", "title": "Shosseynaya ulitsa, Moskovskaya oblast"}, "type": "point"}, "id": 465, "likes": {"can_like": 1, "can_publish": 1, "count": 10, "user_likes": 0}, "online": 1, "post_source": {"type": "api"}, "reply_count": 0, "reposts": {"count": 3, "user_reposted": 0}, "text": "qwerty", "to_id": 201164356} ''' instance = Post() owner = UserFactory(remote_id=201164356) # Travis Djangov author = UserFactory(remote_id=55555) instance.parse(json.loads(response)) instance.save() self.assertTrue(instance.remote_id.startswith('201164356_')) self.assertEqual(instance.wall_owner, owner) self.assertEqual(instance.author, author) self.assertEqual(instance.reply_count, 0) self.assertEqual(instance.likes, 10) self.assertEqual(instance.reposts, 3) self.assertEqual(instance.comments, 4) self.assertEqual(instance.text, 'qwerty') self.assertTrue(isinstance(instance.date, datetime))
def get(self, user): page = helper.sanitizeHtml(self.request.get('pagina')) target_user_str= helper.sanitizeHtml(helper.parse_post_id(user)) perPage = 20 page = int(page) if page else 1 realPage = page - 1 if realPage > 0: prevPage = realPage session = get_current_session() if session.has_key('user'): user = session['user'] target_user = User.all().filter('lowercase_nickname =', target_user_str).fetch(1) if len(target_user) > 0: posts = Post.all().filter('user ='******'-created').fetch(perPage,perPage * realPage) if (page * perPage) < Post.all().filter('user ='******'-created').count(): nextPage = page + 1 prefetch.prefetch_posts_list(posts) i = perPage * realPage + 1 for post in posts: post.number = i i = i + 1 if helper.is_json(self.request.url): posts_json = [p.to_json() for p in posts] if(self.request.get('callback')): self.response.headers['Content-Type'] = "application/javascript" self.response.out.write(self.request.get('callback')+'('+simplejson.dumps({'posts':posts_json})+');') else: self.response.headers['Content-Type'] = "application/json" self.response.out.write(simplejson.dumps({'posts':posts_json})) else: self.response.out.write(template.render('templates/main.html', locals())) else: self.redirect('/')
def test_get_nozomi_dialgs(self): d = feedparser.parse('tests/data/feed.xml') entry_elem = d.entries[0] post = Post(entry_elem) self.assertMultiLineEqual(post.get_nozomi_dialogs()[0], u'「原種・亜種と同じく飛び回ったり走り回ったりして追うのが大変なのに、希少種ときたら頭も硬いのが厄介ですよね」')
def save(self): topic_post = False if not self.topic: topic_type = self.cleaned_data["topic_type"] if topic_type: topic_type = TopicType.objects.get(id=topic_type) else: topic_type = None topic = Topic( forum=self.forum, posted_by=self.user, subject=self.cleaned_data["subject"], need_replay=self.cleaned_data["need_replay"], need_reply_attachments=self.cleaned_data["need_reply_attachments"], topic_type=topic_type, ) topic_post = True topic.save() else: topic = self.topic post = Post( topic=topic, posted_by=self.user, poster_ip=self.ip, message=self.cleaned_data["message"], topic_post=topic_post, ) post.save() if topic_post: topic.post = post topic.save() attachments = self.cleaned_data["attachments"] post.update_attachments(attachments) return post
def post(title=None, category=None): if title: post = Post.query(Post.title==title).get() else: post = Post.get_1lastest(category=category) if not post: return redirect(url_for("notfound", title=title)) pre_post = post.get_pre(category=category) next_post = post.get_next(category=category) content, toc = md2html(post.content) last_posts = Post.get_lastest() txt = noTag(noTag(toc, 'div'), 'ul') toc = toc if txt.strip() else '' return render_template('post.html', post=post, last_posts=last_posts, category=category, pre_post=pre_post, next_post=next_post, toc=toc, content=content)
def sub_post(request, id_num): #for nested posts pform = PostForm(request.POST or None) parent = get_object_or_404(Post, pk=id_num) if (request.method == 'POST' and request.user.is_authenticated()): if pform.is_valid(): title = pform.cleaned_data["title"] check = Post.objects.filter(title=title).order_by("-identifier") check_int = 0 if len(check) > 0: check_int = check[0].identifier + 1 post = Post(title=title, body=pform.cleaned_data["body"], parent=parent, user=request.user, identifier=check_int) post.save() messages.success(request, "Post submitted correctly") else: ### meaningful errors here would be helpful ### messages.error(request, pform.errors) return render_to_response("post_form.html", {'pform' : pform, 'post':parent}, RequestContext(request)) return HttpResponseRedirect("/posts/"+id_num)
def create(request): title = request.GET.get('title') content = request.GET.get('content') if title: post = Post(title=title.strip(), content=content, author=request.user) post.save() return HttpResponse(serializers.serialize("json", Post.objects.filter(title=post.title, content=post.content, author=request.user, create_time=post.create_time)), mimetype="application/json")
def show_all_posts(): """the homepage of the site where all the posts will be shown in a table""" show_followed = False # get the variable "show-all" from the template to determine whether to show all posts or followed ones show_what = request.args.get('show-all') page = request.args.get('page', 1, type=int) print show_what, "this is show_what" if show_what == "false": show_followed = True if show_followed: viewer_id = session.get('loggedin', None) viewer = User.get_user_by_id(viewer_id) posts_all = viewer.followed_posts() pagination = viewer.followed_posts_pagination(page) else: posts_all = Post.get_all_posts() pagination = Post.get_all_posts_pagination(page) if posts_all: session["post_ids"] = [post.post_id for post in posts_all] tags = Tag.sort_all_tags_by_popularity() posts = pagination.items # the records in the current page return render_template('post_list.html', posts=posts, tags=tags, pagination=pagination)
def get(self): page = helper.sanitizeHtml(self.request.get('pagina')) perPage = 20 page = int(page) if page else 1 realPage = page - 1 if realPage > 0: prevPage = realPage if (page * perPage) < Post.get_cached_count(): nextPage = page + 1 session = get_current_session() if session.has_key('user'): user = session['user'] posts = Post.all().order('-created').fetch(perPage,perPage * realPage) prefetch.prefetch_posts_list(posts) i = perPage * realPage + 1 for post in posts: post.number = i i = i + 1 if helper.is_json(self.request.url): posts_json = [p.to_json() for p in posts] if(self.request.get('callback')): self.response.headers['Content-Type'] = "application/javascript" self.response.out.write(self.request.get('callback')+'('+simplejson.dumps({'posts':posts_json})+');') else: self.response.headers['Content-Type'] = "application/json" self.response.out.write(simplejson.dumps({'posts':posts_json})) else: self.response.out.write(template.render('templates/main.html', locals()))
def post_edit(post_id): if request.method == 'GET': try: post = Post.get(Post.post_id == post_id) # todo: get not deleted except Post.DoesNotExist: abort(404) all_categories = Category.select() template = env.get_template('post/edit.html') return template.render(item=post, categories=all_categories, submit_button=u'Оновити') elif request.method == 'POST': post = Post.get(Post.post_id == post_id) post.category = post_get('category_id') post.post_text = post_get('text') post.title = post_get('title') post.draft = bool(int(post_get('draft'))) # zero int is False post.language = post_get('language') new_tags = post_get('tags') old_tags = Tag.select().join(Tag_to_Post)\ .where(Tag_to_Post.post_id == post_id) remove_tags(old_tags, new_tags, post_id) add_new_tags(new_tags, post_id) post.save() app.flash(u'Статтю успішно оновлено') redirect('/post/' + str(post_id))
def single_post(post_id): """Returns everything in a post as json""" post_d = mongo.db.posts.find_one(post_id) if post_d is None: abort(404) post = Post(bson=post_d) return jsonify(**post.to_dict())
def post(self, request): """ Crea un post a partir de la información POST """ success_message = '' post_with_owner = Post() post_with_owner.owner = request.user # aquí asignamos al usuario como propietario del post form = PostForm(request.POST, instance=post_with_owner) if form.is_valid(): new_post = form.save() form = PostForm() # reiniciamos el form success_message = 'Post almacenado con éxito! ' success_message += '<a href="{0}">'.format( reverse('post_detail', args=[request.user.username, new_post.pk]) ) success_message += 'Ver post' success_message += '</a>' context = { 'form': form, 'success_message': success_message } return render(request, 'blogs/new_post.html', context)
user_admin = User(user='******', password=sha256.hash('123456')) tag_adipiscing = Tag(name='Adipiscing') tag_gravida = Tag(name='Gravida') tag_autor = Tag(name='Auctor') tag_pharetra = Tag(name='Pharetra') tag_lorem = Tag(name='Lorem') comment_rhino = Comment( text= 'Rhinoceros, often abbreviated as rhino, is a group of five extant species of odd-toed ungulates in the family Rhinocerotidae.' ) post_lorem = Post( text= 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris quis elit dui. Praesent ultricies hendrerit nulla, ut iaculis nibh efficitur ac. Phasellus facilisis pulvinar enim, ac venenatis nisi tincidunt imperdiet. Maecenas accumsan semper nulla eu tincidunt. Etiam sodales lectus enim, ac faucibus ex porttitor in. Nam euismod tempor eros sed eleifend. Ut sed molestie nibh, ac venenatis mauris. Etiam massa neque, posuere non justo et, dapibus consequat magna. Vivamus condimentum lectus in hendrerit porttitor. Vivamus a nibh arcu. In in elementum enim, eget condimentum arcu.', tags=[tag_pharetra, tag_gravida, tag_lorem], created_at=(datetime.utcnow() - timedelta(days=1))) post_tempus = Post( text= 'Proin tempus, nisi at interdum sollicitudin, risus orci gravida metus, ut sagittis nisi sem vel felis. Nulla euismod ligula at tempus mollis. Phasellus vel luctus eros, a volutpat elit. Maecenas ut orci ipsum. Nullam et iaculis est. Cras rhoncus at dolor id ultricies. Donec a pretium ex. Sed id lacus egestas, blandit ipsum eget, ultricies nunc.', tags=[tag_autor, tag_adipiscing]) post_proin = Post( text= 'Proin ex sem, mattis et varius in, auctor id lacus. Curabitur id est ultrices, aliquam nisl at, pellentesque eros. Etiam sed mollis dui, vitae lobortis ipsum. Nam in fermentum erat, vel accumsan mi. Suspendisse interdum dui sit amet orci molestie, at sollicitudin ex finibus. Mauris orci ligula, malesuada id ullamcorper id, gravida lacinia felis. Maecenas pulvinar, purus in laoreet luctus, velit felis gravida purus, dignissim hendrerit libero ipsum at augue. Morbi iaculis, tellus nec tincidunt maximus, ligula magna pretium risus, vitae tincidunt metus quam eu nisl.', tags=[tag_pharetra]) post_etiam = Post( text= 'Etiam tempus libero semper, tincidunt sem id, aliquet massa. Ut a ipsum ipsum. Donec rhoncus vestibulum blandit. Nunc nec maximus nibh. Quisque eu semper quam. In auctor lorem ut diam commodo ullamcorper. Duis nec porttitor augue. Etiam est nisl, facilisis eget congue vitae, consectetur id nibh. Fusce enim ligula, ultrices non pulvinar elementum, maximus vel dui. Pellentesque congue, nunc lobortis efficitur euismod, nisl sapien convallis mauris, vel lobortis libero felis nec odio. Nullam viverra ultricies magna, vel sollicitudin mauris aliquet ac. Nam mollis magna sit amet varius finibus.', tags=[tag_adipiscing], comments=[comment_rhino])
from models import User, Post, db, connect_db from app import app connect_db(app) db.drop_all() db.create_all() Posts.query.delete() whiskey = Post(title='Whiskey', content='Lane', user_id=9) db.session.add(whiskey) db.session.commit()
def new(bot, update): post = Post(Post.author.telegram_id == update.message.from_chat.id) post.author.state = 'conf' post.save() fill(bot, update)
def miss(bot, update): post = Post.get(Post.author.telegram_id == update.message.from_chat.id) now_ind = order.index(post.author.state[len('conf'):]) if getattr(Post, order[now_ind]).null: post = ask_next(update, now_ind, post) post.save()
def get_posts(self, limit, offset): """ Get all posts ordered by creation date (descending) """ query = Post.all().order( '-created') #App engine query style allows more detailed filtering return query.fetch(limit=limit, offset=offset)
def get(self): posts = Post.find_by_user(self.get_user_id()) self.render('my_posts.html',posts=posts,logged_in=True)
def admin(): posts = map(lambda d: Post(bson=d), mongo.db.posts.find()) return render_template('admin/index.html', posts=posts, user=current_user)
def home(): """A simple view of all the content""" posts = [Post(bson=d) for d in mongo.db.posts.find()] return render_template('home.html', posts=posts)
def show_editor(post_id): d = mongo.db.posts.find_one(post_id) post = Post(bson=d) form = PostEditForm() return render_template('editor.html', post=post, form=form)
def all_posts(page=1, page_size=10): query = Post.all() query.filter("posted_on !=", "") query.order("-posted_on") return query.run()
from models import Model, Tag, Post, User from populate_db import create_tag_or_user, fake, session user = create_tag_or_user(1, User, fake.name)[0] tags = [create_tag_or_user(1, Tag, fake.word)[0] for _ in range(2)] post = Post(user=user, title=fake.sentence(), body=fake.text()) post.tags.extend(tags) session.add(user) session.add(tags[0]) session.add(tags[1]) session.add(post) session.commit() posts = session.query(Post).join(User).filter(User.name == user.name).filter( Post.tags.any(Tag.id.in_([tag.id for tag in tags]))).all() print(posts)
def answer(request): """Adds an answer from a user to a topic.""" try: topic_pk = request.GET["sujet"] except: # problem in variable format raise Http404 # Retrieve current topic. g_topic = get_object_or_404(Topic, pk=topic_pk) if not g_topic.forum.can_read(request.user): raise PermissionDenied # Making sure posting is allowed if g_topic.is_locked: raise PermissionDenied # Check that the user isn't spamming if g_topic.antispam(request.user): raise PermissionDenied last_post_pk = g_topic.last_message.pk # Retrieve 10 last posts of the current topic. posts = \ Post.objects.filter(topic=g_topic) \ .prefetch_related() \ .order_by("-pubdate" )[:10] # User would like preview his post or post a new post on the topic. if request.method == "POST": data = request.POST newpost = last_post_pk != int(data["last_post"]) # Using the « preview button », the « more » button or new post if "preview" in data or newpost: form = PostForm(g_topic, request.user, initial={"text": data["text" ]}) form.helper.form_action = reverse("zds.forum.views.answer") \ + "?sujet=" + str(g_topic.pk) return render_template("forum/post/new.html", { "text": data["text"], "topic": g_topic, "posts": posts, "last_post_pk": last_post_pk, "newpost": newpost, "form": form, }) else: # Saving the message form = PostForm(g_topic, request.user, request.POST) if form.is_valid(): data = form.data post = Post() post.topic = g_topic post.author = request.user post.text = data["text"] post.text_html = emarkdown(data["text"]) post.pubdate = datetime.now() post.position = g_topic.get_post_count() + 1 post.ip_address = get_client_ip(request) post.save() g_topic.last_message = post g_topic.save() #Send mail subject = "ZDS - Notification : " + g_topic.title from_email = "Zeste de Savoir <{0}>".format(settings.MAIL_NOREPLY) followers = g_topic.get_followers_by_email() for follower in followers: receiver = follower.user if receiver == request.user: continue pos = post.position - 1 last_read = TopicRead.objects.filter( topic=g_topic, post__position=pos, user=receiver).count() if last_read > 0: message_html = get_template('email/notification/new.html') \ .render( Context({ 'username': receiver.username, 'title':g_topic.title, 'url': settings.SITE_URL + post.get_absolute_url(), 'author': request.user.username }) ) message_txt = get_template('email/notification/new.txt').render( Context({ 'username': receiver.username, 'title':g_topic.title, 'url': settings.SITE_URL + post.get_absolute_url(), 'author': request.user.username }) ) msg = EmailMultiAlternatives( subject, message_txt, from_email, [ receiver.email]) msg.attach_alternative(message_html, "text/html") msg.send() # Follow topic on answering if not g_topic.is_followed(user=request.user): follow(g_topic) return redirect(post.get_absolute_url()) else: return render_template("forum/post/new.html", { "text": data["text"], "topic": g_topic, "posts": posts, "last_post_pk": last_post_pk, "newpost": newpost, "form": form, }) else: # Actions from the editor render to new.html. text = "" # Using the quote button if "cite" in request.GET: post_cite_pk = request.GET["cite"] post_cite = Post.objects.get(pk=post_cite_pk) if not post_cite.is_visible: raise PermissionDenied for line in post_cite.text.splitlines(): text = text + "> " + line + "\n" text = u"{0}Source:[{1}]({2}{3})".format( text, post_cite.author.username, settings.SITE_URL, post_cite.get_absolute_url()) form = PostForm(g_topic, request.user, initial={"text": text}) form.helper.form_action = reverse("zds.forum.views.answer") \ + "?sujet=" + str(g_topic.pk) return render_template("forum/post/new.html", { "topic": g_topic, "posts": posts, "last_post_pk": last_post_pk, "form": form, })
def post(): if request.method == 'POST': book_name = request.form['bookName'] price = request.form['price'] new = request.form['new'] description = request.form['description'] isbn = request.form['ISBN'] token = request.form['token'] logger.info("post_isbn: {}".format(isbn)) user_found = User.get_by_token(token) book_found = Book.get_by_isbn(isbn) if not book_found: return jsonify({'errMsg': 'Invalid isbn'}), 404 else: now = int(time.time()) today = int(now / (24 * 3600)) # noinspection PyBroadException try: conn_book.zincrby('daily_' + str(today), 2, book_name) # 计入当日上传 conn_book.zincrby('rank_' + str(today), 2, book_name) # 计入当日推荐 current_count = conn_book.zscore('rank_' + str(today), book_name) sub_count = conn_book.zscore('daily_' + str(today - 7), book_name) # 7天前的即将淘汰 if sub_count: conn_book.zadd('rank_' + str(today + 1), {book_name: current_count - sub_count }) # 当前榜减去即将淘汰日写入明日榜 else: conn_book.zadd('rank_' + str(today + 1), {book_name: current_count}) # 当前榜直接写入明日榜 post_ = Post(bookname=book_name, price=price, new=new, description=description, isbn=isbn, openid=user_found.openid) db.session.add(post_) db.session.commit() key = post_.image_name up_token = q.upload_token(bucket_name, key, 3600) return jsonify({'upToken': up_token, 'key': key}), 201 except Exception: abort(500) elif request.method == 'GET': book_name = request.args.get('bookName', '') posts = Post.search_by_name(book_name) # logger.info(posts) search_list = list() if posts: now = int(time.time()) today = int(now / (24 * 3600)) search_names = set() for item in posts: if item.is_valid: search_names.add(item.book_name) # 搜索得到的卖单书名,同名不重复计入 # logger.info(item.book_name) search_item = dict( postId=item.id, bookName=item.book_name, imageName=item.image_name, postTime=item.post_time.strftime("%Y-%m-%d %H:%M:%S"), sale=item.sale_price, new=item.new, addr=item.seller.address, author=item.book.author, publisher=item.book.publisher, pubdate=item.book.pubdate, originalPrice=item.book.original_price) search_list.append(search_item) for name in search_names: # noinspection PyBroadException try: conn_book.zincrby('daily_' + str(today), 1, name) # 计入当日搜索 conn_book.zincrby('rank_' + str(today), 1, name) # 计入当日推荐 current_count = conn_book.zscore('rank_' + str(today), name) sub_count = conn_book.zscore('daily_' + str(today - 7), name) # 7天前的即将淘汰 if sub_count: conn_book.zadd('rank_' + str(today + 1), {name: current_count - sub_count }) # 当前榜减去即将淘汰日写入明日榜 else: conn_book.zadd('rank_' + str(today + 1), {name: current_count}) # 当前榜直接写入明日榜 except Exception: pass return jsonify({'msg': 'Request: ok', 'searchRes': search_list}) else: abort(204) return 'else'
headers=headers) result = r.json() if result.get("appmsgstat"): post['read_num'] = result.get("appmsgstat").get("read_num") post['like_num'] = result.get("appmsgstat").get("like_num") post['reward_num'] = result.get("reward_total_count") post['u_date'] = datetime.now() logger.info("「%s」read_num: %s like_num: %s reward_num: %s" % (post.title, post['read_num'], post['like_num'], post['reward_num'])) post.save() else: logger.warning(u"没有获取的真实数据,请检查请求参数是否正确,返回的数据为:data=%s" % r.text) exit() if __name__ == '__main__': # 直接运行这份代码很定或报错,或者根本抓不到数据 # 因为header里面的cookie信息已经过去,还有URL中的appmsg_token也已经过期 # 你需要配合Fiddler或者charles通过手机重新加载微信公众号的更多历史消息 # 从中获取最新的headers和appmsg_token替换上面 crawler = WeiXinCrawler() # crawler.crawl() # s = "__biz=MjM5MzgyODQxMQ==&appmsg_type=9&mid=2650367540&sn=ef9c6353a9255dbc00e2beac7f449dad&idx=1&scene=27&title=Python%E5%A5%87%E6%8A%80%E6%B7%AB%E5%B7%A7%EF%BC%8C%E7%9C%8B%E7%9C%8B%E4%BD%A0%E7%9F%A5%E9%81%93%E5%87%A0%E4%B8%AA&ct=1511410410&abtest_cookie=AwABAAoADAANAAcAJIgeAGSIHgD8iB4A7IkeAAaKHgAPih4AU4oeAAAA&devicetype=android-24&version=/mmbizwap/zh_CN/htmledition/js/appmsg/index3a9713.js&f=json&r=0.04959653583814139&is_need_ad=0&comment_id=1411699821&is_need_reward=1&both_ad=0&reward_uin_count=24&msg_daily_idx=1&is_original=0&uin=777&key=777&pass_ticket=zpU4AwNXTGS5LfBXFx4NCyMo5YTpSQo9RarrPG3tjhmMaGfORzykNNviX7IlM4i0&wxtoken=1922467438&devicetype=android-24&clientversion=26051732&appmsg_token=938_0n0in1TAhMHhtZ7zXIOyxTxYXZEFW7ez7tXTmochNzKXa19P3wxK6-C-yM1omM_h7gSMZJmyv7glw98g&x5=1&f=json" # print(utils.str_to_dict(s, "&", "=")) # for post in Post.objects(reward_num=0): crawler.update_post(post) time.sleep(1)
def new(request): """Creates a new topic in a forum.""" try: forum_pk = request.GET["forum"] except: # problem in variable format raise Http404 forum = get_object_or_404(Forum, pk=forum_pk) if not forum.can_read(request.user): raise PermissionDenied if request.method == "POST": # If the client is using the "preview" button if "preview" in request.POST: form = TopicForm(initial={"title": request.POST["title"], "subtitle": request.POST["subtitle"], "text": request.POST["text"]}) return render_template("forum/topic/new.html", {"forum": forum, "form": form, "text": request.POST["text"]}) form = TopicForm(request.POST) data = form.data if form.is_valid(): # Treat title (tags, title) = get_tag_by_title(data["title"]) # Creating the thread n_topic = Topic() n_topic.forum = forum n_topic.title = title n_topic.subtitle = data["subtitle"] n_topic.pubdate = datetime.now() n_topic.author = request.user n_topic.save() # add tags n_topic.add_tags(tags) n_topic.save() # Adding the first message post = Post() post.topic = n_topic post.author = request.user post.text = data["text"] post.text_html = emarkdown(request.POST["text"]) post.pubdate = datetime.now() post.position = 1 post.ip_address = get_client_ip(request) post.save() n_topic.last_message = post n_topic.save() # Follow the topic follow(n_topic) return redirect(n_topic.get_absolute_url()) else: form = TopicForm() return render_template("forum/topic/new.html", {"forum": forum, "form": form})
def add_post(house_name, user_id, content): pigeon_key = ndb.Key(Pigeon, user_id) house_list = House.query(House.name == house_name).fetch() house_key = house_list[0].key post_list = Post.query(Post.pigeon_key == pigeon_key, Post.house_key == house_key).fetch() if post_list: length = len(post_list) post = Post(pigeon_key=pigeon_key, house_key=house_key, content=content, number=length + 1, date_str='') post.put() date2str = str(post.date) str_list = date2str.split('.') post.date_str = str_list[0] post.put() return else: post = Post(pigeon_key=pigeon_key, house_key=house_key, content=content, number=1, date_str='') post.put() date2str = str(post.date) str_list = date2str.split('.') post.date_str = str_list[0] post.put() return
def get_posts(self, limit, offset): """ Get all posts ordered by creation date (descending) """ query = Post.all().order('-created') return query.fetch(limit=limit, offset=offset)
def show_user_details(user_id): """ Shows user details """ posts = Post.get_all_user_posts(user_id) user = User.query.get(user_id) return render_template('details.html', user=user, posts=posts)
def pages(): posts = [p.get_json() for p in Post.query().order(-Post.date)] # return jsonify(posts) return Response(json.dumps(posts), mimetype='application/json')
from models import User, Post, Tag, PostTag, db from app import app db.drop_all() db.create_all() u1 = User(first_name='Van', last_name='Helsing', image_url='https://pngimg.com/uploads/cat/cat_PNG50505.png') u2 = User(first_name='Andy', last_name='Nielsen', image_url='https://www.pinclipart.com/picdir/big/173-1733627_clipart-ear-micky-mouse-mickey-mouse-face-transparent.png') u3 = User(first_name='Pauline', last_name='Quinn') p1 = Post(title='Garlic bread', content='Pls need a recipe, asking for a friend', user_id='1') p2 = Post(title='Read me !', content='Starting a vacation blog soon, stay tuned for the first post about Greece', user_id='2') p3 = Post(title='Toothpaste explosion', content='Hi all, giving tips for the elephant toothpaste explosion on this channel', user_id='3') t1 = Tag(name='fun') t2 = Tag(name='weird') t3 = Tag(name='smart') db.session.add_all([u1, u2, u3]) db.session.commit() db.session.add_all([p1, p2, p3]) db.session.commit()
def admin(): last_posts = Post.get_lastest() return render_template('admin.html',last_posts=last_posts)
def notfound(title=None): last_posts = Post.get_lastest() return render_template('notfound.html', suggest=title, last_posts=last_posts)
def hisotry(): posts = Post.query().order(-Post.date) last_posts = Post.get_lastest() return render_template('archives-history.html', last_posts=last_posts, posts=posts)
def about(): last_posts = Post.get_lastest() return render_template('about.html',last_posts=last_posts)
def index(): posts = Post.get_all() return render_template("index.html", posts=posts)
def archives(): entities = Entity.query().order(Entity.name) last_posts = Post.get_lastest() return render_template('archives.html', last_posts=last_posts, entities=entities)
def show_post(slug): post = Post.get_by_slug(slug) if post is None: abort(404) return render_template("post_view.html", post=post)
def setUp(self): """Add sample user/post/fav""" User.query.delete() Post.query.delete() Favorite.query.delete() # create test user u1 = User.signup(display_name='test1', username='******', password="******", caption="i am test user 1") u2 = User.signup(display_name='test2', username='******', password="******", caption="test2") u3 = User.signup(display_name='test3', username='******', password="******", caption="im tester 3") db.session.add(u1) db.session.add(u2) db.session.add(u3) db.session.commit() self.u1_id = u1.id self.u1_username = u1.username self.u2_id = u2.id self.u3_id = u3.id # create test post for test user p1 = Post( title="test title", image= "https://images.unsplash.com/photo-1509840841025-9088ba78a826?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80", description="This is a test1", lat=38.9196, lng=-2.0507, created_dt="2021-03-16 10:45:53.875247", place_name="Testopia", user_id=self.u1_id) p2 = Post( title="test title2", image= "https://images.unsplash.com/photo-1509840841025-9088ba78a826", description="This is a test2", lat=38.9196, lng=-2.0507, created_dt="2021-03-15 10:45:53.875247", place_name="Testopia", user_id=self.u2_id) p3 = Post( title="test title3", image= "https://images.unsplash.com/photo-1509840841025-9088ba78a826", description="This is a test3", lat=38.9196, lng=-2.0507, created_dt="2021-03-16 10:45:53.875247", place_name="Testopia", user_id=self.u1_id) p4 = Post( title="test title4", image= "https://images.unsplash.com/photo-1509840841025-9088ba78a826", description="This is a test4", lat=38.9196, lng=-2.0507, created_dt="2008-03-16 10:45:53.875247", place_name="Testopia", user_id=self.u2_id) p5 = Post( title="test title5", image= "https://images.unsplash.com/photo-1509840841025-9088ba78a826", description="This is a test5", lat=38.9196, lng=-2.0507, created_dt="2020-03-16 10:45:53.875247", place_name="Testopia", user_id=self.u3_id) db.session.add(p1) db.session.add(p2) db.session.add(p3) db.session.add(p4) db.session.add(p5) db.session.commit() self.p1_id = p1.id self.p2_id = p2.id self.p3_id = p3.id self.p4_id = p4.id self.p5_id = p5.id self.p1_title = p1.title self.p1_user = p1.user_id f1 = Favorite(post_id=self.p1_id, user_id=self.u1_id) f2 = Favorite(post_id=self.p1_id, user_id=self.u2_id) f3 = Favorite(post_id=self.p1_id, user_id=self.u3_id) f4 = Favorite(post_id=self.p2_id, user_id=self.u1_id) f6 = Favorite(post_id=self.p2_id, user_id=self.u3_id) f8 = Favorite(post_id=self.p3_id, user_id=self.u2_id) f9 = Favorite(post_id=self.p3_id, user_id=self.u3_id) db.session.add(f1) db.session.add(f2) db.session.add(f3) db.session.add(f4) db.session.add(f6) db.session.add(f8) db.session.add(f9) db.session.commit() self.client = app.test_client()
def get(self): qry = Post.query().order(-Post.created) post = qry.fetch(10) uid = (self.read_secure_cookie("user_id")) self.render("mainpage.html", posts=post, uid=uid)
def test_string_representation(self): expected = "This is a title" p1 = Post(title=expected) actual = str(p1) self.assertEqual(expected, actual)