def process_request(self, request): try: # 1. GET参数整合到parameters request.parameters = request.GET.copy() if request.method == "POST": # 2. 处理request.body内的query_string更新到request.parameters # multipart/form-data 时不处理表单里的参数,因为没有经过nginx的参数签名校验,无法保证参数合法性 if request.META['CONTENT_TYPE'].startswith('multipart/form-data'): return None # application/x-www-form-urlencoded 时不处理request.body elif request.META['CONTENT_TYPE'] == 'application/x-www-form-urlencoded': pass # xml or json 时不处理request.body elif request.body.startswith("<") or request.body.startswith("{") or request.body.startswith("["): pass # 其他情况更新request.body内的query_string到request.parameters elif '=' in request.body: request.parameters.update(QueryDict(request.body, encoding='utf-8')) # 3. 表单参数更新到request.parameters for k in request.POST: # 使用setlist以支持类似复选控件一个name多个value的情况 request.parameters.setlist(k, request.POST.getlist(k)) # 提取用户的客户端信息 RequestInfo.DATA = { "request_ip": get_clientip(request), "user_agent": request.META.get("HTTP_USER_AGENT", "") } # 安全日志部分到此为止 return None except Exception as ex: SysLogger.exception(ex, request) response = HttpResponseBadRequest() return response
def detail(request, year, month, day, id): """ 博客详情 """ try: article = Article.objects.get(id=id) # 文章阅读量统计,12小时内连续访问的IP只记录一次 ip_address = get_clientip(request) key = ip_address + '_' + str(id) if cache.get(key) is None: article.count += 1 article.save(update_fields=['count']) cache.set(key, str(datetime.now() + timedelta(hours=12)), 12 * 60 * 60) # 设置12小时过期 statics_count = Article.objects.aggregate( blog_count=Count('id', distinct=True), read_count=Sum('count'), tags_count=Count('tags', distinct=True) ) # 生成文章目录 if article.editor == EditorKind.Markdown: md = markdown.Markdown(extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc', 'markdown.extensions.tables' ]) article.content = md.convert(article.content) toc = md.toc tag_list, music_list = get_tags_and_musics('tmp_tags', 'tmp_musics') # 获取所有标签,并随机赋予颜色 not_update_days = (datetime.now() - article.last_update).days # 计算文章距现在多长时间没有更新 return render(request, 'blog/content.html', locals()) except Article.DoesNotExist: raise Http404
def _validate_access(request, *args, **kwargs): allowed_ips = config.get('domain') or [] # 验证IP ip_permission = False client_ip = get_clientip(request) if len(allowed_ips) == 0 or allowed_ips[0] == '*': ip_permission = True else: for ip in set(allowed_ips): if fnmatch(client_ip, ip): ip_permission = True break if not ip_permission: return HttpResponseForbidden("REQUEST IP %s IS NOT ALLOWED" % client_ip) response = view_func(request, *args, **kwargs) return response
def _validate_access(request, *args, **kwargs): allowed_ips = config.get('domain') or [] # 验证IP ip_permission = False client_ip = get_clientip(request) if len(allowed_ips) == 0 or allowed_ips[0] == '*': ip_permission = True else: for ip in set(allowed_ips): if fnmatch(client_ip, ip): ip_permission = True break if not ip_permission: return HttpResponseForbidden("REQUEST IP %s IS NOT ALLOWED" % client_ip) response = view_func(request, *args, **kwargs) return response
def add_comments_view(request): """ 添加评论 """ form = CommentForm(request.POST) if not form.is_valid(): return http_response(request, statuscode=ERRORCODE.PARAM_ERROR) nickname = form.cleaned_data.get('nickname') email = form.cleaned_data.get('email') website = form.cleaned_data.get('website') content = form.cleaned_data.get('content') target = form.cleaned_data.get('target') parent_comment_id = form.cleaned_data.get('parent_comment_id') try: user, created = Visitor.objects.update_or_create( nickname=nickname, email=email, defaults={ "nickname": nickname, "email": email, "website": website, "avatar": gravatar_url(email) }) ip_address = get_clientip(request) country, province, city = get_location_by_ip(ip_address) anchor = "".join([ random.choice("abcdefghijklmnopqrstuvwxyz1234567890") for i in xrange(16) ]) comment_data = { "user_id": user.id, "content": content, "target": target, "ip_address": ip_address, "country": country, "province": province, "city": city, "anchor": anchor, } # 二级回复 if parent_comment_id: parent_comment = Comments.objects.select_related().filter( pk=parent_comment_id).first() reply_to = parent_comment.user if parent_comment else None comment_data.update({ "parent_id": parent_comment_id, "reply_to": reply_to }) mail_body = MailTemplate.notify_parent_user.format( parent_user=parent_comment.user.nickname, parent_comment=parent_comment.content, target_url=DOMAIN_NAME + parent_comment.target, anchor='#' + parent_comment.anchor) send_email_task.delay(reply_to.email, mail_body) Comments.objects.create(**comment_data) messages.success(request, u'评论成功') cache.delete_pattern(target) # 清除缓存 if not parent_comment_id and not user.blogger: mail_body = MailTemplate.notify_blogger.format( nickname=nickname, comment=content, target_url=DOMAIN_NAME + target, anchor='#' + anchor) send_email_task.delay(BLOGGER_EMAIL, mail_body) return http_response(request, statuscode=ERRORCODE.SUCCESS) except Exception as exp: return http_response(request, statuscode=ERRORCODE.FAILED, msg=exp)