def download(request): doc = dom.Document() root = doc.createElement("diarys") doc.appendChild(root) diaries = request.user.diary_set.all() for diary in diaries: blognode = doc.createElement("diary") blognode.setAttribute("diaryWeather", diary.weather) tools.debug("download diary", diary.weather, weekday(diary.timestamp.weekday())) blognode.setAttribute("diaryWeekDay", weekday(diary.timestamp.weekday())) blognode.setAttribute("diaryDate", diary.timestamp.strftime("%Y%m%d")) bv = doc.createTextNode(diary.body) blognode.appendChild(bv) root.appendChild(blognode) xmlstr = doc.toprettyxml("\t", "\n", 'utf-8') f = ContentFile(xmlstr) response = HttpResponse(f.read(), content_type='xml') response['Content-Disposition'] = \ 'attachment; filename=%s' % "diary"+datetime.now().strftime("%Y%m%d")+".xml" return response
def recover(request): xmldoc = dom.parse(dazhu.settings.BASE_DIR + '/diary.xml') itemlist = xmldoc.getElementsByTagName('diary') result = "over" tools.debug("start import") for item in itemlist: try: temp_time = datetime.strptime(item.attributes["diaryDate"].value, "%Y%m%d").date() tempdiary = Diary.objects.filter(timestamp=temp_time)[0] except: tempdiary = Diary() tempdiary.author = request.user tempdiary.weather = item.attributes["diaryWeather"].value tempdiary.timestamp = datetime.strptime( item.attributes["diaryDate"].value, "%Y%m%d").date() tempdiary.body = item.firstChild.nodeValue result += item.attributes["diaryDate"].value + " imported <br>" #tools.debug("body",tempdiary.body) tempdiary.save() return HttpResponse(result)
def del_file(request): del_path = request.GET["dp"] subfolder = dazhu.settings.BASE_DIR + "/dazhu/static/pan/" tools.debug("del_file path = ", del_path) os.remove(subfolder + del_path) # out_bytes = subprocess.check_output('wget {}'.format(download_path), shell=True) return redirect("/pan")
def ajaxDiary(request, pages): tools.debug("ajax get posts ", pages) try: pages = int(pages) except: pages = 1 try: is_desc = request.GET["is_desc"] is_desc = False if is_desc.lower() in ['false', '0'] else True except: is_desc = True pagesInfo = getDiary(pages, request.user, is_desc) posts = pagesInfo[0] allpages = pagesInfo[1] if allpages < pages: #tools.debug("allpages < pages ", allpages, pages) return HttpResponse() result = [] for item in posts: result.append({'id':item.id, 'weather':item.weather,\ 'timestamp':item.timestamp.strftime("%Y-%m-%d"),\ 'body':item.body.replace('\r', '<br>').replace('\n', '<br>'),\ 'weekday':weekday(item.timestamp.weekday()),}) #tools.debug("ajax post is ",result) return HttpResponse(json.dumps(result, ensure_ascii=False))
def get_context_data(self, **kwargs): context = super(details, self).get_context_data(**kwargs) guid = self.args[0] tools.debug("blog details get_context_data guid %s" % guid) try: blog = BlogPost.objects.get(guid=guid) except BlogPost.DoesNotExist: tools.debug("blog details get_context_data blog %s is not found" % guid) raise Http404("does not exist") # check if it is privite category category = Category.objects.get(title=blog.category) if category.is_privite and not self.request.user.is_authenticated(): raise Http404( "you cant feel the blog because it is in privite group") blog.body = markdown.markdown(blog.body, extensions=[ 'markdown.extensions.extra', "markdown.extensions.nl2br", 'markdown.extensions.sane_lists', 'codehilite' ]) category = get_category_obj(self.request.user.is_authenticated()) context['blog'] = blog context['category'] = category context['title'] = blog.title context['description'] = blog.body comments = blog.comment_set.all() context['comments'] = comments context['commentsCount'] = len(comments) return context
def resizeImg(img, output_path, dst_w=0, dst_h=0, qua=85): ''''' 只给了宽或者高,或者两个都给了,然后取比例合适的 如果图片比给要压缩的尺寸都要小,就不压缩了 ''' ori_w, ori_h = img.size widthRatio = heightRatio = None ratio = 1 if (ori_w and ori_w > dst_w) or (ori_h and ori_h > dst_h): if dst_w and ori_w > dst_w: widthRatio = float(dst_w) / ori_w #正确获取小数的方式 if dst_h and ori_h > dst_h: heightRatio = float(dst_h) / ori_h if widthRatio and heightRatio: if widthRatio < heightRatio: ratio = widthRatio else: ratio = heightRatio if widthRatio and not heightRatio: ratio = widthRatio if heightRatio and not widthRatio: ratio = heightRatio newWidth = int(ori_w * ratio) newHeight = int(ori_h * ratio) else: newWidth = ori_w newHeight = ori_h tools.debug("resizeImg width %s height %s" % (newWidth, newHeight)) img.resize((newWidth, newHeight), Image.ANTIALIAS).save(output_path, quality=qua)
def delete(self, request, id): tools.debug("delete id is ", id) try: Diary.objects.get(id=int(id)).delete() except Exception as error: tools.debug("delete method error", error) return HttpResponse("error") return HttpResponse("success")
def post(self, request): url = urllib.unquote(request.GET["url"]) if url != "": if request.user.check_password(request.POST['pwd']): set_user_login(request) tools.debug("pwd is error", request.POST['pwd']) return redirect(url) return redirect("/")
def returned_wrapper(request, *args, **kwargs): try: if request.user.is_authenticated(): tools.debug("user is ", request.user.id) return func(request, *args, **kwargs) return HttpResponseForbidden() except Exception as error: tools.debug("login failed", request, error) raise Http404
def returned_wrapper(request, *args, **kwargs): try: if is_user_login_timeout(request) == False: return func(request, *args, **kwargs) return HttpResponseRedirect('/account/userlogin?url=' + urllib.quote(request.get_full_path())) except Exception as error: tools.debug("user_login check failed", request, error) raise Http404
def returned_wrapper(request, *args, **kwargs): try: if is_black_ip(get_ip(request)) == False: return func(request, *args, **kwargs) resp = HttpResponseForbidden() resp.write("你的IP被封禁") return resp except Exception as error: tools.debug("ip filter failed", request, error) raise Http404
def is_black_ip(input_ip): tools.debug("is_black_ip input ip:", input_ip) black_list = cache.get('black_ip_list') if black_list == None: db_ip_list = models.IP.objects.all() cache.set('black_ip_list', db_ip_list, 60) black_list = db_ip_list for item in black_list: if input_ip.startswith(item.body): return True return False
def get_context_data(self, *args, **kwargs): context = super(index, self).get_context_data(**kwargs) context['title'] = u'日记' if 'is_desc' in self.request.GET: is_desc = self.request.GET['is_desc'] is_desc = False if is_desc.lower() in ['false', '0'] else True else: is_desc = True context['is_desc'] = is_desc tools.debug("is_desc", is_desc) return context
def get_user_info(request): try: user_info = [ request.user.email, request.user.first_name, request.user.last_name, request.user.date_joined.strftime('%Y-%m-%d %H:%M:%S'), request.user.is_staff ] tools.debug(user_info) return HttpResponse(simplejson.dumps(user_info, ensure_ascii=False)) except: return HttpResponse()
def get_context_data(self, **kwargs): context = super(result, self).get_context_data(**kwargs) keywords = None try: keywords = self.request.GET["k"] except: pass tools.debug("search key", keywords) keywords = urllib.unquote(keywords) tools.debug('search key2', keywords) posts_title = BlogPost.objects.filter(title__contains=keywords) posts_body = BlogPost.objects.filter(body__contains=keywords) final_result = [] class SearchItem(object): pass def _get_search_item(guid, category, title, body, keywords): tempItem = SearchItem() tempItem.guid = guid tempItem.category = category tempItem.title = self.GetContent(title, keywords) tempItem.search_content = self.GetContent(body, keywords) return tempItem title_result = [ _get_search_item(x.guid, x.category, tools.RemoveHttpStr(x.title), tools.RemoveHttpStr(x.body), keywords) for x in posts_title ] body_result = [ _get_search_item(x.guid, x.category, tools.RemoveHttpStr(x.title), tools.RemoveHttpStr(x.body), keywords) for x in posts_body if keywords in tools.RemoveHttpStr(x.body) ] final_result += title_result final_result += body_result no_repeat_id_map = {} no_repeat_result = [] for item in final_result: if item.guid not in no_repeat_id_map: no_repeat_id_map[item.guid] = True no_repeat_result.append(item) context['title'] = keywords context['posts'] = no_repeat_result return context
def get_context_data(self, **kwargs): tools.debug("kwargs is ", kwargs) aid = self.args[0] context = super(list, self).get_context_data(**kwargs) pageCount = 20 if aid == "": aid = 1 aid = int(aid) allCounts = BlogPost.objects.count() allPages = allCounts // pageCount + 1 posts = BlogPost.objects.all().order_by("-timestamp")[(aid - 1) * pageCount:aid * pageCount] if not self.request.user.is_authenticated(): posts = [x for x in posts] posts = remove_from_category(posts) finalPosts = [] class postBlock(object): def __init__(self): self.title = "" self.items = [] #在list的时候,按月分组显示 tempTime = "" tempPB = postBlock() group_time_fmt = '%Y-%m' for item in posts: item.commentsCount = item.comment_set.count() if item.timestamp.strftime(group_time_fmt) != tempTime: finalPosts.append(tempPB) tempPB = postBlock() tempPB.title = item.timestamp.strftime(group_time_fmt) tempTime = item.timestamp.strftime(group_time_fmt) tempPB.items.append(item) else: tempPB.items.append(item) finalPosts.append(tempPB) finalPosts.pop(0) context['posts'] = finalPosts context['category'] = get_category_obj( self.request.user.is_authenticated()) context['currentAid'] = aid context['allPages'] = allPages context['title'] = u'博客' return context
def setList(self, filelist): for item in filelist: if listtype == "listimage": tools.debug("listtype is ", listtype, item) ext = (os.path.splitext(item.rndName)[1]).lower() tools.debug("upload ext is ", ext) exts = ['.jpg', '.bmp', '.png', '.jpeg'] if ext not in exts: continue tempItem = { 'url': "static/upload/" + os.path.basename(item.rndName), 'title': item.sourceName } self.list.append(tempItem)
def post(self, request, aid): ''' post blog comment NOT blog content :param request: :param aid: :return this page: ''' tools.debug("id is ", aid) commentUser = xss_white_list(request.POST['user']) message = xss_white_list(request.POST['message']) tempComment = Comment() tempComment.author = commentUser tools.debug("commentUser ", commentUser) tempComment.body = message tools.debug("message ", message) tempComment.blog = BlogPost.objects.get(guid=aid) tempComment.timestamp = timezone.now() tools.debug("timestamp ", timezone.now()) tempComment.save() send_msg(rid=0, sid=0, title=u"新的博客评论", content=u"标题:{} <a href='/blog/details/{}'>链接</a>".format( tempComment.blog.title, tempComment.blog.guid)) return redirect("/blog/details/" + aid)
def get_content(request): aid = request.GET["aid"] answer = request.GET["answer"] tempblog = BlogPost.objects.get(guid=aid) tools.debug("getcontent", aid, answer, tempblog.answer) if tempblog.answer == answer: tempblog.body = markdown.markdown(tempblog.body, extensions=[ 'markdown.extensions.extra', "markdown.extensions.nl2br", 'markdown.extensions.sane_lists', 'codehilite' ]) return HttpResponse(tempblog.body) else: return HttpResponse("error")
def download_file(request): subfolder = dazhu.settings.BASE_DIR + "/dazhu/static/pan/" dp_url = request.GET["dp"] tools.debug("download_file dp_url = ", dp_url) # out_bytes = subprocess.check_output('wget {}'.format(download_path), shell=True) def __download(url): tools.debug("__download url", url) out_bytes = subprocess.check_output('wget {} -P {}'.format( url, subfolder), shell=True) tools.debug("download_file", out_bytes) pool.apply_async(__download, (dp_url, )) return redirect("/pan")
def post(self, request, pid): commentUser = websecu.xss_white_list(request.POST['user']) message = websecu.xss_white_list(request.POST['message']) tools.debug("message:", pid, commentUser, message, request.POST['message']) insert_message = Message() insert_message.body = message insert_message.author = commentUser insert_message.timestamp = datetime.now() insert_message.save() send_msg(rid=0, sid=0, title=u"新的留言", content=u"内容:{}".format(message)) return redirect("/message/")
def GetContent(self, input_str, keyword): color_fmt = "<span style='color:red;'>@#k</span>" content_length = 60 tools.debug("GetContent ", input_str) # input_str = tools.RemoveHttpStr(input_str) index = input_str.find(keyword) start = index - content_length if start < 0: start = 0 end = index + content_length if end > len(input_str): end = len(input_str) input_str = input_str[start:end] color_keyword = color_fmt.replace("@#k", keyword) input_str = input_str.replace(keyword, color_keyword) return input_str
def rolate_pic(request, inputName): pic = Photoes.objects.get(rndName=inputName) normal_path = u"".join( [settings.BASE_DIR, "/dazhu/static/album/normal/", pic.rndName]).encode("utf-8") im = Image.open(normal_path) im.rotate(-90, expand=True).save(normal_path) mini_path = u"".join( [settings.BASE_DIR, "/dazhu/static/album/mini/", pic.rndName]).encode("utf-8") make_thumbnail(normal_path, mini_path) redict_path = u"".join(["/album/show/", inputName]) tools.debug("rolate_pic", redict_path) return redirect(redict_path)
def change_view(self, request, object_id, form_url='', extra_context=None): try: tempDiary = Diary.objects.get(id=object_id) tools.debug("obj id ", object_id) tools.debug("author id", tempDiary.author.id) tools.debug("request author id", request.user.id) if tempDiary.author.id != request.user.id or \ "user_login" not in request.session: tools.debug("change diary error") return HttpResponse("cannot access this diary") except: tools.debug("change diary except error") pass return admin.ModelAdmin.change_view(self, request, object_id, form_url=form_url, extra_context=extra_context)
def getAlbum(pages, is_login): pageCount = 24 tools.debug("islogin", is_login) pages = int(pages) allCounts = Photoes.objects.count() allPages = allCounts // pageCount + 1 posts = None if is_login: posts = Photoes.objects.all().order_by("-timestamp")[(pages - 1) * pageCount:pages * pageCount] else: posts = Photoes.objects.filter( phototype='public').order_by("-timestamp")[(pages - 1) * pageCount:pages * pageCount] return posts, allPages
def post(self, request, id): tools.debug("id is ", id) weather = request.POST['weather'] textbody = request.POST['textbody'] DiaryDate = request.POST['DiaryDate'] textbody = textbody.replace("\r\n", "<br/>") id = int(id) tempDiary = Diary() if id != 0: tempDiary = Diary.objects.get(id=id) tempDiary.author = request.user tempDiary.body = textbody tempDiary.weather = weather tools.debug("weather is ", weather) tempDiary.timestamp = datetime.strptime(DiaryDate, "%Y-%m-%d").date() tempDiary.save() return HttpResponseRedirect('/diary/')
def controller(request, *args): path = request.path tempPathArr = path.split("/") ctl = tempPathArr[1] vw = tempPathArr[2] itemID = tempPathArr[3] tools.debug("id is ",itemID) try: if itemID == "": tools.debug("id is empty") tempCms = CmsItem.objects.filter(controller = ctl).get(view = vw) else: tempCms = CmsItem.objects.filter(controller = ctl).filter(view = vw).get(itemID=int(itemID)) return cms(request,tempCms) except Exception as error: tools.debug("cms routing error ",error) valList = "" for item in tempPathArr: valList += item + " ; " return HttpResponse("controller:" + tempPathArr[1] + "<br/>view:" + \ tempPathArr[2] + "<br/>input id:" + itemID)
def get_context_data(self, **kwargs): tools.debug("kwargs is ", kwargs) page_id = self.args[0] context = super(list, self).get_context_data(**kwargs) pageCount = 10 if page_id == "": page_id = 1 page_id = int(page_id) allCounts = Message.objects.count() allPages = allCounts // pageCount + 1 posts = Message.objects.all().\ order_by("-timestamp")[(page_id - 1) * pageCount:page_id * pageCount] #c = {'posts':finalPosts, "category":category, 'currentAid':aid, 'allPages':allPages, } context['currentAid'] = page_id context['posts'] = posts context['allPages'] = allPages context['title'] = u'留言板' return context
def ajaxGetFirst6Album(request): pages = 1 pagesInfo = getAlbum(pages, request.user.is_authenticated()) posts = pagesInfo[0] allpages = pagesInfo[1] if allpages < pages: tools.debug("allpages < pages ", allpages, pages) return HttpResponse() result = [] i = 0 for item in posts: i += 1 if i == 7: break result.append({ 'rndName': item.rndName, 'showName': item.showName, }) return HttpResponse(json.dumps(result, ensure_ascii=False))
def ajaxGetAlbum(request, pages): tools.debug("ajax get posts ", pages) try: pages = int(pages) except: pages = 1 pagesInfo = getAlbum(pages, request.user.is_authenticated()) posts = pagesInfo[0] allpages = pagesInfo[1] if allpages < pages: tools.debug("allpages < pages ", allpages, pages) return HttpResponse() result = [] for item in posts: result.append({ 'rndName': item.rndName, 'showName': item.showName, }) return HttpResponse(json.dumps(result, ensure_ascii=False))