def comments(): if request.method == "GET": msg = dbHandler.comment(request.args["blog_id"]) else: print "form : ", request.form["blog_id"] msg = dbHandler.comment(request.form["blog_id"]) return render_template('comment_div.html', user=msg)
def dele(id): type = request.form.get('type', 2, type=int) pid = request.form.get('pid', -1, type=int) if session.get('log') and pid == id: if type == 0: Article(pid).delArti() else: comment(pid).delete() return jsonify(type=type, pid=pid)
def addComment(): user_com = users.query.filter(users.id == session['user']['id']).first() post_com = posts.query.filter(posts.id == request.form['post_id']).first() comm = comment(text=request.form['text'], user_com=user_com, post_com=post_com) db.session.add(comm) db.session.commit() return redirect( url_for('links_blog.singlePage', id=request.form['post_id']))
def post(self, request, pk): newCom = comForm(request.POST) if newCom.is_valid(): newUser = newCom.cleaned_data["user_com"] newBody = newCom.cleaned_data["body_com"] newArticle_id = pk newcomment = comment(user_com=newUser, body_com=newBody, article_id=newArticle_id) newcomment.save() print '评论总数', comment.objects.count() return HttpResponseRedirect(reverse("djSeccess", args=[pk]))
def article(bg_id): info = tagInfo() if request.method == 'POST' and request.form['comment']: newCom = comment(bg_id) newCom.insert(request.form['comment'], request.form['author'], request.form['reply']) return redirect(url_for('article', bg_id=bg_id)) try: curArti = Article(bg_id) curArti.getArti() except: return render_template('error.html'), 404 return render_template('article.html', curArti=curArti, id=bg_id, info=info)
def post_detail(request, id, showComments=False): post_det=post.objects.filter(pk=id) for h in post_det: wanted_post=h if request.method == 'POST': the_comment= comment(post=wanted_post) the_comment.name= request.user form=commentForm(request.POST,instance=the_comment) if form.is_valid (): form.save() return HttpResponseRedirect(request.path) else: form=commentForm() comments = comment.objects.filter(post = id) t = loader.get_template('blog/post_detail.html') c = Context ({ 'post' :wanted_post, 'comments' : comments, 'form':form,'user':request.user}) return HttpResponse(t.render(c))
def submitComment(request): if request.user.is_authenticated(): user = request.user content = request.POST.get('content', '') if content == '': return HttpResponse('comment can not be empty') Tid = request.POST.get('Tid', '') if Tid == '': raise Http404 try: Thread = thread.objects.get(id=Tid) except thread.DoesNotExist: return HttpResponse('thread not found') Comment = comment(content=content, time=datetime.datetime.now(), likeCount=0) Comment.author = user Comment.belongTo = Thread Comment.save() return HttpResponse('ok') else: return HttpResponse('please login')
def post(self): #first, collect data to be placed into the comment entity commentText = self.request.get("comment_text") uniqueSloganID = self.request.get("slogan_id") userRows = models.user.gql('') currentUser = users.get_current_user().user_id() userNickname = "" commentAuthorID = 0 for uRow in userRows: if uRow.uniqueGivenID == currentUser: userNickname = uRow.nickname commentAuthorID = uRow.key.id() uRow.slogarma += commentPoints #add slogarama points for the commenter uRow.put() #increment "numComments" for the slogan. sloganRows = models.slogan.gql('') for sRow in sloganRows: if sRow.key.id() == int(uniqueSloganID): sRow.numComments += 1 sRow.globalRank += commentPoints sRow.put() #create a new comment entity. c = models.comment(uniqueAuthorID = commentAuthorID, uniqueSloganID = int(uniqueSloganID), userNickname = userNickname, text = commentText) c.put() #add slogarama points for the commentee theSlogan = models.slogan.get_by_id(int(uniqueSloganID)) sloganAuthor = models.user.get_by_id(theSlogan.uniqueAuthorID) if sloganAuthor.key.id() != commentAuthorID: sloganAuthor.slogarma += commentPoints sloganAuthor.put() time.sleep(.2) #This helps keep the eventual consistency at bay self.redirect("/app/slogan/" + uniqueSloganID + "/comments")
def post_detail(request, id, showComments=False): posts = post.objects.get(pk = id)##similar to select from ...where id=... ##remember rel_type from models?it connects a ##post to its comments and we can retrieve ##them this way ''' html = '<h3>'+str(result) + '</h3><br/>' + str(result.body)+'<br/><h5>COMMENTS</ h5><br/>' comm='' for i in result.comments.all(): print 'haha' comm+=i.body + '<br/>' ''' ##previously if request.method == 'POST': comm = comment(post = posts) form = CommentForm(request.POST, instance=comm) if form.is_valid(): form.save() return HttpResponseRedirect(request.path) else: form = CommentForm() comments = posts.comments.all() #my_context = Context({'posts':posts, 'comment' : comments, 'form':form}) return render_to_response('blog/post_detail.html', {'posts':posts, 'comments' : comments, 'form':form})
def paraFetch(request): commentStatus = False if 'say' in request.POST and 'idkey' in request.POST: say = request.POST['say'] idkey = request.POST['idkey'] if say and idkey: idobj = paper.objects.get(id=idkey) commentobj = comment(paper=idobj,body=say) commentobj.save() commentStatus = True article = paper.objects.get(id=idkey) return render_to_response('page.html',locals()) else: return render_to_response('error.html',locals()) elif 'p' in request.GET: pagekey = request.GET['p'] paper_list = paper.objects.order_by("-score").all() paginator = Paginator(paper_list, 8) try: page = int(pagekey) except ValueError: page = 1 try: p = paginator.page(page) except (EmptyPage, InvalidPage): p = paginator.page(paginator.num_pages) page_range = paginator.page_range[int(page)-5:int(page)+5] return render_to_response('index.html',locals()) else: paper_list = paper.objects.order_by("-score").all() paginator = Paginator(paper_list, 8) page = 1 try: p = paginator.page(page) except (EmptyPage, InvalidPage): p = paginator.page(paginator.num_pages) page_range = paginator.page_range[int(page)-5:int(page)+5] return render_to_response('index.html',locals())
async def get_comments(id, comments): ''' 评论 ''' page_count = int(comments / 10) + 1 cookie = 'MLOGIN=1; M_WEIBOCN_PARAMS=featurecode%%3D20000320%%26oid%%3D%s%%26luicode%%3D10000011%%26lfid%%3D1076031791709041%%26uicode%%3D20000061%%26fid%%3D%s; WEIBOCN_FROM=1110006030; SSOLoginState=1525931210; SUB=_2A25396yaDeRhGeRN71cU9CjEwjuIHXVVGzTSrDV6PUJbkdANLWfukW1NU47RslnWkS5f5K-NHkB62C58p0Bnegav; SUHB=0WGtKITH-S-Yul; H5_INDEX=2; H5_INDEX_TITLE=Bililiooo; SCF=AjOJzMUpKNRc4sqxMp__70x4DbSoPaPY9rwsACWlPzjkN4ptz3fa8ri-Qsj0eeM1HCtWlvpVIl0_MpYHtdRRYJs.; _T_WM=bd324ce74a01f146dfcc272ebbbc5f45' % ( id, id) referer = 'https://m.weibo.cn/status/%s' % id logging.info('当前微博:%s', referer) headers = { 'Host': 'm.weibo.cn', 'Accept': 'application/json, text/plain, */*', 'Connection': 'keep-alive', 'Accept-Language': 'zh-cn', 'Accept-Encoding': 'br, gzip, deflate', 'Cookie': cookie, 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.1 Safari/605.1.15', 'Referer': referer, 'X-Requested-With': 'XMLHttpRequest', } items = [] for page in range(1, page_count): # 只采前3页 if page > 3: return await asyncio.sleep(10) url = 'https://m.weibo.cn/api/comments/show?id=%s&page=%s' % (id, page) logging.info('当前评论页:%s' % url) response = requests.get(url, headers=headers) data = response.json().get('data', None) if data == None: continue if data.get('data', None) != None: for item in data.get('data'): if item.get('pic'): items.append(item) if data.get('hot_data', None) != None: for hot_item in data.get('hot_data'): if hot_item.get('pic'): items.append(hot_item) if len(items) == 0: logging.info('------------没有图片评论') else: logging.info('------------图片评论有%d条' % len(items)) for item in items: id = item.get('id') r_uid = item.get('user').get('id') name = item.get('user').get('screen_name') pic = item['pic']['url'] text = item.get('text') try: text = re.sub(r'</?\w+[^>]*>', '', text) t = datetime.datetime.now() model = models.comment(id=id, name=name, pic=pic, text=text, r_uid=r_uid, time=t) logging.info(model) await model.save() except Exception as error: logging.info('<<<<<<<<<<<<<<< error:%s' % error)
def POST(self): #User wishes to post a comment or image data = web.input() name = data.name try: raw_image_data = data.image_data except ValueError: #No image data... print("No image data in request!") raise web.SeeOther(".") return #get the client IP address if settings.USE_FORWARDED_HEADER: ip_address = web.ctx.env['HTTP_X_FORWARDED_FOR'] else: ip_address = web.ctx.ip #validate ip address - TODO: this only validates IPv4 addresses! if not web.net.validipaddr(ip_address): print( "web.ctx.ip returned an invalid IP address! Check your WSGI configuration." ) raise web.SeeOther(".") return if not models.is_allowed_to_post(ip_address): return "You are posting too quickly, slow down!" #File size check if len(raw_image_data) > settings.MAX_IMAGE_SIZE: print("Image exceeds maximum size.") raise web.SeeOther(".") return if 'data:image/png;base64,' in raw_image_data: try: image_data = bytes( base64.b64decode( (raw_image_data.partition('data:image/png;base64,')[2] ))) print(image_data) image = Image.open(io.BytesIO(image_data)) except Exception as e: print("Error converting image data. \n" + str(e)) raise web.SeeOther(".") return else: #Comment with no image or an invalid image! raise web.SeeOther(".") return #Check that the image is in the correct format and is the correct size. if not image.size == (settings.IMAGE_WIDTH, settings.IMAGE_HEIGHT): print("Invalid image size: " + image.size) raise web.SeeOther(".") return #Check that the image format is correct if not image.format == "PNG": print("Invalid image format: " + image.format) raise web.SeeOther(".") return #Check that the provided name is a reasonable length if len(name) > settings.MAX_NAME_LENGTH: print("Name is too long! " + str(len(name))) raise web.SeeOther(".") return #All good, build the comment. reply = models.comment(name=name, ip_address=ip_address, approved=True) #Save the image. Could benifit from some sanity checks. outfile = open(reply.get_local_filename(), 'wb') image.save(outfile) #Save the reply reply.save() print(ip_address) models.make_post(ip_address) raise web.SeeOther(".")
def admin(): if session.get('log'): tem = comment().getNew() return render_template('admin.html', tem=tem) else: redirect(url_for('login'))