def test_about_page_resolves_to_correct_view(self): found = resolve('/about-this-site/') self.assertEqual(found.func, about) about_test = Post() about_test.title = 'About this site' about_test.slug = 'about-this-site' about_test.body = 'This is the body.' about_test.status = 'p' about_test.save() saved_items = Post.objects.all() self.assertEqual(saved_items.count(), 1) about_saved_item = saved_items[0] self.assertEqual(about_saved_item.title, 'About this site') request = HttpRequest() response = about(request) url = reverse('about') response = self.client.get(url) self.assertEqual(response.status_code, 200) html = response.content.decode('utf8') self.assertIn('<html lang="en">', html) self.assertIn('<title>H2100</title>', html) self.assertIn('favicon-32x32.png', html) self.assertIn('</html>', html) self.assertIn('<h1>About this site</h1>', html) self.assertTrue(html.strip().endswith('</html>')) self.assertTemplateUsed(response, 'about.html')
def test_create_post(self): label = Label() label.name = 'python' label.save() post = Post() post.title = 'Test post' post.save() post.abstract = 'Test Abstract' post.body = 'Post Body' post.slug = 'test-post' post.label = [1] post.publish = True post.created = timezone.now() post.modified = timezone.now() post.numofseen = 0 post.save() all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1) only_post = all_posts[0] self.assertEquals(only_post, post) self.assertEquals(only_post.title, 'Test post') self.assertEquals(only_post.abstract, 'Test Abstract') self.assertEquals(only_post.body, post.body) self.assertEquals(only_post.slug, post.slug) self.assertEquals(only_post.label.get(), post.label.get()) self.assertEquals(only_post.created.day, post.created.day) self.assertEquals(only_post.created.month, post.created.month) self.assertEquals(only_post.created.year, post.created.year) self.assertEquals(only_post.created.hour, post.created.hour) self.assertEquals(only_post.created.minute, post.created.minute) self.assertEquals(only_post.created.second, post.created.second) self.assertEquals(only_post.modified, post.modified) self.assertEquals(only_post.numofseen, 0)
def post(self, request, format=None): serializer = PublishSerializer(data=request.data) if not serializer.is_valid(): print(serializer.errors) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) category = serializer.data.get('category') category = Category.objects.get(pk=category) if category is None: return Response(status=status.HTTP_400_BAD_REQUEST) tags = serializer.data.get('tags') with transaction.atomic(): post = Post() post.title = serializer.data.get('title') post.body = serializer.data.get('body') post.category = category post.author = request.user post.save() for tag in tags: tag = Tag.objects.get(pk=tag) post.tags.add(tag) return Response(status=status.HTTP_201_CREATED)
def test_delete_post(self): label = Label() label.name = 'python' label.save() post = Post() post.title = 'Test post' post.save() post.abstract = 'Test Abstract' post.body = 'Post Body' post.slug = 'test-post' post.label = [1] post.publish = True post.created = timezone.now() post.modified = timezone.now() post.numofseen = 0 post.save() all_posts = Post.objects.all() self.assertEquals(len(all_posts),1) self.client.login(username = '******', password = '******') response = self.client.post('/admin/blog/post/'+str(post.pk)+'/delete/',{ 'post':'yes'}, follow = True) self.assertEquals(response.status_code,200) self.assertTrue(str.encode('deleted successfully') in response.content) all_posts = Post.objects.all() self.assertEquals(len(all_posts),0)
def handle(self, **options): feed = feedparser.parse( 'https://www.headphonezone.in/sitemap_products_1.xml?from=373372541&to=1398753460287' ) for post in Post.objects.all(): post.delete() loop_max = len(feed['entries']) category = Category.objects.get( id="ce867a33-fddf-4e60-89ec-179c9792889d") author = User.objects.get(pk=1) for i in range(0, loop_max): if feed['entries'][i]: blog_post = Post() blog_post.title = feed['entries'][i].title blog_post.slug = slugify(feed['entries'][i].title) link = self.parse_url(feed['entries'][i].link) blog_post.external_url = link blog_post.category = category blog_post.sender = "indiafashionblogger" blog_post.author = author blog_post.short_description = feed['entries'][i].description blog_post.body = self.get_content(link) blog_post.created = datetime.fromtimestamp( mktime(feed['entries'][i].published_parsed)) print(blog_post.short_description) blog_post.save()
def test_creating_a_new_post(self): """ Testing the Posts creation in Blog application_ """ post=Post() post.body='Test post' post.created=timezone.now() # now i'm gonna check if i can save this post post.save() # check if post is in database all_posts_in_database=Post.objects.all() self.assertEquals(len(all_posts_in_database), 1) only_post_in_database=all_posts_in_database[0] self.assertEquals(only_post_in_database, post) #check the data in post self.assertEquals(only_post_in_database.body, 'Test post') self.assertEquals(only_post_in_database.created.date(), post.created.date()) self.browser.get(self.live_server_url + '/blog/') # She sees the familiar 'Django administration' heading body = self.browser.find_element_by_tag_name('body') self.assertIn('Blog', body.text)
def test_index(self): label = Label() label.name = 'python' label.save() post = Post() post.title = 'Test post' post.save() post.abstract = 'Test Abstract' post.body = 'Post Body' post.slug = 'test-post' post.label = str(label.pk) post.publish = True post.created = timezone.now() post.modified = timezone.now() post.numofseen = 0 post.publish = True post.save() all_posts = Post.objects.all() self.assertEquals(len(all_posts),1) year = str(post.created.year) month = post.created.strftime('%b') day = str(post.created.day) response = self.client.get('/') self.assertEquals(response.status_code,200) self.assertTrue(str.encode(post.title) in response.content) self.assertTrue(str.encode(post.abstract) in response.content) self.assertTrue(str.encode(post.label.get().name) in response.content) self.assertTrue(str.encode(year) in response.content) self.assertTrue(str.encode(month) in response.content) self.assertTrue(str.encode(day) in response.content)
def process(self): self.log("Starting to process key: " + self.key) data = self._getData() post = self._getExistingPost() if not post: self.log("Post has not been seen before, creating new one.") post = Post() post.date_published = self._getPublishedDate() post.key = ndb.Key("Post", self.subkey) post.slug = data.get('slug', self.slug) post.published = True else: self.log("Post has been seen before, updating existing one.") # As a precaution, if the post has a status that is draft, ignore it. if data.get('status'): if data['status'] == "draft": self.log("Caught post in Draft mode, ending processing.") return post.title = data['title'] post.body = self._renderBody(data.content) post.frontmatter = data.to_dict() post.put() return post.body
def dashboard_view(request): if 'u_id' not in request.session: messages.error(request, "You must be logged in!") return HttpResponseRedirect('login') else: username = request.session['u_id'] if request.method == 'POST': title = request.POST['ptitle'] body = request.POST['pbody'] dt = str(datetime.datetime.now()) print(dt) post = Post() post.user_name = User.objects.get(user_name=username) post.title = title post.body = body post.date = dt post.save() return HttpResponseRedirect('/blog') else: return render(request, 'userprofile/userdashboard.html', {"username": username})
def addPost(self, item): #print(item_type, item_title) title = item.find("title").text # Nouveau Blog! link = item.find("link").text # http://mart-e.be/?p=68 ou http://mart-e.be/post/nouveau-blog post_id = item.find("{http://wordpress.org/export/1.2/}post_id").text # 68 pub_date = item.find("pubDate").text # Fri, 05 Feb 2010 11:14:00 +0000 author = item.find("{http://purl.org/dc/elements/1.1/}creator").text # mart content = item.find("{http://purl.org/rss/1.0/modules/content/}encoded").text # the whole article slug = item.find("{http://wordpress.org/export/1.2/}post_name").text # nouveau-blog (CAN BE EMPTY) allow_comments = item.find("{http://wordpress.org/export/1.2/}comment_status").text # open status = item.find("{http://wordpress.org/export/1.2/}status").text # publish publish = item.find("{http://wordpress.org/export/1.2/}post_date").text # 2010-01-05 15:09:00 if slug: posts = Post.objects.filter(slug=slug) else: posts = Post.objects.filter(id=int(post_id)) if len(posts) != 0: print("Skipping {0}".format(posts[0].slug)) return posts[0] try: print("Creating post '"+title+"'") except: print("Creating post #"+post_id) #print("Creating post '{0}'".format(title.decode('utf-8'))) post = Post() post.title = title post.id = post_id if slug: post.slug = slug[:50] else: post.slug = slugify(title)[:50] if author != self.author_name: raise Exception("Unknown author {0}".format(author)) post.author = self.author post.body = content #post.body_html = markdown(parser.inlines(content), output_format="html5") # in wordpress don't use markdown post.body_html = post.body if status == "publish": post.status = 2 else: post.status = 1 if allow_comments == "open": post.allow_comments = True else: post.allow_comments = False post.publish = datetime.strptime(publish,"%Y-%m-%d %H:%M:%S").replace(tzinfo=utc) post.created = post.publish # really, who cares about that post.modifier = post.publish # still don't care post.save() self.addComments(item, post) self.addTags(item, post) return post
def add_post(request): post = Post() num = random.randrange(100) post.title = "第%s文章" % num post.body = "body of %s" % num post.save() return HttpResponse("Hello Django!")
def gen_post(request): for i in range(20): num = random.randrange(100, 999) post = Post() post.title = "post%s" % str(num) post.body = "body of post%s" % str(num) post.save() return HttpResponse("数据生成成功!")
def test_body_of_post_is_truncated(self): post = Post(title=u"Long post") post.body = "ABC " * 123 post.put() expected_body = ( "ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC " "ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC " "ABC ABC A..." ) response = self.client.get(self.url) self.assertContains(response, expected_body)
def test_basic_post_data(self): post = Post() post.title = u"Some interesting post" post.body = "ABC" * 1000 post.author = "Owner of blog" post.put() response = self.client.get(post.url) self.assertContains(response, post.title) self.assertContains(response, post.body) self.assertContains(response, "Written by Owner of blog")
def test_add_post(): ''' 如何测试数据是否添加成功, 那么首先必须创建数据对象,并增加后,如果不报错,那么数据添加成功. ''' #创建添加7ge对象,数据库中应当有6条 p1 = Post(title="面向对象四大特征", body="面向对象的定义,作用...", summary="面向对象的抽象,继承,封装,多态", author="玄锷无梦", create_time="2018-7-3 7:12:38", modify_time="2018-7-3 7:12:38") p1.save() p2 = Post(title="GIL", summary="GIL全局锁,仅仅存在于Cpython编辑器,和python语言没有关系", body="GIL的存在历史原因,解决办法...", author="玄锷无梦", create_time="2018-6-10 7:22:22", modify_time="2018-7-22 18:18:22") p2.save() p3 = Post.objects.create(title="Linux笔记", summary="这里仅仅收录了常用的linux命令", body="多多使用几次就熟练了...", author="玄锷无梦", create_time="2018-8-8 18:00:00", modify_time="2019-02-03 16:22:00") p4 = Post.objects.create(title="元类", summary="元类就是创建类对象的类", author="玄锷无梦", body="python中一切皆对象....", create_time="2018-8-8 19:22:33", modify_time="2018-12-13 00:00:00") p5 = Post(title="感恩新时代") p5.summary = "进入新时代,应当以历史的角度,看待这一历史巨变" p5.body = "新时代,新历史,新征程..." p5.author = "玄锷无梦" p5.create_time = "2017-12-12 00:00:00" p5.modify_time = "2017-12-12 00:00:00" p6 = Post.objects.get_or_create(title="面向对象四大特征", summary="面向对象的抽象,继承,封装,多态", body="面向对象的思想.....", author="玄锷无梦", create_time="2018-7-3 7:12:38", modify_time="2018-7-3 7:12:38") P7 = Post.objects.get_or_create(title="ORM对象映射数据库", summary="将对象与数据库关联起来,无需直接操作数据库", body="ORM的定义,原因,使用场景.....", author="玄锷无梦", create_tiem="2018-8-8 00:00:00", modify_time="2019-09-09 12:22:33") #计算数据库中的数据数量,判断是否正确 self.assertEqual(Post.objects.all().count(), 6)
def code_create(request): if request.method == 'POST': code = Code() post = Post() try: path = "upload/" file = request.FILES['file'] if not os.path.exists(path): os.makedirs(path) list = GetFileList(path,file.name) version ='1' if len(list)>0: version = str(len(list)+1) file_name = path +request.session['username']+'-'+request.POST['category']+'-'+version+'-'+file.name else: file_name = path +request.session['username']+'-'+request.POST['category']+'-1-'+file.name destination = open(file_name, 'wb+') for chunk in file.chunks(): destination.write(chunk) destination.close() with open(file_name, 'r') as filer: code.wenku = filer.read() code.title = request.POST['title'] code.version = version code.intro = request.POST['body'] code.status = '0' code.path = path+file.name code.size = str(file.size/1000).split('.')[0]+'K' tlist = file.name.split('.') code.type = tlist[len(tlist)-1] code.author = User.objects.get_by_natural_key(request.session['username']) code.category_id = request.POST['category'] code.save() with open(file_name, 'r') as filer: post.body = filer.read() post.title = request.POST['title'] post.author = User.objects.get_by_natural_key(request.session['username']) post.category_id = request.POST['category'] post.save() request.session['codeid'] = code.id return HttpResponseRedirect(reverse('codemg:code_post_list')) except Exception as e: print(e) return HttpResponse(json.dumps({ "status": "fail", }), content_type="application/json") return render(request, "codemg/create.html", { 'username':request.session['username'] })
def setUp(self): user = User.objects.create_user('user', '*****@*****.**', 'user') user.save() post = Post() post.pub_date = datetime.datetime(int(self.date['year']), int(self.date['month']), int(self.date['day'])) post.headline = 'h' post.summary = 's' post.body = 'b' post.author_id = user.id post.save()
def setUp(self): user = User.objects.create_user('user', '*****@*****.**', 'user') user.save() post = Post() post.pub_date = datetime.datetime( int(self.date['year']), int(self.date['month']), int(self.date['day']) ) post.headline = 'h' post.summary = 's' post.body = 'b' post.author_id = user.id post.save()
def new(request): """View to make a new blog post. @param request: request data @type request: Django request @return a view page to make a new blog post @rtype: Django response """ if not request.user.is_authenticated(): redirect_to = reverse('user_signin') + '?next=' + reverse(new) return HttpResponseRedirect(redirect_to) if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): if request.POST.has_key('preview'): preview = { 'headline': form.cleaned_data['headline'], 'summary': form.cleaned_data['summary'], 'body': form.cleaned_data['body'], } else: post = Post() post.pub_date = datetime.datetime.now() post.headline = form.cleaned_data['headline'] post.summary = form.cleaned_data['summary'] post.body = form.cleaned_data['body'] post.author_id = request.user.id post.save() return HttpResponseRedirect(post.get_absolute_url()) else: preview = False form = PostForm() info_dict = { 'request': request, 'form': form, 'preview': preview, 'section': 'blog', 'user': request.user, } return render_to_response('blog/new.html', info_dict)
def post(self, req, *args, **kwargs): ubody = req.body.decode('utf-8') params = json.loads(ubody) _id = params.get('id') if _id: item = Post.objects.get(id=_id) else: item = Post() item.title = params.get('title') item.body = params.get('body') author_id = params.get('author_id') try: item.author = settings.AUTH_USER_MODEL.objects.get(id=author_id) except: item.author = None item.created = params.get('created') item.updated = params.get('updated') item.save() return JsonResponse({'data': to_json(item)})
def create_post(data): draft_id = data.get('id') try: post = Post.objects.get(draft_id=draft_id) except Post.DoesNotExist: post = Post(draft_id=draft_id) title = data.get('name') body = data.get('content') author = User.objects.get(username='******') post.title = title post.slug = slugify(title.decode()) post.body = body post.tease = body[:200] + '...' post.author = author post.save() return post
def test_detail(self): label = Label() label.name = 'python' label.save() post = Post() post.title = 'Test post' post.save() post.abstract = 'Test Abstract' post.body = 'Post Body' post.slug = 'test-post' post.label = str(label.pk) post.publish = True post.created = timezone.now() post.modified = timezone.now() post.numofseen = 0 post.publish = True post.save() all_posts = Post.objects.all() self.assertEquals(len(all_posts),1) response=self.client.get('/'+str(post.slug)) self.assertEquals(response.status_code,200) self.assertTrue(str.encode(post.body) in response.content)
def test_edit_post(self): label = Label() label.name = 'python' label.save() post = Post() post.title = 'Test post' post.save() post.abstract = 'Test Abstract' post.body = 'Post Body' post.slug = 'test-post' post.label = [1] post.publish = True post.created = timezone.now() post.modified = timezone.now() post.numofseen = 0 post.save() self.client.login(username = '******', password = '******') response = self.client.post('/admin/blog/post/'+str(post.pk)+'/', { 'title':'second test post', 'abstract':'second test abstract', 'body':'second test body', 'label':str(label.pk), 'slug':'second-test-post', 'numofseen':str(0) }, follow = True ) self.assertEquals(response.status_code,200) self.assertTrue(str.encode('changed successfully') in response.content) all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1) only_post = all_posts[0] self.assertEquals(only_post.title, 'second test post') self.assertEquals(only_post.body, 'second test body')
def new(request): """View to make a new blog post. @param request: request data @type request: Django request @return a view page to make a new blog post @rtype: Django response """ if not request.user.is_authenticated(): redirect_to = reverse("user_signin") + "?next=" + reverse(new) return HttpResponseRedirect(redirect_to) if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): if request.POST.has_key("preview"): preview = { "headline": form.cleaned_data["headline"], "summary": form.cleaned_data["summary"], "body": form.cleaned_data["body"], } else: post = Post() post.pub_date = datetime.datetime.now() post.headline = form.cleaned_data["headline"] post.summary = form.cleaned_data["summary"] post.body = form.cleaned_data["body"] post.author_id = request.user.id post.save() return HttpResponseRedirect(post.get_absolute_url()) else: preview = False form = PostForm() info_dict = {"request": request, "form": form, "preview": preview, "section": "blog", "user": request.user} return render_to_response("blog/new.html", info_dict)
def dashboard_view(request): if 'u_id' not in request.session: messages.error(request, "You must be logged in!") return HttpResponseRedirect('login') else: username = request.session['u_id'] if request.method == 'POST': title = request.POST['ptitle'] body = request.POST['pbody'] dt = str(datetime.datetime.now()) print(dt) post = Post() post.user_name = User.objects.get(user_name=username) post.title = title post.body = body post.date = dt post.save() return HttpResponseRedirect('/blog') else: return render(request, 'userprofile/userdashboard.html', {"username": username})
def test_create_post(id, title, body): post = Post() post.id = id post.title = title post.body = body