def post(self, request, *args, **kwargs): if not request.user.has_perm('accounts.view_profile'): return render(request, '401.html') searchText = '' found_msg = None found_file = None # deal with search if ('search' in request.POST): if request.POST['search'].strip(): searchText = '' found_msg = None found_file = None found_bulletin = None searchText = request.POST['search'] entry_query = get_query(searchText, ['context', 'title', 'tag1']) found_msg = Post.objects.filter(entry_query).order_by('-time') entry_query = get_query(searchText, ['docfile', 'doctypeTag']) found_file = Document.objects.filter(entry_query).order_by( '-time') entry_query = get_query(searchText, ['title', 'context']) found_bulletin = Bulletin.objects.filter(entry_query).order_by( '-time') datalist = sorted(chain(list(found_msg), list(found_file), list(found_bulletin)), key=lambda instance: instance.time, reverse=True) else: datalist = [] #datalist = found_msg return render(request, self.template_name, {'alldata': datalist}) # deal with create announcement elif ('announce_title' in request.POST and 'announce_text' in request.POST): newdoc = Post() newdoc.title = request.POST['announce_title'] newdoc.context = request.POST['announce_text'] newdoc.tag1 = "announcement" newdoc.author = MyProfile.objects.get(user=request.user) newdoc.save() return redirect("/home")
def test_posts_view_preview(self): """A post of more than 40 chars is shortened.""" this_user = self.users[0] this_post = Post() this_post.author = this_user this_post.content = ( '11111111111111111111' + '11111111111111111111' + '11111111111111111111') this_post.title = 'marc ben benny built this site' this_post.save() self.client.force_login(self.users[1]) response = self.client.get( '/posts/', follow=True) self.assertContains( response, ('11111111111111111111' + '11111111111111111111' + '...') )
def test_add_notification_when_add_answer(self): post = Post( type='answer', parent=Post.objects.get(pk=1), content='Ok', created_by=self.admin ) post.save() self.check_unread_notifications() self.check_notifications_per_user( post.parent.followed_by.all(), post.created_by ) self.check_users_per_notification() self.check_notification( Notification.objects.latest('created_date'), type='02', content='', users=post.parent.followed_by.all() )
def setUpClass(cls): super().setUpClass() settings.MEDIA_ROOT = tempfile.mkdtemp(dir=settings.BASE_DIR) cls.user = User.objects.create(username='******') cls.user_2 = User.objects.create(username='******') # Создадим запись в БД для проверки доступности адреса cls.group = Group.objects.create( title='Заголовок тестовой задачи', slug='test-slug', description='Описание' ) cls.group_2 = Group.objects.create( title='Заголовок тестовой задачи второй группы', slug='second-slug', description='Описание второй группы' ) small_gif = ( b'\x47\x49\x46\x38\x39\x61\x02\x00' b'\x01\x00\x80\x00\x00\x00\x00\x00' b'\xFF\xFF\xFF\x21\xF9\x04\x00\x00' b'\x00\x00\x00\x2C\x00\x00\x00\x00' b'\x02\x00\x01\x00\x00\x02\x02\x0C' b'\x0A\x00\x3B' ) cls.image = SimpleUploadedFile( name='small.gif', content=small_gif, content_type='image/gif' ) cls.post = Post.objects.create( text='Текст', group=cls.group, author=cls.user, image=cls.image, ) posts = [Post(text='Текст', group=cls.group, author=cls.user) for i in range(12)] Post.objects.bulk_create(posts)
def create(request): '''title and url coming from create.html textfield''' if request.method == 'POST': if request.POST['title'] and request.POST['url']: post = Post() post.title = request.POST['title'] if request.POST['url'].startswith( 'http://') or request.POST['url'].startswith('https://'): post.url = request.POST['url'] else: post.url = "http://" + request.POST['url'] post.pub_date = timezone.datetime.now() post.author = request.user post.save() return redirect('home') else: return render(request, 'posts/create.html', {'error': 'ERROR. Fill in all the Field'}) else: return render(request, 'posts/create.html')
def handle(self, *args, **options): batch_size = 100 path = os.path.join(os.path.dirname(os.path.realpath( __file__)), 'data/bioinformatics_posts_se.xml') tree = ET.parse(path) root = tree.getroot() x = {'OwnerDisplayName', 'CreationDate', 'AcceptedAnswerId', 'Tags', 'Id', 'AnswerCount', 'LastEditorUserId', 'LastActivityDate', 'OwnerUserId', 'Title', 'ClosedDate', 'PostTypeId', 'ViewCount', 'CommentCount', 'LastEditDate', 'Body', 'ParentId', 'Score', 'FavoriteCount'} objs = (Post( post_id=row.get('Id'), post_type_id=row.get('PostTypeId'), score=row.get('Score'), comment_count=row.get('CommentCount'), creation_date=self.get_ts(row.get('CreationDate')), last_activity_date=self.get_ts(row.get('LastActivityDate')), body=row.get('Body'), owner_user_id=row.get('OwnerUserId'), owner_display_name=row.get('OwnerDisplayName'), accepted_answer_id=row.get('AcceptedAnswerId'), tags=row.get('Tags'), answer_count=row.get('AnswerCount'), last_edit_user_id=row.get('LastEditorUserId'), title=row.get('Title'), closed_date=self.get_ts(row.get('ClosedDate')), view_count=row.get('ViewCount'), last_edit_date=self.get_ts(row.get('LastEditDate')), parent_id=row.get('ParentId'), favorite_count=row.get('FavoriteCount') ) for row in root.findall('row')) while True: batch = list(islice(objs, batch_size)) if not batch: break Post.objects.bulk_create(batch, batch_size)
def create(self, validated_data): subforum = validated_data['subforum'] user = validated_data['user'] title = validated_data['title'] post = validated_data['post'] thread_obj = Thread( subforum=subforum, user=user, title=title, ) thread_obj.save() post_obj = Post( user=thread_obj.user, thread=thread_obj, content=post, ) post_obj.save() thread_slug = Thread.objects.get(id=thread_obj.id).thread_slug validated_data['thread_slug'] = thread_slug return validated_data
def post(self, request): # Get Current User user = request.user # Create Post Instance post = Post(user=user) # Create PostSerializer Instance post_serializer = CreatePostSerializer(post, data=request.data) # Check Validation if post_serializer.is_valid(): # Save Model post_serializer.save() # Return Model return Response(post_serializer.data, status=status.HTTP_201_CREATED) # Return Error return Response(post_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, *args, **kwargs): form = request.data.get('formData', None) if form is None: return Response({'message': 'Invalid data received.'}, status=HTTP_404_NOT_FOUND) selected_categories = request.data.get('selectedCategories') if len(selected_categories) < 1: return Response( {'message': 'You must select at least one category.'}, status=HTTP_404_NOT_FOUND) if request.user.is_authenticated: current_author, created = Author.objects.get_or_create( user=request.user) created_post = Post(title=form['title'], overview=form['overview'], author=current_author, thumbnail=form['thumbnail'], content=form['content']) created_post.save() for category in selected_categories: selected_category = Category.objects.get(title=category) created_post.category.add(selected_category) created_post.save() return Response( { 'message': 'Successfully created a new post.', 'id': created_post.id }, status=HTTP_201_CREATED) else: return Response({'message': 'You must login first.'}, status=HTTP_401_UNAUTHORIZED)
def create(request): context = {} if request.method == 'GET': if request.GET.get('title'): context['title'] = request.GET.get('title') else: context['title'] = '' if request.GET.get('link'): context['link'] = request.GET.get('link') else: context['link'] = '' return render(request, 'posts/create.html', context) elif request.method == 'POST': title = request.POST.get("title", "") link = request.POST.get("link", "") editorvalue = request.POST.get("editorvalue", "") public = request.POST.get("public", "") public_bool = (public == 'public') user = request.user slug = slugify(title[:100]) if len(Post.objects.filter(slug=slug)) > 0: slug += '-' + str(math.floor(random.uniform(1000, 9999))) if title == None or title == '': context['message'] = 'You need a title :)' else: p = Post(author=user, title=title, text=editorvalue, link=link, slug=slug, public=public_bool) p.save() context['message'] = 'Message posted!' response = render(request, 'posts/success.html', context) response['X-IC-Redirect'] = '/post/' + slug return response return render(request, 'posts/success.html', context) return render(request, 'posts/create.html', context)
def create_post(request): user = User.objects.get(username = '******') #token не работает, так как подкорректирован. У вас должен быть свой token = 'f88de38bf88de38bf88de38bd3f8fc7a6fff88df88de38ba620dc9725559b497361de40' version = 5.103 domain = 'tproger' response = requests.get('https://api.vk.com/method/wall.get', params={ 'access_token': token, 'v': version, 'domain': domain, 'count': 5 } ) data = response.json()['response']['items'] for news in data: try: if news['attachments'][0]['type']: img_url = news['attachments'][0]['photo']['sizes'][-1]['url'] else: img_url = '' except: img_url = '' try: news['attachments'][0]['video'] except: if news['text'] != '': in_post = Post.objects.filter(post_text = news['text']) else: in_post = Post.objects.filter(post_image_url = img_url) if not in_post: post = Post(author = user, post_text=news['text'], post_time = timezone.now(), post_image_url=img_url) post.save() return HttpResponse('Complete ')
def post(self, request): """ Presenta el formuario para crear un post y en el caso de que la petición sea post la valida y la crea en el caso de que sea válida Args: request: returns: """ message = None post_with_user = Post(owner=request.user) post_form = PostCreationForm(request.POST, instance=post_with_user) if post_form.is_valid(): new_post = post_form.save() # post_form = PostCreationForm() # vaciamos el formulario message = 'Artículo creado satisfactoriamente <a href="{0}">Ver artículo</a>'.format( reverse('post_detail', args=[new_post.pk])) context = {'form': post_form, 'message': message} # return render(request, 'posts/post_creation.html', context) messages.add_message(request, messages.INFO, "Artículo creado satisfactoriamente") return redirect(reverse('post_detail', args=[new_post.pk]))
def post(self, request): # Define new instance post = Post() # Add user logged post.owner = request.user # Create form form = PostForm(request.POST, request.FILES, instance=post) # Validate form if form.is_valid(): # Create add post = form.save() # Clear form form = PostForm() # Redirect return redirect('blogs') context = {'form': form} return render(request, 'posts/new_post.html', context)
def save(self, request): data = self.cleaned_data category = Caterory.objects.get(pk=int(data['category'])) # Split to string the tags name_tags = data['tags'].split(',') tags = [] for name_tag in name_tags: tags.append(Tag.objects.get(name_tag=name_tag)) post = Post( title=data['title'], subtitle=data['subtitle'], content=data['content'], author=request.user, category=category ) post.save() post.tags.set(tags) post.save()
def setUpClass(cls): super().setUpClass() cls.user = User.objects.create(username='******') # Создадим запись в БД для проверки доступности адреса cls.group = Group.objects.create(title='Заголовок тестовой задачи', slug='test-slug', description='Описание') cls.group_2 = Group.objects.create( title='Заголовок тестовой задачи второй группы', slug='second-slug', description='Описание второй группы') cls.post = Post.objects.create( text='Текст', group=cls.group, author=cls.user, ) # Создадим большое кол-во постов для проверки паджинатора posts = [ Post(text='Текст', group=cls.group, author=cls.user) for i in range(12) ] Post.objects.bulk_create(posts)
def test_comment_length_render_on_other_user_profile(self): """Test comment length render on profile post.""" this_user = self.users[0] this_post = Post() this_post.author = this_user this_post.save() this_comment = Comment() this_comment.by_user = this_user this_comment.on_post = this_post this_comment.save() this_comment = Comment() this_comment.by_user = this_user this_comment.on_post = this_post this_comment.save() this_comment = Comment() this_comment.by_user = this_user this_comment.on_post = this_post this_comment.save() self.client.force_login(self.users[1]) response = self.client.get( '/profile/' + str(this_user.username), follow=True) self.assertContains(response, 'Comments: (3)')
def post_repost(request, pk=None): """ Repost a post. This always reposts the original post. Redirects to the post's page if the repost was successful or if the user is not authenticated. Otherwise, redirects to the referer if present, or the landingpage if not. @param pk: the primary key which identifies the post @return redirect depending on the success """ user = request.user repost_original = Post.objects.get(pk=pk).original_or_self() check = repost_original.check_repost(user) if check == 'not_auth': return redirect('posts:post', pk=repost_original.pk) if check != 'ok': return redirect(request.META['HTTP_REFERER'] or 'landingpage') repost = Post(content=repost_original.content, author=user, repost_original=repost_original) repost.save() context = { 'content': "There is a new repost to a post of you made by %s" % user.username, 'link_to_subject': reverse("posts:post", kwargs={'pk': repost.pk}) } send_notifications(repost_original.author, "There is a new repost to your post", 'users/notification_for_post_email.html', context, repost) return redirect('posts:post', pk=repost.pk)
def post(self, request): if request.user.is_authenticated is False: return redirect('home') form = NewPostForm(request.POST) if form.is_valid(): title = form.cleaned_data.get('title') url = form.cleaned_data.get('url') introduction = form.cleaned_data.get('intro') body = form.cleaned_data.get('body') categories = form.cleaned_data.get('categories') publication_date = form.cleaned_data.get('pub_date') post = Post(owner=User.objects.get(username=request.user.username), title=title, url=url, introduction=introduction, body=body, publication_date=publication_date) post.save() post.categories.set(categories) url = request.GET.get('next', 'home') return redirect(url) return self.render_template_with_form(request, form)
def mutate(root, info, title, content): message = '' user = info.context.user today = datetime.datetime.now().strftime('%d %B %Y') # Filter posts that belongs to user and are posted today filtered_posts = Post.objects.filter(user__username=user, posted=today) fields_are_not_filled = title == '' or content == '' title_has_reached_limit_of_chars = len(title) > 100 user_posted_maximum_posts = filtered_posts.count() >= 5 content_has_reached_limit_of_chars = len(content) > 10000 if fields_are_not_filled: raise GraphQLError('Fields are not filled!') elif title_has_reached_limit_of_chars and user_posted_maximum_posts: message = 'Title has more than 100 characters and you have reached your maximum posts per day!' elif title_has_reached_limit_of_chars: message = 'Title has more than 100 characters!' elif user_posted_maximum_posts: message = 'You have reached your maximum posts per day!' elif content_has_reached_limit_of_chars: message = 'Content is over 10,000 characters!' else: # Create date when was the post posted posted = datetime.datetime.now().strftime('%d %B %Y') post = Post(title=title, content=content, user=user, posted=posted) post.save() message = 'Success' return CreatePost(message=message)
def setUpClass(cls): super().setUpClass() settings.MEDIA_ROOT = tempfile.mkdtemp(dir=settings.BASE_DIR) cls.user_0 = get_user_model().objects.create(username="******", first_name="Andrey", last_name="Turutov") small_gif = (b"\x47\x49\x46\x38\x39\x61\x02\x00" b"\x01\x00\x80\x00\x00\x00\x00\x00" b"\xFF\xFF\xFF\x21\xF9\x04\x00\x00" b"\x00\x00\x00\x2C\x00\x00\x00\x00" b"\x02\x00\x01\x00\x00\x02\x02\x0C" b"\x0A\x00\x3B") cls.uploaded = SimpleUploadedFile(name="small.gif", content=small_gif, content_type="image/gif") posts_count = 20 new_groups = [ Group(title=f"Тестовое название группы {post}", slug=f"slug{post}", description="Тестовое описание группы") for post in range(posts_count) ] Group.objects.bulk_create(new_groups) new_posts = [ Post(text="Тестовая запись", author=cls.user_0, group=Group.objects.get(id=(post + 1)), image=cls.uploaded) for post in range(posts_count) ] Post.objects.bulk_create(new_posts)
def run_one_node(self, node): start_time = time.time() invoices_details = lnclient.listinvoices( index_offset=node.global_checkpoint, rpcserver=node.rpcserver, mock=settings.MOCK_LN_CLIENT) if node not in self.all_invoices_from_db: invoice_list_from_db = {} logger.info("DB has no invoices for this node") else: invoice_list_from_db = self.all_invoices_from_db[node] # example of invoices_details: {"invoices": [], 'first_index_offset': '5', 'last_index_offset': '72'} invoice_list_from_node = invoices_details['invoices'] self.invoice_count_from_nodes[node] = len(invoice_list_from_node) if settings.MOCK_LN_CLIENT: # Here the mock pulls invoices from DB Invoice model, while in prod invoices are pulled from the Lightning node # 1. Mocked lnclient.listinvoices returns an empty list # 2. The web front end adds the InvoiceRequest to the DB before it creates the actual invoices with lnclient.addinvoice # 3. Mocked API lnclient.addinvoice simply fakes converting InvoiceRequest to Invoice and saves to DB # 4. Here the mocked proces_tasks pulls invoices from DB Invoice model and pretends they came from lnclient.listinvoices # 5. After X seconds passed based on Invoice created time, here Mock update the Invoice checkpoint to "done" faking a payment invoice_list_from_node = [] for invoice_obj in Invoice.objects.filter( lightning_node=node, checkpoint_value="no_checkpoint"): invoice_request = InvoiceRequest.objects.get( id=invoice_obj.invoice_request.id) if invoice_request.lightning_node.id != node.id: continue mock_setteled = (invoice_obj.created + timedelta(seconds=3) < timezone.now()) creation_unixtime = int( time.mktime(invoice_obj.created.timetuple())) invoice_list_from_node.append({ "settled": mock_setteled, "settle_date": str(int(time.time())) if mock_setteled else 0, "state": "SETTLED" if mock_setteled else "OPEN", "memo": invoice_request.memo, "add_index": invoice_obj.add_index, "payment_request": invoice_obj.pay_req, "pay_req": invoice_obj.pay_req, # Old format "r_hash": invoice_obj.r_hash, "creation_date": str(creation_unixtime), "expiry": str(creation_unixtime + 120) }) retry_mini_map = { int(invoice['add_index']): False for invoice in invoice_list_from_node } one_hour_ago = timezone.now() - timedelta(hours=1) recent_invoices = [ i.id for i in invoice_list_from_db.values() if i.modified > one_hour_ago ] if len(recent_invoices) == 0: logger.info("invoice_list_from_db is empty") else: logger.info( "Recent invoice_list_from_db was: {}".format(recent_invoices)) for raw_invoice in invoice_list_from_node: # Example of raw_invoice: # { # 'htlcs': [], # 'settled': False, # 'add_index': '5', # 'value': '1', # 'memo': '', # 'cltv_expiry': '40', 'description_hash': None, 'route_hints': [], # 'r_hash': '+fw...=', 'settle_date': '0', 'private': False, 'expiry': '3600', # 'creation_date': '1574459849', # 'amt_paid': '0', 'features': {}, 'state': 'OPEN', 'amt_paid_sat': '0', # 'value_msat': '1000', 'settle_index': '0', # 'amt_paid_msat': '0', 'r_preimage': 'd...=', 'fallback_addr': '', # 'payment_request': 'lnbc...' # } created = general_util.unixtime_to_datetime( int(raw_invoice["creation_date"])) if created < general_util.now() - settings.INVOICE_RETENTION: logger.info( "Got old invoice from listinvoices, skipping... {} is older then retention {}" .format(created, settings.INVOICE_RETENTION)) continue add_index_from_node = int(raw_invoice["add_index"]) invoice = invoice_list_from_db.get(add_index_from_node) if invoice is None: logger.error( "Unknown add_index {}".format(add_index_from_node)) logger.error( "Raw invoice from node was: {}".format(raw_invoice)) if raw_invoice['state'] == "CANCELED": logger.error("Skipping because invoice is cancelled...") retry_mini_map[ add_index_from_node] = False # advance global checkpoint else: retry_mini_map[ add_index_from_node] = True # try again later continue # Validate if invoice.invoice_request.memo != raw_invoice["memo"]: logger.error( "Memo in DB does not match the one in invoice request: db=({}) invoice_request=({})" .format(invoice.invoice_request.memo, raw_invoice["memo"])) retry_mini_map[add_index_from_node] = True # try again later continue if invoice.pay_req != raw_invoice["payment_request"]: logger.error( "Payment request does not match the one in invoice request: db=({}) invoice_request=({})" .format(invoice.pay_req, raw_invoice["payment_request"])) retry_mini_map[add_index_from_node] = True # try again later continue checkpoint_helper = CheckpointHelper( node=node, invoice=invoice, creation_date=raw_invoice["creation_date"]) if checkpoint_helper.is_checkpointed(): continue if raw_invoice['state'] == 'CANCELED': checkpoint_helper.set_checkpoint("canceled") continue if raw_invoice['settled'] and (raw_invoice['state'] != 'SETTLED' or int(raw_invoice['settle_date']) == 0): checkpoint_helper.set_checkpoint("inconsistent") continue if time.time() > int(raw_invoice['creation_date']) + int( raw_invoice['expiry']): checkpoint_helper.set_checkpoint("expired") continue if not raw_invoice['settled']: logger.info("Skipping invoice at {}: Not yet settled".format( checkpoint_helper)) retry_mini_map[ checkpoint_helper.add_index] = True # try again later continue # # Invoice is settled # logger.info( "Processing invoice at {}: SETTLED".format(checkpoint_helper)) memo = raw_invoice["memo"] try: action_details = json_util.deserialize_memo(memo) except json_util.JsonUtilException: checkpoint_helper.set_checkpoint("deserialize_failure") continue try: validators.validate_memo(action_details) except ValidationError as e: logger.exception(e) checkpoint_helper.set_checkpoint("memo_invalid") continue action = action_details.get("action") if action: if action in ["Upvote", "Accept"]: vote_type = Vote.VOTE_TYPE_MAP[action] change = settings.PAYMENT_AMOUNT post_id = action_details["post_id"] try: post = Post.objects.get(pk=post_id) except (ObjectDoesNotExist, ValueError): logger.error( "Skipping vote. The post for vote does not exist: {}" .format(action_details)) checkpoint_helper.set_checkpoint("invalid_post") continue user = get_anon_user() logger.info( "Creating a new vote: author={}, post={}, type={}". format(user, post, vote_type)) vote = Vote.objects.create(author=user, post=post, type=vote_type) # Update user reputation # TODO: reactor score logic to be shared with "mark_fake_test_data.py" User.objects.filter(pk=post.author.id).update( score=F('score') + change) # The thread score represents all votes in a thread Post.objects.filter(pk=post.root_id).update( thread_score=F('thread_score') + change) if vote_type == Vote.ACCEPT: if "sig" not in action_details: checkpoint_helper.set_checkpoint("sig_missing") continue sig = action_details.pop("sig") sig = validators.pre_validate_signature(sig) verifymessage_detail = lnclient.verifymessage( msg=json.dumps(action_details, sort_keys=True), sig=sig, rpcserver=node.rpcserver, mock=settings.MOCK_LN_CLIENT) if not verifymessage_detail["valid"]: checkpoint_helper.set_checkpoint( "invalid_signiture") continue if verifymessage_detail[ "pubkey"] != post.parent.author.pubkey: checkpoint_helper.set_checkpoint( "signiture_unauthorized") continue if change > 0: # First, un-accept all answers for answer in Post.objects.filter( parent=post.parent, type=Post.ANSWER): if answer.has_accepted: Post.objects.filter(pk=answer.id).update( vote_count=F('vote_count') - change, has_accepted=False) # There does not seem to be a negation operator for F objects. Post.objects.filter(pk=post.id).update( vote_count=F('vote_count') + change, has_accepted=True) Post.objects.filter(pk=post.root_id).update( has_accepted=True) else: # TODO: change "change". here change is set to payment ammount, so does not make sense to be called change # TODO: detect un-accept attempt and raise "Un-accept not yet supported" raise Exeption( "Payment ammount has to be positive") else: Post.objects.filter(pk=post.id).update( vote_count=F('vote_count') + change) # Upvote on an Aswer is the trigger for potentian bounty awards if post.type == Post.ANSWER and post.author != get_anon_user( ): award_bounty(question_post=post.parent) checkpoint_helper.set_checkpoint("done", action_type="upvote", action_id=post.id) elif action == "Bounty": valid = True for keyword in ["post_id", "amt"]: if keyword not in action_details: logger.warn( "Bounty invalid because {} is missing".format( keyword)) valid = False if not valid: logger.warn("Could not start Bounty: bounty_invalid") checkpoint_helper.set_checkpoint("bounty_invalid") continue post_id = action_details["post_id"] amt = action_details["amt"] try: post_obj = Post.objects.get(pk=post_id) except (ObjectDoesNotExist, ValueError): logger.error( "Bounty invalid because post {} does not exist". format(post_id)) checkpoint_helper.set_checkpoint( "bounty_invalid_post_does_not_exist") continue logger.info("Starting bounty for post {}!".format(post_id)) new_b = Bounty( post_id=post_obj, amt=amt, activation_time=timezone.now(), ) new_b.save() checkpoint_helper.set_checkpoint("done", action_type="bonty", action_id=post_id) else: logger.error("Invalid action: {}".format(action_details)) checkpoint_helper.set_checkpoint("invalid_action") continue else: # Posts do not include the "action" key to save on memo space logger.info("Action details {}".format(action_details)) if "sig" in action_details: sig = action_details.pop("sig") sig = validators.pre_validate_signature(sig) verifymessage_detail = lnclient.verifymessage( msg=json.dumps(action_details, sort_keys=True), sig=sig, rpcserver=node.rpcserver, mock=settings.MOCK_LN_CLIENT) if not verifymessage_detail["valid"]: checkpoint_helper.set_checkpoint("invalid_signiture") continue pubkey = verifymessage_detail["pubkey"] else: pubkey = "Unknown" if "parent_post_id" in action_details: # Find the parent. try: parent_post_id = int(action_details["parent_post_id"]) parent = Post.objects.get(pk=parent_post_id) except (ObjectDoesNotExist, ValueError): logger.error( "The post parent does not exist: {}".format( action_details)) checkpoint_helper.set_checkpoint("invalid_parent_post") continue title = parent.title tag_val = parent.tag_val else: title = action_details["title"] tag_val = action_details["tag_val"] parent = None user, created = User.objects.get_or_create(pubkey=pubkey) post = Post( author=user, parent=parent, type=action_details["post_type"], title=title, content=action_details["content"], tag_val=tag_val, ) # TODO: Catch failures when post title is duplicate (e.g. another node already saved post) post.save() # New Answer is the trigger for potentian bounty awards if post.type == Post.ANSWER and user != get_anon_user(): award_bounty(question_post=post.parent) # Save tags if "tag_val" in action_details: tags = action_details["tag_val"].split(",") for tag in tags: tag_obj, created = Tag.objects.get_or_create(name=tag) if created: logger.info("Created a new tag: {}".format(tag)) tag_obj.count += 1 post.tag_set.add(tag_obj) tag_obj.save() post.save() checkpoint_helper.set_checkpoint("done", action_type="post", action_id=post.id) # advance global checkpoint new_global_checkpoint = None for add_index in sorted(retry_mini_map.keys()): retry = retry_mini_map[add_index] if retry: break else: logger.info("add_index={} advances global checkpoint".format( add_index)) new_global_checkpoint = add_index if new_global_checkpoint: node.global_checkpoint = new_global_checkpoint node.save() logger.info( "Saved new global checkpoint {}".format(new_global_checkpoint)) processing_wall_time = time.time() - start_time logger.info("Processing node {} took {:.3f} seconds".format( node.node_name, processing_wall_time)) return processing_wall_time
def post(request): """ Get post for index page and create new post """ try: if request.method == 'GET': if request.GET.get('filter-search-by') == "Category": posts = Post.objects.filter(category=request.GET.get( 'filter-category')).order_by('-create_at') elif request.GET.get('filter-search-by') == "Location": posts = Post.objects.filter(location=request.GET.get( 'filter-location')).order_by('-create_at') elif request.GET.get('filter-search-by') == "Status": posts = Post.objects.filter(status=request.GET.get( 'filter-status').upper()).order_by('-create_at') else: posts = Post.objects.all().order_by('-create_at') payload = [{ "id": p.id, "title": p.title, "description": p.descriptions, "status": p.status, "location": p.location.name, "category": [c.name for c in p.category.all()], "create_at": p.create_at, "date": p.date, "user": getUser(p.user.id), "images": getImage(p.id), "comments": getComment(p.id) } for p in posts] categoryAll = Category.objects.all() locationAll = Location.objects.all() return render(request, 'posts/index.html', context={ 'Category': categoryAll, 'Locations': locationAll, 'Posts': payload }) elif request.method == 'POST': try: # Create Post post = Post(title=request.data['title'], descriptions=request.data['descriptions'], status=request.data['status'], date=request.data['date'], user=User.objects.get(pk=request.data['user_id']), location=Location.objects.get( pk=request.data['location_id'])) # Add category to post post.save() for c in request.data['categories_id']: post.category.add(Category.objects.get(pk=c)) post.save() # Create PostImage for i in request.data['images']: image = PostImage(image_url=i, post=post) image.save() return JsonResponse({ "statusCode": 201, "statusText": "Created", "message": "Create Post Successfully", "error": False, }) except KeyError: return JsonResponse({ "statusCode": 400, "statusText": "Bad Request", "message": "Invalid API Payload", "error": True }) except: return JsonResponse({ "statusCode": 500, "statusText": "Internal Server", "message": "Internal Server", "error": True })
def create_new_post(request): # POST to http://service/author/posts # Create a post to the currently authenticated user # First get the information out of the request body size = len(request.body) #body = json.load(body) # body = dict(x.split("=") for x in body.split("&")) #post = body['post'] post = request.POST new_post = Post() # Post ID's are created automatically in the database # new_post.id = post['id'] #: "de305d54-75b4-431b-adb2-eb6b9e546013", #: "A post title about a post about web dev", new_post.title = post['title'] # Source and origin are the same, and depend on the ID so we wait until after the post gets saved to # generate this URLS # new_post.source = post['source'] #: "http://lastplaceigotthisfrom.com/posts/yyyyy" # new_post.origin = post['origin'] #: "http://whereitcamefrom.com/posts/zzzzz" new_post.description = post[ 'description'] # : "This post discusses stuff -- brief", # If the post is an image, the content would have been provided as a file along with the upload if len(request.FILES) > 0: file_type = request.FILES['file'].content_type allowed_file_type_map = { 'image/png': Post.TYPE_PNG, 'image/jpg': Post.TYPE_JPEG } if file_type not in allowed_file_type_map.keys(): return JsonResponse({ 'success': 'false', 'msg': f'You uploaded an image with content type: {file_type}, but only one of {allowed_file_type_map.keys()} is allowed' }) new_post.contentType = allowed_file_type_map[ file_type] # : "text/plain" new_post.content = base64.b64encode( request.FILES['file'].read()).decode('utf-8') else: new_post.contentType = post['contentType'] # : "text/plain", new_post.content = post['content'] #: "stuffs", new_post.author = request.user # the authenticated user # Categories added after new post is saved new_post.count = 0 #: 1023, initially the number of comments is zero new_post.size = size #: 50, the actual size of the post in bytes # This is not a property that gets stored, but rather a link to the comments of this post that should # be generated on the fly. # new_post.next = post['next'] #: "http://service/posts/{post_id}/comments", # We do not permit adding comments at the same time a post is created, so this field is not created # new_post.comments = post['comments'] #: LIST OF COMMENT, current_tz = pytz.timezone('America/Edmonton') timezone.activate(current_tz) #: "2015-03-09T13:07:04+00:00", new_post.published = str(datetime.datetime.now()) new_post.visibility = post['visibility'].upper() #: "PUBLIC", new_post.unlisted = True if 'unlisted' in post and post[ 'unlisted'] == 'true' else False #: true new_post.save() # Now we can set source and origin new_post.source = settings.HOSTNAME + "/posts/" + str(new_post.id.hex) new_post.origin = settings.HOSTNAME + "/posts/" + str(new_post.id.hex) new_post.save() # Take the user uid's passed in and convert them into Authors to set as the visibleTo list uids = post.getlist('visibleTo') visible_authors = Author.objects.filter(uid__in=uids) for author in visible_authors: new_post.visibleTo.add(author) # Categories is commented out because it's not yet in the post data, uncomment once available for category in post['categories'].split('\r\n'): try: # Try connecting to existing categories cat_object = Category.objects.get(name=category) except Category.DoesNotExist as e: cat_object = Category.objects.create( name=category) # Create one if not new_post.categories.add(cat_object) #: LIST, # for key in body.keys(): # print(f'{key}: {body[key]}') if len(request.FILES) > 0: # If they uploaded a file this is an ajax call and we need to return a JSON response return JsonResponse({'success': 'true', 'msg': new_post.id.hex}) else: return redirect("/")
def create(self, request_data): post = Post() return self.update(post, request_data)
from mongoengine import connect from posts.models import Post from flask_mongoengine import MongoEngine db = MongoEngine() ''' class Post(db.Document): title = db.StringField(required=True) tag = db.StringField(max_length=25) text = db.StringField() urls = db.ListField(db.StringField()) posted = db.DateTimeField(default=datetime.datetime.now) def __repr__(self): return f"Post {self.title}" ''' connect(db='testdb', host=MONGO_URI) for post in Post.objects(): print(post.text) ''' Post( title='Engine test', tag='pytest', text='Hello Everyone!', urls= ['https://sun6-14.userapi.com/c855128/v855128189/10f4b2/J977kYyDEag.jpg', 'https://sun9-45.userapi.com/c855128/v855128189/10f478/yH9fX5eBFOA.jpg'], ).save() '''
def setUpTestViewData(cls): create_taptap() number_of_post = 15 for post_num in range(number_of_posts): Post(user=user"%s"%post_num, slug='marshall-edikan-faith%s'%post_num, title='marshaledikanfaith%s'%post_num,content='This is a post for carrying out an assessment%s'%post_num)
def create_post(self): user=MyUser(username='******',password='******',phone_number='07063419292',first_name='akanbi',last_name='bakare',email='*****@*****.**') return Post(user=user, slug='marshall-edikan-faith', title='marshaledikanfaith',content='This is a post for carrying out an assessment')
def perform_create(self, serializer): post = Post(owner=self.request.user, **serializer.validated_data) post.save()
def test_add_post(self): p = Post(title='Test Post', text='This is a test post')
def initialize_calendar(data): post_new_years = Post() post_new_years.author = Account.objects.get(username = data['username']) post_new_years.content = 'New Year\'s Day' post_new_years.start_time = datetime.date(2015, 1, 1) post_new_years.day_of_week = 'Thursday' post_new_years.is_holiday = True post_new_years.save() post_mlk = Post() post_mlk.author = Account.objects.get(username = data['username']) post_mlk.content = 'Martin Luther King Day' post_mlk.start_time = datetime.date(2015, 1, 19) post_mlk.day_of_week = 'Monday' post_mlk.is_holiday = True post_mlk.save() post_groundhog_day = Post() post_groundhog_day.author = Account.objects.get(username = data['username']) post_groundhog_day.content = 'Groundhog Day' post_groundhog_day.start_time = datetime.date(2015, 2, 1) post_groundhog_day.day_of_week = 'Monday' post_groundhog_day.is_holiday = True post_groundhog_day.save() post_rosa_parks = Post() post_rosa_parks.author = Account.objects.get(username = data['username']) post_rosa_parks.content = 'Rosa Parks Day' post_rosa_parks.start_time = datetime.date(2015, 2, 4) post_rosa_parks.day_of_week = 'Wednesday' post_rosa_parks.is_holiday = True post_rosa_parks.save() post_lincolns_bday = Post() post_lincolns_bday.author = Account.objects.get(username = data['username']) post_lincolns_bday.content = 'Lincoln\'s Birthday' post_lincolns_bday.start_time = datetime.date(2015, 2, 12) post_lincolns_bday.day_of_week = 'Thursday' post_lincolns_bday.is_holiday = True post_lincolns_bday.save() post_valentine = Post() post_valentine.author = Account.objects.get(username = data['username']) post_valentine.content = 'Valentine\'s Day' post_valentine.start_time = datetime.date(2015, 2, 14) post_valentine.day_of_week = 'Saturday' post_valentine.is_holiday = True post_valentine.save() post_presidents = Post() post_presidents.author = Account.objects.get(username = data['username']) post_presidents.content = 'President\'s Day' post_presidents.start_time = datetime.date(2015, 2, 16) post_presidents.day_of_week = 'Monday' post_presidents.is_holiday = True post_presidents.save() post_ash = Post() post_ash.author = Account.objects.get(username = data['username']) post_ash.content = 'Ash Wednesday Day' post_ash.start_time = datetime.date(2015, 2, 18) post_ash.day_of_week = 'Wednesday' post_ash.is_holiday = True post_ash.save() post_chinese = Post() post_chinese.author = Account.objects.get(username = data['username']) post_chinese.content = 'Chinese New Year' post_chinese.start_time = datetime.date(2015, 2, 19) post_chinese.day_of_week = 'Thursday' post_chinese.is_holiday = True post_chinese.save() post_texas = Post() post_texas.author = Account.objects.get(username = data['username']) post_texas.content = 'Texas Independence Day' post_texas.start_time = datetime.date(2015, 3, 2) post_texas.day_of_week = 'Monday' post_texas.is_holiday = True post_texas.save() post_employee = Post() post_employee.author = Account.objects.get(username = data['username']) post_employee.content = 'Employee Appreciation Day' post_employee.start_time = datetime.date(2015, 3, 6) post_employee.day_of_week = 'Friday' post_employee.is_holiday = True post_employee.save() post_daylight = Post() post_daylight.author = Account.objects.get(username = data['username']) post_daylight.content = 'Daylight Saving\'s Time' post_daylight.start_time = datetime.date(2015, 3, 6) post_daylight.day_of_week = 'Friday' post_daylight.is_holiday = True post_daylight.save() post_patrick = Post() post_patrick.author = Account.objects.get(username = data['username']) post_patrick.content = 'St. Patrick\'s Day' post_patrick.start_time = datetime.date(2015, 3, 17) post_patrick.day_of_week = 'Tuesday' post_patrick.is_holiday = True post_patrick.save() post_spring = Post() post_spring.author = Account.objects.get(username = data['username']) post_spring.content = 'Spring Solstice' post_spring.start_time = datetime.date(2015, 3, 20) post_spring.day_of_week = 'Friday' post_spring.is_holiday = True post_spring.save() post_friday = Post() post_friday.author = Account.objects.get(username = data['username']) post_friday.content = 'Good Friday' post_friday.start_time = datetime.date(2015, 4, 3) post_friday.day_of_week = 'Friday' post_friday.is_holiday = True post_friday.save() post_passover = Post() post_passover.author = Account.objects.get(username = data['username']) post_passover.content = 'Passover' post_passover.start_time = datetime.date(2015, 4, 4) post_passover.day_of_week = 'Saturday' post_passover.is_holiday = True post_passover.save() post_easter = Post() post_easter.author = Account.objects.get(username = data['username']) post_easter.content = 'Easter Sunday' post_easter.start_time = datetime.date(2015, 4, 5) post_easter.day_of_week = 'Sunday' post_easter.is_holiday = True post_easter.save() post_tax = Post() post_tax.author = Account.objects.get(username = data['username']) post_tax.content = 'Tax Day' post_tax.start_time = datetime.date(2015, 4, 15) post_tax.day_of_week = 'Wednesday' post_tax.is_holiday = True post_tax.save() post_cinco = Post() post_cinco.author = Account.objects.get(username = data['username']) post_cinco.content = 'Cinco de Mayo' post_cinco.start_time = datetime.date(2015, 5, 5) post_cinco.day_of_week = 'Tuesday' post_cinco.is_holiday = True post_cinco.save() post_mother = Post() post_mother.author = Account.objects.get(username = data['username']) post_mother.content = 'Mother\'s Day' post_mother.start_time = datetime.date(2015, 5, 15) post_mother.day_of_week = 'Sunday' post_mother.is_holiday = True post_mother.save() post_armed = Post() post_armed.author = Account.objects.get(username = data['username']) post_armed.content = 'Armed Forces Day' post_armed.start_time = datetime.date(2015, 5, 16) post_armed.day_of_week = 'Saturday' post_armed.is_holiday = True post_armed.save() post_memorial = Post() post_memorial.author = Account.objects.get(username = data['username']) post_memorial.content = 'Memorial Day' post_memorial.start_time = datetime.date(2015, 5, 25) post_memorial.day_of_week = 'Monday' post_memorial.is_holiday = True post_memorial.save() post_dday = Post() post_dday.author = Account.objects.get(username = data['username']) post_dday.content = 'D-Day Day' post_dday.start_time = datetime.date(2015, 6, 6) post_dday.day_of_week = 'Saturday' post_dday.is_holiday = True post_dday.save() post_flag = Post() post_flag.author = Account.objects.get(username = data['username']) post_flag.content = 'Flag Day' post_flag.start_time = datetime.date(2015, 6, 14) post_flag.day_of_week = 'Sunday' post_flag.is_holiday = True post_flag.save() post_summer = Post() post_summer.author = Account.objects.get(username = data['username']) post_summer.content = 'Summer Starts' post_summer.start_time = datetime.date(2015, 6, 21) post_summer.day_of_week = 'Sunday' post_summer.is_holiday = True post_summer.save() post_father = Post() post_father.author = Account.objects.get(username = data['username']) post_father.content = 'Father\'s Day' post_father.start_time = datetime.date(2015, 6, 21) post_father.day_of_week = 'Sunday' post_father.is_holiday = True post_father.save() post_independence = Post() post_independence.author = Account.objects.get(username = data['username']) post_independence.content = 'Independence Day' post_independence.start_time = datetime.date(2015, 7, 4) post_independence.day_of_week = 'Saturday' post_independence.is_holiday = True post_independence.save() post_labor = Post() post_labor.author = Account.objects.get(username = data['username']) post_labor.content = 'Labor Day' post_labor.start_time = datetime.date(2015, 9, 7) post_labor.day_of_week = 'Monday' post_labor.is_holiday = True post_labor.save() post_patriot = Post() post_patriot.author = Account.objects.get(username = data['username']) post_patriot.content = 'Patriot Day' post_patriot.start_time = datetime.date(2015, 9, 11) post_patriot.day_of_week = 'Friday' post_patriot.is_holiday = True post_patriot.save() post_constitution = Post() post_constitution.author = Account.objects.get(username = data['username']) post_constitution.content = 'Constitution Day' post_constitution.start_time = datetime.date(2015, 9, 17) post_constitution.day_of_week = 'Thursday' post_constitution.is_holiday = True post_constitution.save() post_fall = Post() post_fall.author = Account.objects.get(username = data['username']) post_fall.content = 'Autumnal Equinox' post_fall.start_time = datetime.date(2015, 9, 23) post_fall.day_of_week = 'Wednesday' post_fall.is_holiday = True post_fall.save() post_columbus = Post() post_columbus.author = Account.objects.get(username = data['username']) post_columbus.content = 'Columbus Day' post_columbus.start_time = datetime.date(2015, 10, 12) post_columbus.day_of_week = 'Monday' post_columbus.is_holiday = True post_columbus.save() post_halloween = Post() post_halloween.author = Account.objects.get(username = data['username']) post_halloween.content = 'Halloween' post_halloween.start_time = datetime.date(2015, 10, 31) post_halloween.day_of_week = 'Saturday' post_halloween.is_holiday = True post_halloween.save() post_light = Post() post_light.author = Account.objects.get(username = data['username']) post_light.content = 'Daylight Saving Time Ends' post_light.start_time = datetime.date(2015, 11, 1) post_light.day_of_week = 'Sunday' post_light.is_holiday = True post_light.save() post_election = Post() post_election.author = Account.objects.get(username = data['username']) post_election.content = 'Election Day' post_election.start_time = datetime.date(2015, 11, 3) post_election.day_of_week = 'Tuesday' post_election.is_holiday = True post_election.save() post_thanksgiving = Post() post_thanksgiving.author = Account.objects.get(username = data['username']) post_thanksgiving.content = 'Thanksgiving' post_thanksgiving.start_time = datetime.date(2015, 11, 26) post_thanksgiving.day_of_week = 'Tuesday' post_thanksgiving.is_holiday = True post_thanksgiving.save() post_presidents = Post() post_presidents.author = Account.objects.get(username = data['username']) post_presidents.content = 'President\'s Day' post_presidents.start_time = datetime.date(2015, 11, 27) post_presidents.day_of_week = 'Friday' post_presidents.is_holiday = True post_presidents.save() post_black = Post() post_black.author = Account.objects.get(username = data['username']) post_black.content = 'Black Friday' post_black.start_time = datetime.date(2015, 11, 27) post_black.day_of_week = 'Friday' post_black.is_holiday = True post_black.save() post_monday = Post() post_monday.author = Account.objects.get(username = data['username']) post_monday.content = 'Cyber Monday' post_monday.start_time = datetime.date(2015, 11, 30) post_monday.day_of_week = 'Monday' post_monday.is_holiday = True post_monday.save() post_han = Post() post_han.author = Account.objects.get(username = data['username']) post_han.content = 'Hanukkah' post_han.start_time = datetime.date(2015, 12, 7) post_han.day_of_week = 'Monday' post_han.is_holiday = True post_han.save() post_pearl = Post() post_pearl.author = Account.objects.get(username = data['username']) post_pearl.content = 'Pearl Harbor Remembrance Day' post_pearl.start_time = datetime.date(2015, 12, 7) post_pearl.day_of_week = 'Monday' post_pearl.is_holiday = True post_pearl.save() post_winter = Post() post_winter.author = Account.objects.get(username = data['username']) post_winter.content = 'Winter Solstice' post_winter.start_time = datetime.date(2015, 12, 22) post_winter.day_of_week = 'Tuesday' post_winter.is_holiday = True post_winter.save() post_xmas_eve = Post() post_xmas_eve.author = Account.objects.get(username = data['username']) post_xmas_eve.content = 'Christmas Eve' post_xmas_eve.start_time = datetime.date(2015, 12, 24) post_xmas_eve.day_of_week = 'Thursday' post_xmas_eve.is_holiday = True post_xmas_eve.save() post_xmas = Post() post_xmas.author = Account.objects.get(username = data['username']) post_xmas.content = 'Christmas Day' post_xmas.start_time = datetime.date(2015, 12, 25) post_xmas.day_of_week = 'Friday' post_xmas.is_holiday = True post_xmas.save() post_nye = Post() post_nye.author = Account.objects.get(username = data['username']) post_nye.content = 'New Year\'s Eve' post_nye.start_time = datetime.date(2015, 12, 31) post_nye.day_of_week = 'Thursday' post_nye.is_holiday = True post_nye.save()