def open_post(request, login, name): post = _get_post(login, name) if not post: post = Post() post.login, post.name = login,name return render(request, 'paste.html', dict(post=post))
def load_posts(file): print '\nimporting posts' for e in json.load(file): created = datetime.strptime(e['created'], '%Y-%m-%d %H:%M%S') author = Author.objects.filter(name=e['author_name'], source=e['author_source']).get() try: post = Post.objects.filter(content=e['content'], author=author, created=created).get() except Post.DoesNotExist: post = Post(content=e['content'], latitude=float(e['latitude']), longitude=float(e['longitude']), address=e['address'], created=created, source=e['source'], external_id=e['external_id'], external_data=e['external_data']) post.author = author post.save() print '.', sys.stdout.flush()
def newthread(request, sid): def default_post_page(error=None): return render(request, 'newthread.html', { 'error': error, 'section': Section.objects.get(id=sid) }) current_user = request.user title = request.POST.get('title') content = request.POST.get('content') if content == '' or title == '': return default_post_page('No title or content supplied') if not content or not title: return default_post_page() try: section = Section.objects.get(id=sid) except: # no section return default_post_page() # create a thread if needed thread = Thread(title=title, creator=current_user, section=section) thread.save() post = Post(thread=thread, content=content, author=current_user) post.save() next = request.GET.get('next', reverse('thread', args=[thread.id])) return redirect(next)
def new_post(request: WSGIRequest) -> HttpResponseRedirect: url = HttpRequest.build_absolute_uri(request, reverse("home")) if request.method == "POST": content = bleach.clean(request.POST["content"]) title = request.POST["title"] slug = request.POST["slug"] new_post = Post( content=content, title=title, author=request.user, published_at=datetime.now(), slug=slug ) try: new_post.full_clean() # XXX: we really should just be using a ModelForm except ValidationError as e: # XXX: this way of rendering the error message ends up # looking too JSONy from a user's perspective messages.error(request, str(e)) return redirect(reverse('new_post')) new_post.save() return redirect( reverse( "show_post", args=(new_post.year, new_post.month, new_post.slug) ) ) else: return render(request, "new_post.html", {"url": url})
def save(self, *args, **kwargs): if not self.id: super(Issue, self).save() if not self.author.landlord and self.author.phone: client = TwilioRestClient(settings.TWILLIO_ACCOUNT, settings.TWILLIO_TOKEN) message = client.sms.messages.create( to=self.house.landlord.phone, from_="+441827231000", body="Issue Raised: "+self.title+" on "+self.house.name) post = Post() post.text = "The issue '"+self.title+"' has been raised" post.posted_by = self.author post.save() if self.resolved: super(Issue, self).save() for user in self.house.user_set.all(): if user.phone: client = TwilioRestClient(settings.TWILLIO_ACCOUNT, settings.TWILLIO_TOKEN) message = client.sms.messages.create( to=user.phone, from_="+441827231000", body="The issue '"+self.title+"' has been resolved.") post = Post() post.text = "The issue '"+self.title+" has been resolved" post.posted_by = self.house.landlord post.save() else: super(Issue, self).save()
def post(self, request, topic_id, *args, **kwargs): post = Post( topic_id=topic_id, user=request.user, content=request.POST.get("content") ) post.save() return redirect("topic", topic_id)
def test_order_queryset_by_num_loves_returns_posts_ordered_by_num_loves( self): queryset = Post.get_queryset(self.user_1.id) queryset = Post.order_queryset_by_num_loves(queryset, limit=10) expected = (self.posts_with_2_loves + self.posts_with_1_love + self.posts_with_no_love) for index, post in enumerate(queryset): self.assertEqual(post.id, expected[index].id)
def save_post(self, pid, person, created_time, photo, text, latitude, longitude, network): post = Post(id=pid, author=person, dateOfCreation=created_time, photo=photo, text=text[:120], latitude=latitude, longitude=longitude, network=network) post.save() return post
class PostTestCase(NdbTestCase): def setUp(self): super(PostTestCase, self).setUp() self.post = Post( title = 'Test Post', brief = 'To infinity ... and beyond.', content = 'Vestibulum id ligula porta felis euismod semper.', is_active = True, comments_enabled = False, date_published = datetime.date(2013,07,04), ) self.client = Client() def test_index_page(self): response = self.client.get(reverse('post_index')) self.assertEqual(response.status_code, 200) def test_archive_page(self): response = self.client.get(reverse('archive_index')) self.assertEqual(response.status_code, 200) def test_post_that_does_exist(self): post = self.post.put().get() response = self.client.get(reverse('post_view', args=[ post.date_published.strftime("%Y"), post.date_published.strftime("%m"), post.date_published.strftime("%d"), slugify(post.title)]) ) self.assertEqual(response.status_code, 200) def test_post_that_does_not_exist(self): new_title = 'I don\'t exist' post = self.post.put().get() response = self.client.get(reverse('post_view', args=[ post.date_published.strftime("%Y"), post.date_published.strftime("%m"), post.date_published.strftime("%d"), slugify(new_title)]) ) self.assertEqual(response.status_code, 404) def test_post_is_not_active(self): post = self.post.put().get() post.is_active = False edited_post = post.put().get() response = self.client.get(reverse('post_view', args=[ edited_post.date_published.strftime("%Y"), edited_post.date_published.strftime("%m"), edited_post.date_published.strftime("%d"), slugify(edited_post.title)]) ) self.assertEqual(response.status_code, 404)
def create_fake_posts(number=10): Post.objects.all().delete() for i in range(number): instance = Post(title=fake.sentence(), abstract=fake.text(), body=fake.text(), public=True) instance.save() instance.comments.set(get_random_comments(i)) instance.tags.set(get_random_tags(i)) time.sleep(2) print("post %s added" % i)
def save_post(self, pid, person, created_time, photo, text, latitude, longitude, network): post = Post( id=pid, author=person, dateOfCreation=created_time, photo=photo, text=text[:120], latitude=latitude, longitude=longitude, network=network, ) post.save() return post
def save_status(self, data): """TODO""" status = Status.parse(self.api, json.loads(data)) if not status.geo: # _datafile.write(data+'\n') return if Author.objects.filter(owner__userprofile__twitter_id=status.user.id_str).exists(): # this tweet's author is on stargazer return try: author = Author.objects.filter(source=Author.T_TWITTER, external_id=status.user.id_str).get() except Author.DoesNotExist: author = Author( name=status.user.screen_name, avatar_uri=status.user.profile_image_url, source=Author.T_TWITTER, external_id=status.user.id_str, ) author.save() try: post = Post.objects.filter(source=Post.T_TWITTER, external_id=status.id_str).get() except Post.DoesNotExist: lat = float(status.geo["coordinates"][0]) lng = float(status.geo["coordinates"][1]) try: addr = self._latlng2addr.get(lat, lng) except (LatLng2Addr.ConnectionFailed, LatLng2Addr.GeocodingFailed) as e: addr = "" # twitter api response in UTC created = status.created_at + timedelta(hours=8) post = Post( content=status.text, author=author, latitude=lat, longitude=lng, address=addr, source=Post.T_TWITTER, external_id=status.id_str, external_data=data, created=created, ) post.save() return
def update_post(request, post_id=None, title=None, body=None, published=False, tags=None): """ Add/Edit Blog Post :param: post_id [LONG] id of post to update [optional] :param: title [STR] post title [optional] :param: body [STR] post body [optional] :param: published [BOOL] post published flag [optional] :param: tags [LIST] list of tags[optional] :return: success [BOOL] success or failure """ # Create or retrieve Post if post_id: post = Post.get_by_id(post_id, parent=get_blog_key()) else: post = Post(parent=get_blog_key()) # Update Post if body is not None: post.body = body if title is not None: post.title = title if tags is not None: post.tags = tags post.published = published # Persist try: post.put() success = True except Exception: success = False logging.error("Error saving post", exc_info=True) return HttpResponse(success)
def delete_post(request, post_id): """ Delete Blog Post :param: post_id [LONG] id of post to delete :return: success [BOOL] success or failure """ # Attempt to delete the Post try: Post.get_by_id(post_id, parent=get_blog_key()).key.delete() success = True except Exception: logging.error("Error deleting Post", exc_info=True) success = False return HttpResponse(success)
def get_queryset(self): """Returns queryset in order of date last modified by default However, if the query string says top posts, order posts by number of loves """ search_str = self.request.query_params.get('q', '') limit = self.request.query_params.get('limit', 10) private = self.request.query_params.get('private', False) qs = Post.get_queryset(self.request.user.id) if private: qs = Post.filter_others_post(qs, self.request.user) if search_str.lower() == 'top': qs = Post.order_queryset_by_num_loves(qs, int(limit)) return qs
def save_posts(data_posts, id_users): cleaned_posts = [] id_posts = {} for obj in data_posts: if not id_users[obj["userId"]]: continue obj["user"] = id_users[obj["userId"]] id_posts[obj["id"]] = obj["id"] cleaned_posts.append( Post(title=obj["title"], body=obj["body"], user=obj["user"])) response_posts = Post.objects.bulk_create(cleaned_posts, ignore_conflicts=True) response_posts = remove_unvalid_objects(response_posts) response_posts = Post.objects.order_by('-pk')[:len(response_posts)] response_posts = list(reversed(response_posts)) id_posts = bind_id_with_objects(id_posts, response_posts) return id_posts, response_posts
def admin_edit_post(request, slug, year, month, day): post = Post.query( ndb.AND( Post.slug == slug, Post.date_published == datetime.datetime( int(year), int(month), int(day) ) ) ).get() form = PostForm(initial = post.to_dict()) if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post.title = form.cleaned_data['title'] post.brief = form.cleaned_data['brief'] post.content = form.cleaned_data['content'] post.is_active = form.cleaned_data['is_active'] post.comments_enabled = form.cleaned_data['comments_enabled'] post.put() return redirect(post.get_absolute_url()) else: form r = render( request, 'admin/edit.html', { 'post': post, 'form': form } ) return r
def fetch(url): from core.models import Post d = feedparser.parse(url) entries = d.entries for entry in entries: try: content = entry.content and entry.content[0].value except AttributeError: content = entry.summary or entry.title try: created_at = strp_datetime(entry.published) except ValueError: print(entry.published) created_at = None try: tags = entry.tags except AttributeError: tags = [] _, ok = Post.update_or_create( author_id=2, title=entry.title, orig_url=entry.link, content=strip_tags(content), created_at=created_at, tags=[tag.term for tag in tags], )
def post(self, request, **kwargs): ancestor_key = Post.get_key(kwargs.get('id', None)) comment_id = Comment(parent=ancestor_key, name=request.POST.get('name', ''),\ url=request.POST.get('url', ''), email=request.POST.get('email', ''), body=request.POST.get('body', '')).put().id() return HttpResponse(json.dumps({'status': 'OK', 'message': 'Comment Created', 'id': comment_id}))
def test_post_update(self): """ lets update it """ res = self.c.put('/post/edit/{0}'.format(self.post_id), {'title': 'Sample Title Updated', 'synopsis': 'The Synopsis Updated', 'content': 'The Content Updated'}) self.assertEqual(Post.get(self.post_id).title, 'Sample Title Updated')
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('main.home')) return render_template('create_post.html', title='New Post', form=form, legend='New Post')
def post(request): current_user = request.user try: tid = int(request.POST.get('tid')) except: return render_error(request, 'No thread id supplied') content = request.POST.get('content') if not content: return render_error(request, 'No content supplied') thread = Thread.objects.get(id=tid) post = Post(thread=thread, content=content, author=current_user) post.save() next = request.GET.get('next', reverse('thread', args=[thread.id])) return redirect(next)
def test_get_queryset_returns_accurate_values_for_num_loves(self): queryset = Post.get_queryset(self.user_1.id) for post in queryset: if post.num_loves == 2: self.assertIn(post, self.posts_with_2_loves) elif post.num_loves == 1: self.assertIn(post, self.posts_with_1_love) else: self.assertIn(post, self.posts_with_no_love)
def test_comment_create(self): res = self.c.post('/post/{0}/comment'.format(self.post_id), {'name': 'John Lennon', 'url': 'http://url.tld', 'email': '*****@*****.**', 'body': 'New Comment'}) # Comment created self.assertEqual(len(Post.get_all_comments(self.post_id)), 1)
def put(self, request, id, **kwargs): coerce_put_post(request) post = Post.get(id) if post: post.title = request.PUT.get('title', '') post.synopsis = request.PUT.get('synopsis', '') post.content = request.PUT.get('content', '') post.put() return HttpResponse(json.dumps({'status': 'OK', 'message': 'Post Updated'})) return HttpResponse(json.dumps({'status': 'Error', 'message': 'Post not foud'}))
def create_post(request): """ Create a new post """ local = {} if request.method == 'POST': try: title = request.POST.get('title') content = request.POST.get('content') post = Post(title=title, content=content) post.put() return HttpResponseRedirect('/') except: status = "msg msg-error" message = "Error: Create post" local = { "status": status, "message": message } return direct_to_template(request, 'create_post.html', local)
def post(self, request): image = request.POST.get('image') caption = request.POST.get('caption') public = request.POST.get('status') poster = request.POST.get('post_by') post = Post() post.poster_id = poster post.caption = caption post.public = public == "public" post.save() if image != "": type, content = image.split(";base64,") _, ext = type.split('/') image = ContentFile(base64.b64decode(content), "{}.{}".format(post.id, ext)) post.post_image = image post.save() return Response("success")
def get(self, request): favorites = Favorite.objects.filter(user=request.user) favorites = [favorite.busline for favorite in favorites] favorites_posts = [] for busline in favorites: posts = Post.api_filter_contains(busline, limit=1) favorites_posts = favorites_posts + list(posts) return render_to_response('home.html', locals(), context_instance=RequestContext(request))
def setUp(self): super(PostTestCase, self).setUp() self.post = Post( title = 'Test Post', brief = 'To infinity ... and beyond.', content = 'Vestibulum id ligula porta felis euismod semper.', is_active = True, comments_enabled = False, date_published = datetime.date(2013,07,04), ) self.client = Client()
def add_post(request): params = request.POST text, login, name, password = (params['text'], params['login'], params['name'], params['password']) text = crypt.encrypt_text(password,text) passhash = crypt.hash_text(password) post = _get_post(login,name) if post: if passhash == post.password: post.text = text post.save() return render_to_json({'success': True}) else: return render_to_json({'success': False}) #create new post p = Post() p.text, p.login, p.name, p.password = text, login, name, passhash p.save() return render_to_json({'success': True})
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])
def test_can_create_simple_post(self): post = Post() post.title = "should be title" post.subtitle = "should be subtitle" post.created = datetime.now() post.body = "should be body" post.save() post_find = Post.objects.get(title=post.title) self.assertEquals(post_find.title, post.title) self.assertEquals(post_find.id, post.id) self.assertEquals(post_find.subtitle, post.subtitle) self.assertEquals(post_find.body, post.body) self.assertEquals(post_find.created, post.created) post.delete()
def tags(request): """ Get exhaustive list of Tags for published Posts :return: tags [LIST] list of Post tags """ # Grab all published Posts post_query = Post.query(ancestor=get_blog_key()).filter(Post.published == True) # Remove duplicates tags = list(set(flatten_list([post.tags for post in post_query.iter()]))) return json_response(tags)
def save_post(): form = PostForm(request.form) if request.method == 'POST' and form.validate(): blog = Routes.response_sql() title = form.title.data content = form.content.data p = Post( title=title, content=content, blog_id=blog.id_blog, create_date=datetime.datetime.now(), update_date=datetime.datetime.now(), status=1, ) if 'tag' in request.form.keys() and request.form['tag'] != '': tag_post = request.form['tag'].split() tag_list = list() for tag in tag_post: tag_query = Tag.query.filter_by(name=tag_post) if tag_query.count() == 1: id_tag = tag_query.first().id_tag else: tag_model = Tag( name=tag, create_date=datetime.datetime.now(), update_date=datetime.datetime.now(), status=1, ) tag_list += [tag_model] if len(tag_list) > 0: db.session.add_all(tag_list) db.session.commit() id_tag = db.session.query(Tag).order_by( Tag.id_tag.desc()).first().id_tag p.tag_id = id_tag db.session.add(p) db.session.commit() return redirect(url_for('admin.default'))
def post_index(request): posts = Post.query( Post.is_active == True ).order( -Post.created_at ).fetch() r = render( request, 'post/index.html', { 'posts': posts } ) return r
def posts(request, post_id=None, tags=None, page=None, titles_only=False, published_only=False): """ Get Published Blog Posts :param tags [LIST] of tags to filter on [optional] :param page [INT] page number of Posts to return [optional] :param titles_only [BOOLEAN] return Post titles and stamps only [optional] :param published_only [BOOLEAN] return published Posts only [optional] :param post_id [LONG] Post identifier [optional] :return: posts [LIST] List of Posts """ # ID filter (if we get an ID parameter lets assume the user wants all the info on that Post) if post_id: post = Post.get_by_id(post_id, parent=get_blog_key()) iterator = [post] if post else [] else: # If no ID specified, get all Posts ordered by stamp for our Blog post_query = Post.query(ancestor=get_blog_key()).order(-Post.stamp) # Published filter if published_only: post_query = post_query.filter(Post.published == True) # Tag filter if tags: post_query = post_query.filter(Post.tags.IN(tags)) # Page Filter if page is not None: iterator = post_query.fetch(POST_PAGE_SIZE, offset=page * POST_PAGE_SIZE) else: iterator = post_query.fetch() # Preview or full Post if titles_only: response = json_response([post.preview() for post in iterator]) else: response = json_response([post.dictionary() for post in iterator]) return response
def pages(request, tags=None): """ Get number of pages of Blog Posts :param tags [LIST] of tags to filter on [optional] :return: pages [INT] number of pages """ # Grab all published Posts post_query = Post.query().filter(Post.published == True) # Apply Tag filter if tags: post_query = post_query.filter(Post.tags.IN(tags)) return HttpResponse(page_count(post_query.count(), POST_PAGE_SIZE))
def admin_add_post(request): form = PostForm() if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = Post( title = form.cleaned_data['title'], brief = form.cleaned_data['brief'], content = form.cleaned_data['content'], is_active = form.cleaned_data['is_active'], comments_enabled = form.cleaned_data['comments_enabled'], ) post.put() return redirect(post.get_absolute_url()) else: form = PostForm() r = render( request, 'admin/add.html', { 'form': form } ) return r
def admin_delete_post(request, slug, year, month, day): post = Post.query( ndb.AND( Post.slug == slug, Post.date_published == datetime.datetime( int(year), int(month), int(day) ) ) ).get() post.key.delete() return redirect('/')
def home(): form = PostForm() if form.validate_on_submit(): post = Post(fact=form.fact.data, source=form.source.data, author=current_user) db.session.add(post) db.session.commit() flash('Your post has been added!', 'success') return redirect(url_for('home')) posts = Post.query.order_by(Post.date_posted.desc()).all() return render_template('home.html', form=form, posts=posts, current_user=current_user)
def search(): if not g.search_form.validate(): return redirect(url_for('main.explore')) page = request.args.get('page', 1, type=int) posts, total = Post.search(g.search_form.q.data, page, app.config['POSTS_PER_PAGE']) next_url = url_for('search', q=g.search_form.q.data, page=page + 1) \ if total > page * app.config['POSTS_PER_PAGE'] else None prev_url = url_for('search', q=g.search_form.q.data, page=page - 1) \ if page > 1 else None return render_template('search.html', title=_('Search'), posts=posts, next_url=next_url, prev_url=prev_url)
def create_posts(count=100): from random import seed, randint import forgery_py seed() user_count = User.query.count() for i in range(count): u = User.query.offset(randint(0, user_count -1)).first() p = Post( title = forgery_py.lorem_ipsum.sentence(), body = forgery_py.lorem_ipsum.sentences(randint(1,3)), author_id=u.id ) db.session.add(p) db.session.commit() return '{} Posts created'.format(Post.query.count())
def handle(self, *args, **kwargs): locale.setlocale(locale.LC_ALL, 'ru_RU.UTF-8') resp = requests.get(DATA_URL) data = json.loads(resp.text) Post.objects.bulk_create([ Post(post_id=int(item['id']), category=item['category'], from_whom=item['from'], title=item['title'], text=item['text'], thedate=datetime.datetime.strptime(item['thedate'], '%d %B %Y года')) for item in data['items'] ], ignore_conflicts=True)
def test_can_add_tags_to_post(self): tag1 = Tag(name='my first tag', slug='my-first-tag') tag1.save() tag2 = Tag(name='my second tag', slug='my-second-tag') tag2.save() post = Post() post.title = "should be title" post.subtitle = 'should be subtitle' post.created = datetime.now() post.body = "should be body" post.save() post.tags = [tag1, tag2] post_found = Post.objects.get(title=post.title) self.assertIn(tag1, post_found.tags.all()) self.assertIn(tag2, post_found.tags.all()) self.assertEquals(len(post_found.tags.all()), 2)
def postSave(self, msg, parent_post=None, audio_URL=None, attachments=None, attachmentsName=None): """-- Save a message as *POST* :param msg: The text of a message. :param parent_post: The parent post if it is a comment. :param audio_URL: URL to the audio file. :param attachments: URLs to attachments. :param attachmentsName: Names of attachments. """ postuser = self.socket.session['DjangoUser'] textcontent = msg # activity to assign post to activityType = self.socket.session['roomType'] activityID = self.socket.session['roomNumber'] # validation and save if len(textcontent) > 0: mess = Post(text=textcontent) mess.creator = postuser if parent_post: mess.parent_post = Post.objects.get(pk=parent_post) if audio_URL: mess.audio_URL = audio_URL if mess: mess.save() # print "message successfully saved to database" # bind message to the document if attachments: for attachment in attachments: # accessURL is "media/documents/filename" targetDoc = Document.objects.filter( accessURL=attachment)[0] targetDoc.content_object = mess targetDoc.save() # save mess with that activity activity = self.socket.session['DjangoRoom'] activity.posts.add(mess) return mess else: return False
def bot_process(user_id, data): print(data) number_of_users = data["number_of_users"] max_posts_per_user = data["max_posts_per_user"] max_likes_per_user = data["max_likes_per_user"] # algorithm is not ideal, # because users can like their own posts, # but for the sake of better readability was decided to make it so new_users_ids_start = User.objects.last().id + 1 new_users_ids_end = new_users_ids_start + number_of_users - 1 new_users_ids_range = range(new_users_ids_start, new_users_ids_end + 1) User.objects.bulk_create( User.objects.initialize_user(**get_random_user_data()) for _ in range(number_of_users)) new_posts_ids_start = Post.objects.last().id + 1 posts = Post.objects.bulk_create( Post(user_id=user_id, **get_random_post_data()) for _ in range(random.randint(0, max_likes_per_user)) for user_id in new_users_ids_range) new_posts_ids_end = new_posts_ids_start + len(posts) - 1 new_posts_ids_range = range(new_posts_ids_start, new_posts_ids_end + 1) Like.objects.bulk_create( Like(user_id=user_id, **get_random_like_data(new_posts_ids_range)) for _ in range(random.randint(0, max_posts_per_user)) for user_id in new_users_ids_range) channel_layer = get_channel_layer() # Sends message to channels group in order to inform user async_to_sync(channel_layer.group_send)(f'ws_bot_{user_id}', { 'type': 'message_from_bot', "message": "work is done" }) return None
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) return render_template('index.html', title='Home', form=form, posts=posts.items)
def handle(self, *args, **kwargs): with open(args[0]) as file: xml = minidom.parseString(file.read()) for row in xml.getElementsByTagName('row'): post = Post() for node in row.childNodes: if node.nodeType != node.TEXT_NODE: attr = node.getAttribute('name') try: post.__dict__[attr] = node.firstChild.data except AttributeError: post.__dict__[attr] = '' print 'Post:', repr(post.title) post.published_date = post.created_date post.user = User.objects.get(username='******') post.save()
def post_create(req): page = "post-create-page" if req.method == 'GET': context = { 'current_user': req.user, 'form': PostForm(), 'page': page, } return render(req, 'post-create.html', context) creator_obj = req.user.userprofile creator_post = Post(creator=creator_obj) form = PostForm(req.POST, req.FILES, instance=creator_post) if form.is_valid(): form.save() return redirect('post list') context = { 'form': form, 'current_user': req.user, 'page': page, } return render(req, 'post-create.html', context)
def post_view(request, slug, year, month, day): post = Post.query( ndb.AND( Post.slug == slug, Post.date_published == datetime.datetime( int(year), int(month), int(day) ), Post.is_active == True, ) ).get() if post is None: raise Http404 r = render( request, 'post/view.html', { 'post': post, 'disqus_shortname': settings.DISQUS_SHORTNAME } ) return r
def postSave(self, msg, parent_post=None, audio_URL=None, attachments = None, attachmentsName = None): """-- Save a message as *POST* :param msg: The text of a message. :param parent_post: The parent post if it is a comment. :param audio_URL: URL to the audio file. :param attachments: URLs to attachments. :param attachmentsName: Names of attachments. """ postuser = self.socket.session['DjangoUser'] textcontent = msg # activity to assign post to activityType = self.socket.session['roomType'] activityID = self.socket.session['roomNumber'] # validation and save if len(textcontent) > 0: mess = Post(text=textcontent) mess.creator = postuser if parent_post: mess.parent_post = Post.objects.get(pk=parent_post) if audio_URL: mess.audio_URL = audio_URL if mess: mess.save() # print "message successfully saved to database" # bind message to the document if attachments: for attachment in attachments: # accessURL is "media/documents/filename" targetDoc = Document.objects.filter(accessURL = attachment)[0] targetDoc.content_object = mess targetDoc.save() # save mess with that activity activity = self.socket.session['DjangoRoom'] activity.posts.add(mess) return mess else: return False
def create_post(title, body, user): post = Post(title=title, body=body, author=user) post.save() return post.toJSON()
def insert_post(title, body, original_link): newpost = Post(title=title, content=body, original_link=original_link) session.add(newpost) session.commit()
def get_queryset(self): """Returns queryset in order of date last modified by default""" qs = Post.get_queryset(self.request.user.id) return qs
def test_get_queryset_returns_accurate_values_for_in_love_profile_2(self): queryset = Post.get_queryset(self.user_2.id) queryset_with_loved_posts = queryset.filter(loves__fan=self.user_2) expected = self.posts_with_2_loves + self.posts_with_1_love for post in queryset_with_loved_posts: self.assertIn(post, expected)
def update(): """Reindex Posts.""" Post.reindex()
def test(request): template = """ <strong>{0}:</strong><br> Result: {1}<br> <hr> """ response = "<h1>TESTE:</h1>" Imagem( seq_imagem=1, des_hash=hashlib.sha1("foo").hexdigest(), nom_imagem=hashlib.sha1("foo").hexdigest() + ".jpg", des_diretorio="/2015/01/07/", dat_cadastro=timezone.now(), ).save() response = response + template.format('Imagem', Imagem.objects.get(seq_imagem=1)) Usuario(seq_usuario=1, seq_imagem=Imagem(seq_imagem=1), cod_usuario="clagomess", nom_usuario=u"Cláudio Gomes", des_email="*****@*****.**", des_senha=hashlib.sha1("010203").hexdigest(), dat_cadastro=timezone.now(), dat_ultimo_acesso=timezone.now()).save() response = response + template.format('Usuario', Usuario.objects.get(seq_usuario=1)) Post(seq_post=1, seq_usuario=Usuario(seq_usuario=1), cod_post=base64.b64encode( timezone.now().strftime("%H%M%S%f")).replace("=", ''), des_post=u"Olá Amiguinhos!", dat_post=timezone.now()).save() response = response + template.format('Post', Post.objects.get(seq_post=1)) Like(seq_like=1, seq_post=Post(seq_post=1), seq_usuario=Usuario(seq_usuario=1)).save() response = response + template.format('Like', Like.objects.get(seq_like=1)) Notificacao(seq_notificacao=1, seq_usuario=Usuario(seq_usuario=1), dat_notificacao=timezone.now()).save() response = response + template.format( 'Notificacao', Notificacao.objects.get(seq_usuario=1)) Seguidor(seq_seguidor=1, seq_usuario_seguidor=Usuario(seq_usuario=1), seq_usuario_seguido=Usuario(seq_usuario=1), dat_seguidor=timezone.now()).save() response = response + template.format('Seguidor', Seguidor.objects.get(seq_seguidor=1)) return HttpResponse(response)
def save(self, *args, **kwargs): if not self.id: super(Issue, self).save() if not self.author.landlord and self.author.phone: client = TwilioRestClient(settings.TWILLIO_ACCOUNT, settings.TWILLIO_TOKEN) message = client.sms.messages.create( to=self.house.landlord.phone, from_="+441827231000", body="Issue Raised: " + self.title + " on " + self.house.name) post = Post() post.text = "The issue '" + self.title + "' has been raised" post.posted_by = self.author post.save() if self.resolved: super(Issue, self).save() for user in self.house.user_set.all(): if user.phone: client = TwilioRestClient(settings.TWILLIO_ACCOUNT, settings.TWILLIO_TOKEN) message = client.sms.messages.create( to=user.phone, from_="+441827231000", body="The issue '" + self.title + "' has been resolved.") post = Post() post.text = "The issue '" + self.title + " has been resolved" post.posted_by = self.house.landlord post.save() else: super(Issue, self).save()
def save_results(self, instagram_results): """ Implement yourself to work out what to do with each extract batch of posts :param instagram_results: A list of Instagram Posts """ for result in instagram_results: if not self.already_saved(result.post_id): post = Post() post.enterprise = self.get_enterprise(result.hashtags()) post.username = result.user.id post.user_display_name = result.user.bio post.text = result.processed_text() tz = pytz.timezone("UTC") post.date_posted = datetime.fromtimestamp( result.created_at, tz) post.external_id = result.post_id if result.is_video: post.file = self.get_video(result.code) else: post.file = result.display_src post.save()