def post(self, request): responseblock = {} body_unicode = request.body.decode('utf-8') data = json.loads(body_unicode) # email=request.data['email'] # password=request.data['password'] email = data['email'] password = data['password'] user = authenticate(email=email, password=password) if user: login(request, user) if request.user.is_authenticated: print(user.id) # print(request.session) # role=Group.objects.get(id=user.id) # print("role is",role) jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user) temp_token = jwt_encode_handler(payload) token = "Bearer " + temp_token # print(token) responseblock['status'] = "success" responseblock['message'] = "successfully logged in" responseblock['token'] = token response = JsonResponse(responseblock) response.set_cookie('cookie', token) #let me understand if the cookie disabled in the browser settings, what wil happens? else: responseblock['status'] = "failure" responseblock['message'] = "something went wrong" response = JsonResponse(responseblock) return response
def deatil_one(request): good_id = request.GET.get('good')[:-1] try: good = Goods.objects.get(id=good_id) good_type = good.type hot_good = good_type.goods_set.order_by('-id').all()[:2] # Typefood = GoodsType.objects.order_by(id='id') except ObjectDoesNotExist as e: logging.warning(e) if request.COOKIES.get('Recently_Viewed'): cookie_good = request.COOKIES.get('Recently_Viewed') list_good = cookie_good.split(',') if good.id in list_good: list_good.remove(good.id) # 如果最近浏览多的话那么将最久没有被浏览的那个商品删除 if len(list_good) >= 5: list_good.pop() list_good = [good_id] + list_good cookie_good_new = ','.join(list_good) else: cookie_good_new = good_id user_id = request.session.get('user_id') mycartc = 0 if user_id: mycartc = CartInfo.objects.filter(user=user_id).count() # cookie处理数据添加的位置 response = render(request, 'detail.html', { 'goodone': good, 'hot_list': hot_good, 'mycartc': mycartc }) response.set_cookie('Recently_Viewed', cookie_good_new, max_age=3000) return response
def detail(request,gid=1): gdatail = GoodsInfo.goodsobj.get(id=int(gid)) gdatail.gclick=gdatail.gclick+1#维护一个点击量 gdatail.save() gtype = TypeInfo.typeobj.get(pk=gdatail.goodstype_id) goods_news = GoodsInfo.goodsobj.filter(goodstype_id=gdatail.goodstype_id).order_by('-id')[0:2] # 新品推荐 context = {'title': '商品详情', 'gtype': gtype, 'goods_news': goods_news,'gdatail': gdatail} response = render(request, 'homegoods/detail.html', context) #维护用户对商品的浏览记录 # goodsid = '%d'%gid#把整数变为字符串 goodsid=gid goodsids = request.COOKIES.get('goodsids','') if goodsids != '': #判断是否有浏览记录 goodsid_list = goodsids.split(',')#将字符串以','拆分为列表 if goodsid_list.count(goodsid)>=1:#该商品已经在最近浏览列表里 则删除 goodsid_list.remove(goodsid) goodsid_list.insert(0,goodsid) #添加到第一个 if len(goodsid_list)>=6: #判断商品是否已经多于六个 多了则删除最后一个 del goodsid_list[5] goodsids=','.join(goodsid_list) #将列表值拼接为字符串 else: goodsids = goodsid#没有则直接添加 response.set_cookie('goodsids',goodsids) #写入cookie return response
def login(request): fromPath = request.GET.get("from") gid = request.GET.get("gid") cid = request.GET.get("cid") sid = request.GET.get("sid") if request.method == "GET": return render(request, "mine/login.html", { "fromPath": fromPath, "gid": gid, "cid": cid, "sid": sid }) else: phone = request.POST.get('username') tokenValue = str(uuid.uuid4()) try: user = User.objects.get(pk=phone) #登录 user.tokenValue = tokenValue user.save() except User.DoesNotExist as e: #注册 user = User.create(phone, tokenValue) user.save() #将电话号吗写入session request.session['phone'] = user.phoneNum if gid: response = redirect('/' + fromPath + '/' + gid + '/' + cid + '/' + sid + '/') else: response = redirect('/' + fromPath + '/') #将token写入cookie response.set_cookie('token', user.tokenValue) return response
def post(self, request): """ 1.接收参数 2.将参数保存起来 3.更新cookie中的username信息 4.刷新当前页面(重定向操作) 5.返回响应 :param request: :return: """ user = request.user # 1.接收参数 username = request.POST.get('username', user.username) user_desc = request.POST.get('desc', user.user_desc) avatar = request.FILES.get('avatar') # 2.将参数保存起来 try: user.username = username user.user_desc = user_desc if avatar: user.avatar = avatar user.save() except Exception as e: logger.error(e) return HttpResponseBadRequest('修改失败,请稍后再试') # 3.更新cookie中的username信息 # 4.刷新当前页面(重定向操作) response = redirect(reverse('users:center')) response.set_cookie('username', user.username, max_age=14 * 3600 * 24) # 5.返回响应 return response
def glukalo2 (request): tStart = clock() # проверка на аутентификацию # if not request.user.is_authenticated(): # return HttpResponseRedirect("/not-denice") dimention_to_template = {} template = "glukalo_2.html" # шаблон NumViz = 0 # как будто первый визит if 'NumVisit' in request.COOKIES: # стоят кукии, и это не первый визит NumViz = request.COOKIES['NumVisit'] # читаем из кук число визитов NumViz = int(NumViz) + 1 # увеличиваем порядковый номер визитов # перебор видов деревьев # for i in SECTION_TYPE: # print i[0] Data = [] queryTree = TreeClassify.objects.order_by('iSectionType').order_by('sbSortTree') #.filter(iNesting=0) for countSection in queryTree: path = u"" Chain = countSection.lParentChain.split(',') queryTMP = TreeClassify.objects.filter(id__in=Chain[0:-1]).order_by('sbSortTree') for i in queryTMP: path += i.sSectionName_ru + ' ' path += countSection.sSectionName_ru Data.append( u"root " + path ) dimention_to_template.update({'DATA': Data}) dimention_to_template.update({'NV': NumViz}) dimention_to_template.update({'TAU': float(clock()-tStart)}) response = render (request, template, dimention_to_template) response.set_cookie("NumVisit", NumViz, max_age=604800) ## ставим или перезаписывем куки (неделя) return response
def glukalo1 (request): tStart = clock() # проверка на аутентификацию # if not request.user.is_authenticated(): # return HttpResponseRedirect("/not-denice") dimention_to_template = {} template = "glukalo_1.html" # шаблон NumViz = 0 # как будто первый визит if 'NumVisit' in request.COOKIES: # стоят кукии, и это не первый визит NumViz = request.COOKIES['NumVisit'] # читаем из кук число визитов NumViz = int(NumViz) + 1 # увеличиваем порядковый номер визитов queryTree = TreeClassify.objects.order_by('iSectionType').order_by('sbSortTree') #.filter(iNesting=0) Data = [] for countSection in queryTree: # path = u"" #Chain = countSection.lParentChain.split(',') #for count in Chain[0:-1]: # queryTMP = TreeClassify.objects.get(id=count) # path += queryTMP.sSectionName_ru + ' / ' # path += countSection.sSectionName_ru Data.append( u"root " + countSection.sSectionName_ru ) # TreeData.sort(key=lambda countSection: countSection['path']) dimention_to_template.update({'DATA': Data}) dimention_to_template.update({'NV': NumViz}) dimention_to_template.update({'TAU': float(clock()-tStart)}) response = render (request, template, dimention_to_template) response.set_cookie("NumVisit", NumViz, max_age=604800) ## ставим или перезаписывем куки (неделя) return response
def detail(request, id): goods = GoodsInfo.objects.get(pk=int(id)) goods.gclick = goods.gclick + 1 goods.save() news = goods.gtype.goodsinfo_set.order_by('-id')[0:2] context = { 'title': goods.gtype.ttitle, 'guest_cart': 1, 'g': goods, 'news': news, 'id': id} response = render(request, 'df_goods/detail.html', context) # 记录最近浏览,在用户中心使用 goods_ids = request.COOKIES.get('goods_ids', '') goods_id = '%d' % goods.id if goods_ids != '': # 判断是否有浏览记录,如果有则继续判断 goods_ids1 = goods_ids.split(',') # 拆分为列表 if goods_ids1.count(goods_id) >= 1: # 如果商品已经被记录,则删除 goods_ids1.remove(goods_id) goods_ids1.insert(0, goods_id) # 添加到第一个 if len(goods_ids1) >= 6: # 如果超过6个则删除最后一个 del goods_ids1[5] goods_ids = ','.join(goods_ids1) # 拼接为字符串 else: goods_ids = goods_id # 如果没有浏览记录则直接加 response.set_cookie('goods_ids', goods_ids) # 写入cookie return response
def post(self, request): username = request.POST.get('username') password = request.POST.get('password') remembered = request.POST.get('remembered') # print("-----",username) user = authenticate(request, username=username, password=password) # print("----",username) if user is None: return render(request, 'login.html', {'account_errmsg': '用户名或密码错误'}) # 4.保持登录状态 login(request, user) # 5.是否记住用户名 if remembered != 'on': # 不记住用户名, 浏览器结束会话就过期 request.session.set_expiry(0) else: # 记住用户名, 浏览器会话保持两周 request.session.set_expiry(None) # 6.返回响应结果 response = redirect(reverse('contents:index')) response.set_cookie('username', user.username, max_age=3600 * 24 * 15) from apps.carts.utils import merge_cart_cookie_to_redis merge_cart_cookie_to_redis(request=request, response=response) return response
def detail(request, id): goods = GoodsInfo.objects.get(pk=int(id)) goods.gclick += 1 goods.save() news = goods.gtype.goodsinfo_set.order_by('id')[0:2] context = {'g': goods, 'id': id, 'news': news, 'title': goods.gtype.ttitle} response = render(request, 'df_goods/detail.html', context) # 记录最近浏览在用户中心使用 goods_ids = request.COOKIES.get('goods_ids', '') goods_id = '%d' % goods.id # print(goods_id) if goods_ids != '': goods_ids1 = goods_ids.split(',') # 拆分为列表 if goods_ids1.count(goods_id) >= 1: goods_ids1.remove(goods_id) goods_ids1.insert(0, goods_id) if len(goods_ids1) >= 6: del goods_ids1[5] goods_ids = ','.join(goods_ids1) else: goods_ids = goods_id response.set_cookie('goods_ids', goods_ids) return response
def switch_lang(request): lang = request.GET.get("lang", None) response = HttpResponse(status=200) if lang is not None: request.session[translation.LANGUAGE_SESSION_KEY] = lang response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang) return response
def _make_cookie(response,uid,expires_in): expires = str(int(expires_in)) cookie = '%s:%s' % (str(uid), expires) '''md5 = hashlib.md5(s).hexdigest() cookie = '%s:%s:%s' % (str(uid), expires, md5)''' response.set_cookie(_COOKIE,base64.b64encode(cookie).replace('=', '_'),expires,expires,'/','.sinaapp.com') '''response.set_cookie(_COOKIE,base64.b64encode(cookie).replace('=', '_'),expires,'/','sinaapp.com')'''
def post(self, request): '''登录校验''' #接收数据 username = request.POST.get('username') password = request.POST.get('pwd') #校验数据 if not all([username, password]): return render(request, 'login.html', {'errmsg': '数据不完整'}) #业务处理:登录校验 user = authenticate(username=username, password=password) if user is not None: if user.is_active: #用户已激活时需要获取用户的登录状态 login(request, user) print('用户已激活!') #判断是否需要记住用户名 remember = request.POST.get('remember') #跳转到首页 response = redirect(reverse('goods:index')) if remember == 'on': #记住用户名 response.set_cookie('username', username, max_age=7 * 24 * 3600) else: response.delete_cookie('username') #返回response return response else: return render(request, 'login.html', {'errmsg': '账户未激活'}) else: #用户名密码错误 return render(request, 'login.html', {'errmsg': '用户名或密码错误'})
def post(self, request): # 接收参数 sku_id = request.POST.get('sku_id') # 判断参数是否为空 if not sku_id: return JsonResponse({'code': 1, 'message': '参数为空'}) # 判读用户是否登陆 if request.user.is_authenticated(): # 删除购物车数据 redis_conn = get_redis_connection('default') user_id = request.user.id # 商品不存在可忽略 redis_conn.hdel('cart_%s' % user_id, sku_id) else: # 未登录的状态 cart_json = request.COOKIES.get('cart') if cart_json is not None: cart_dict = json.loads(cart_json) # 判断要删除的数据在字典中 if sku_id in cart_dict: del cart_dict[sku_id] response = JsonResponse({'code': 0, "message": '删除成功'}) response.set_cookie('cart', json.dumps(cart_dict)) return response # 当删除成功或者没有要删除的都提示用户成功 return JsonResponse({'code': 0, 'message': '删除成功'})
def glukalo1(request): tStart = clock() # проверка на аутентификацию # if not request.user.is_authenticated(): # return HttpResponseRedirect("/not-denice") dimention_to_template = {} template = "glukalo_1.html" # шаблон NumViz = 0 # как будто первый визит if 'NumVisit' in request.COOKIES: # стоят кукии, и это не первый визит NumViz = request.COOKIES['NumVisit'] # читаем из кук число визитов NumViz = int(NumViz) + 1 # увеличиваем порядковый номер визитов queryTree = TreeClassify.objects.order_by('iSectionType').order_by( 'sbSortTree') #.filter(iNesting=0) Data = [] for countSection in queryTree: # path = u"" #Chain = countSection.lParentChain.split(',') #for count in Chain[0:-1]: # queryTMP = TreeClassify.objects.get(id=count) # path += queryTMP.sSectionName_ru + ' / ' # path += countSection.sSectionName_ru Data.append(u"root " + countSection.sSectionName_ru) # TreeData.sort(key=lambda countSection: countSection['path']) dimention_to_template.update({'DATA': Data}) dimention_to_template.update({'NV': NumViz}) dimention_to_template.update({'TAU': float(clock() - tStart)}) response = render(request, template, dimention_to_template) response.set_cookie( "NumVisit", NumViz, max_age=604800) ## ставим или перезаписывем куки (неделя) return response
def wrapper(detailView, request, goodsid, *args, **kwargs): #将存放在cookie中的goodsId获取 cookie_str = request.COOKIES.get('recommend', '') #存放所有goodsid的列表 goodsIdList = [gid for gid in cookie_str.split() if gid.strip()] #思考1:最终需要获取的推荐商品 goodsObjList = [ Goods.objects.get(id=gsid) for gsid in goodsIdList if gsid != goodsid and Goods.objects.get( id=gsid).category_id == Goods.objects.get( id=goodsid).category_id ][:4] #将goodsObjList传递给get方法 response = func(detailView, request, goodsid, goodsObjList, *args, **kwargs) #判断goodsid是否存在goodsIdList中 if goodsid in goodsIdList: goodsIdList.remove(goodsid) goodsIdList.insert(0, goodsid) else: goodsIdList.insert(0, goodsid) #将goodsIdList中的数据保存到Cookie中 response.set_cookie('recommend', ' '.join(goodsIdList), max_age=3 * 24 * 60 * 60) return response
def post(self,request): username = request.POST.get("username") password = request.POST.get("password") merusername = request.POST.get("merusername") # user = User.objects.get(username=username,password=password) user = authenticate(username=username,password=password) # django认证机制内置 print(user.username) if user!=None: if user.is_active: print("+++++++++++++++++++") login(request,user) print("+++++++++++++++++++") if merusername=="true": response = JsonResponse({"message": "OK", "username": username}) response.set_cookie("username",username) else: response = JsonResponse({"message": "OK", "username": username,}) response.delete_cookie("username") print("==================") return response else: return JsonResponse({"message":"账号尚未激活不能登陆"}) else: return JsonResponse({"message":"用户名或密码错误"})
def login(request): # html=request.COOKIES.get('html') # html = html[:3]+':'+html[3:] if request.method == 'GET': return render(request, 'login.html') elif request.method == 'POST': username = request.POST.get('username') password = genertat_password(request.POST.get('password')) users = User.objects.filter(username=username) if users.count(): users = User.objects.filter(username=username).filter( password=password) if users.count(): user = users.first() user.token = generate_token() #刷新token 保证安全性 user.save() response = redirect('mbb:index') request.session['token'] = user.token print(1) response.set_cookie('token', user.token) return response else: num = 2 print(2) return render(request, 'login.html', context={'num': num}) else: num = 1 print(3) return render(request, 'login.html', context={'num': num})
def login2(request): try: name = request.POST['name'] pwd = request.POST['pwd'] check = request.POST.get('check') with transaction.atomic(): user = User.objects.filter(Q(email=name) | Q(phone=name)).first() salt = user.salt # 再次对密码进行加密对比 hash_pwd1 = hash_pwd(pwd, salt) user = User.objects.filter( Q(email=name, password=hash_pwd1) | Q(phone=name, password=hash_pwd1)) if user: request.session['is'] = True request.session['name'] = name if check == '1': response = redirect('http://127.0.0.1:8000/ems/index/') response.set_cookie('name', name, max_age=3600 * 24 * 7) response.set_cookie('pwd', hash_pwd1, max_age=3600 * 24 * 7) return response else: response = redirect('http://127.0.0.1:8000/ems/index/') return response else: return HttpResponse('用户名或密码错误') except: return HttpResponse('登录失败')
def prize(request, num): token = request.session.get('token') user = User.objects.get(userToken=token) pri = Prize.objects.get(pk=num) request.session['prizeID'] = pri.id # 历史记录 # 获取cookie cookies = request.COOKIES.get(user.account, '') pk = str(pri.id) # 如果是第一次浏览,本地没有cookie,直接将id存到cookie里 if cookies == '': cookies = pk + ';' # ['1','2','3'] elif cookies != '': goods_id_list = cookies.split(';') # 判断这个奖品是否已经浏览过 if pk in goods_id_list: goods_id_list.remove(pk) goods_id_list.insert(0, pk) # 只保留10条记录 if len(goods_id_list) >= 10: goods_id_list = goods_id_list[:10] cookies = ';'.join(goods_id_list) # 获得参与人员名单 users = [] attachs = Attach.objects.filter(attachPrize_id=num) for attach in attachs: joiner = User.objects.get(pk=attach.attachUser_id) users.append(joiner) # 获得中奖人鱼名单 luckyUser = [] luckyAttach = Attach.objects.filter( Q(attachPrize_id=num) & Q(isLucky=True)) for luckyattach in luckyAttach: print(luckyattach.attachPrize.name) lucky = User.objects.get(pk=luckyattach.attachUser_id) print(lucky.name) luckyUser.append(lucky) # 参加抽奖 if request.method == "POST": code = request.POST.get('code') if code == pri.code: attach = Attach() attach.attachUser_id = user.id attach.attachPrize_id = pri.id pri.joinNum += 1 pri.save() attach.save() messages.success(request, '参与成功') return redirect('/prize/' + str(num) + '/') else: messages.error(request, '抽奖码错误') response = render(request, 'mylucky/prize.html', { 'prize': pri, 'joiner': users, 'luckyuser': luckyUser, 'user': user }) response.set_cookie(user.account, cookies) return response
def login_func(request, *args, **kwargs): # if request.session.get('user_id', None):... if request.session.get('user_name', None): return func(request, *args, **kwargs) else: response = redirect('/user/login/') response.set_cookie('url', request.path) return response
def about(request): visits = request.COOKIES.get('about_visits') if visits: visits = int(visits) + 1 else: visits = 1 response = render(request, 'myapp/about1.html', {'visits': visits}) response.set_cookie('about_visits', visits, expires=300) return response
def post(self, request): # 获取参数:sku_id, count sku_id = request.POST.get('sku_id') count = request.POST.get('count') # 校验参数all() if not all([sku_id, count]): return JsonResponse({'code': 1, 'message': '参数不对'}) # 判断商品是否存在 try: sku = GoodsSKU.objects.get(id=sku_id) except GoodsSKU.DoesNotExist: return JsonResponse({'code': 2, 'message': '商品不存在'}) # 判断count是否是整数 try: count = int(count) except Exception: return JsonResponse({'code': 3, 'message': '数量格式不对'}) # 判断库存 if count > sku.stock: return JsonResponse({'code': 4, 'message': '超过库存'}) print(11111) # 判断用户是否登陆 if request.user.is_authenticated(): print(99999999) # 如果用户登陆,将修改的购物车数据存储到redis中 redis_conn = get_redis_connection("default") user_id = request.user.id print(sku_id) redis_conn.hset('cart_%s' % user_id, sku_id, count) return JsonResponse({'code': 0, 'message': '保存成功'}) # 如果用户未登陆,将修改的购物车数据存储到cookie中 else: cart_json = request.COOKIES.get('cart') if cart_json is not None: cart_dict = json.loads(cart_json) else: cart_dict = {} print(2222) cart_dict[sku_id] = count # 将购物车字典转化为json字符串格式 new_cart_dict = json.dumps(cart_dict) # 响应结果 response = JsonResponse({'code': 0, 'message': '保存成功'}) # 保存到cook中 response.set_cookie('cart', new_cart_dict) return response
def chklogin(request): form = loginForm() if request.method == 'POST': form = loginForm(request.POST) if form.is_valid(): unm = request.POST.get('username') pwd = request.POST.get('password') response.set_cookie("user", unm) return render(request, 'stud/disp.html', {}) else: return render(request, 'stud/list.html', {})
def adddislike(request, slug): if slug in request.COOKIES: response = HttpResponseRedirect('/') else: article = get_object_or_404(Articles, id=slug) # возвращает id статьи или 404. article.article_dislike += 1 # Прибавляет единицу к article_likes article.save() # сохраняет response = HttpResponseRedirect('/') response.set_cookie(str(slug), "dislike") return response # делает редирект на ту же страницу
def my_team(request, key, write_cookie=True): if key == 'your-key-goes-here': return render(request, 'draftHost/team_hint.html', {}) team = get_object_or_404(models.FantasyTeam, auth_key=key) draft = fantasy.JsonFantasyDraft(team.draft) context = { 'team': team, 'draft': draft.json_dict(), } response = render(request, 'draftHost/team_page.html', context) if write_cookie: response.set_cookie('draftKey', key) return response
def room(request, user_id): id_user = get_object_or_404(User, id=user_id) if not request.COOKIES.get(str(request.user.id) + 'browse'): id_user.browse += 1 id_user.save() context = {} articles = Article.objects.filter(author=id_user) context['id_user'] = id_user context['articles'] = articles response = render(request, 'room.html', context) response.set_cookie(str(request.user.id) + 'browse', '1', max_age=3) return response
def pay(request): num = request.GET.get('num') response = redirect('mbb:returnurl') response.set_cookie('num', num) print(num) # 支付url url = alipay_mbb.direct_pay( subject='测试订单 --- iphone X', out_trade_no=num, total_amount=9.9, # 付款金额 return_url='http://http://127.0.0.1:8000/returnurl/') alipay_url = 'https://openapi.alipaydev.com/gateway.do?{data}'.format( data=url) return JsonResponse({'alipay_url': alipay_url})
def login(request): if request.method == 'POST': uf = UserForm(request.POST) if uf.is_valid(): username = uf.cleaned_data['name'] password = uf.cleaned_data['pwd'] #对比输入的用户名和密码和数据库中是否一致 userPassJudge = User.objects.filter(name=username, pwd=password) if userPassJudge: response = HttpResponseRedirect('/index/') response.set_cookie('cookie_username', username, 300) return response else: return render(request, 'login.html', {'uf': uf, 'error': "用户名或密码错误"}) else: uf = UserForm() return render(request, 'login.html', {'uf': uf})
def login(request): if request.method == "GET": return render(request, 'html/login.html') elif request.method == "POST": username = request.POST.get("username") password = generate_password(request.POST.get("password")) print(username, password) users = User.objects.filter(username=username).filter( password=password) if users.exists(): user = users.first() response = redirect('leshangwang:index') response.set_cookie('username', user.username) print(username) return response else: return HttpResponse('用户名或密码错误!')
def post(self, request): # 1.接收参数 mobile = request.POST.get('mobile') password = request.POST.get('password') remember = request.POST.get('remember') # 2.参数的验证 # 2.1 验证手机号是否符合规则 if not re.match(r'^1[3-9]\d{9}$', mobile): return HttpResponseBadRequest('手机号不符合规则') # 2.2 验证密码是否符合规则 if not re.match(r'^[a-zA-Z0-9]{8,20}$', password): return HttpResponseBadRequest('密码不符合规则') # 3.用户认证登录 # 采用系统自带的认证方法进行认证 # 如果我们的用户名和密码正确,会返回user # 如果我们的用户名或密码不正确,会返回None from django.contrib.auth import authenticate # 默认的认证方法是 针对于 username 字段进行用户名的判断 # 当前的判断信息是 手机号,所以我们需要修改一下认证字段 # 我们需要到User模型中进行修改,等测试出现问题的时候,我们再修改 user = authenticate(mobile=mobile, password=password) if user is None: return HttpResponseBadRequest('用户名或密码错误') # 4.状态的保持 from django.contrib.auth import login login(request, user) # 5.根据用户选择的是否记住登录状态来进行判断 # 6.为了首页显示我们需要设置一些cookie信息 # 根据next参数来进行页面的跳转 # next_page = request.GET.get('next') # if next_page: # response = redirect(next_page) # else: response = redirect(reverse('home:index')) if remember != 'on': # 没有记住用户信息 # 浏览器关闭之后 request.session.set_expiry(0) response.set_cookie('is_login', True) response.set_cookie('username', user.username, max_age=14 * 24 * 3600) else: # 记住用户信息 # 默认是记住 2周 request.session.set_expiry(None) response.set_cookie('is_login', True, max_age=14 * 24 * 3600) response.set_cookie('username', user.username, max_age=14 * 24 * 3600) # 7.返回响应 return response
def setCookie(request, *args, **kwargs): key_list = list(kwargs.keys()) try: if (('file_path' in key_list) and ('data' in key_list)): request.session.set_expiry(0) response = render(request, kwargs['file_path'], kwargs['data']) for item in key_list: if item != 'file_path' and item != 'data': response.set_cookie(f"{item}", kwargs[item]) if item == 'ucrypt': response.set_cookie('user_name', kwargs['user_name']) else: raise Exception('Check arguments passed !') except Exception as ex: print(f"SET COOKIE EX : {ex}") else: return response
def post(self, request): username = request.POST.get('username') password = request.POST.get('password') password2 = request.POST.get('password2') mobile = request.POST.get('mobile') sms_code = request.POST.get('msg_code') allow = request.POST.get('allow') if not all([username, password, password2, mobile, allow]): return http.HttpResponseForbidden("缺少必备参数") if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username): return http.HttpResponseForbidden('请输入5-20个字符的用户名') if not re.match(r'^[0-9A-Za-z]{8,20}$', password): return http.HttpResponseForbidden('请输入8-20位de的密码') if password != password2: return http.HttpResponseForbidden('请再次输入密码') if not re.match(r'^1[345789]\d{9}$', mobile): return http.HttpResponseForbidden('请输入正确的手机号') if allow != 'on': return http.HttpResponseForbidden('请勾选用户协议') # 3.注册 user = User.objects.create_user(username=username, password=password, mobile=mobile), # 3.保持登录状态 login(request, user) response = redirect(reverse("contents:index")) response.set_cookie('username', username, max_age=3600 * 24 * 15) sms_code_redis = get_redis_connection('sms_code') x_sms_code = sms_code_redis.get('sms_%s' % mobile) if x_sms_code != sms_code: return render(request, 'register.html', {'sms_code_errmsg': '输入短信验证码有误'}) return response
def register(request): token = request.COOKIES.get('token') user = User.objects.filter(token=token).first() if request.method == 'GET': return render(request, 'register.html', context={'user': user}) elif request.method == 'POST': user = User() user.username = request.POST.get('username') user.password = genertat_password(request.POST.get('password')) user.img = '/static/img/index/head.jpeg' user.token = uuid.uuid5(uuid.uuid4(), 'register') user.save() request.session['username'] = user.username response = redirect('mbb:index') response.set_cookie('token', user.token) return response
def index (request) : tStart = clock() # проверка на аутентификацию if not request.user.is_authenticated(): return HttpResponseRedirect("/not-denice") dimention_to_template = {} # словарь, для передачи шаблону template = "index.html" # шаблон MarkRowWithID = [] if request.method == 'GET': if 'to_do' in request.GET: # MarkRowWithID = int(request.GET['to_do']) MarkRowWithID = request.GET['to_do'].split(',') for countSection in range(0, len(MarkRowWithID)): try: MarkRowWithID[countSection] = int(MarkRowWithID[countSection]) except: pass # MarkRowWithID.append(int(request.GET['to_do'])) if 'to_del' in request.GET: dimention_to_template.update({'MAKE_DEL': request.GET['to_del']}) if 'to_aka' in request.GET: try: dimention_to_template.update({'MAKE_AKA': [int(request.GET['to_aka'])]}) except: pass dimention_to_template.update({'MAKE_LIGHT': MarkRowWithID}) NumViz = 0 # как будто первый визит if 'NumVisit' in request.COOKIES: # стоят кукии, и это не первый визит NumViz = request.COOKIES['NumVisit'] # читаем из кук число визитов NumViz = int(NumViz) + 1 # увеличиваем порядковый номер визитов # варианты деревьев TreeVariant = [] for i in SECTION_TYPE: TreeVariant.append({ 'TREE_NAME': i[1], 'TREE_VAL': i[0] }) dimention_to_template.update({ 'TREE_VARIANT': TreeVariant }) # вывод дерева queryTree = TreeClassify.objects.order_by('iSectionType', 'sbSortTree') #.filter(iNesting=0) dimention_to_template.update({'NUM_T': queryTree.count()}) TreeData = [] maxNest = 0 levNest = [] TypeOfTree = -100 for countSection in queryTree: if TypeOfTree != countSection.iSectionType: TypeOfTree = countSection.iSectionType TreeData.append({ 'id': 'NEW_SEC', 'sSectionName_ru': countSection.get_iSectionType_display() }) lag = u"" path = u"" if maxNest < countSection.iNesting: maxNest = countSection.iNesting levNest.append(maxNest) Chain = countSection.lParentChain.split(',') for count in Chain[0:-1]: # queryTMP = TreeClassify.objects.get(id=count) # path += queryTMP.sSectionName_ru + ' / ' lag += u" ├──" # path += countSection.sSectionName_ru strII = lag+countSection.sSectionName_ru strII = strII.replace(u"├── ", u"│ ") TreeData.append({ 'id': countSection.id, 'path': countSection.sbSortTree, 'nest': countSection.iNesting, 'alias': countSection.kAlias_id, 'sSectionName_ru': strII, 'sSectionName_trans': countSection.sSectionName_trans }) # TreeData.sort(key=lambda countSection: countSection['path']) for count in range(0, len(TreeData)): try: if TreeData[count+1]['nest'] < TreeData[count]['nest']: TreeData[count]['sSectionName_ru'] = TreeData[count]['sSectionName_ru'].replace(u"├──", u"└──") except: pass dimention_to_template.update({'QUERY': TreeData}) dimention_to_template.update({'LEV_NEST': levNest}) dimention_to_template.update({'NV': NumViz}) dimention_to_template.update({'TAU': float(clock()-tStart)}) response = render (request, template, dimention_to_template) response.set_cookie("NumVisit", NumViz, max_age=604800) ## ставим или перезаписывем куки (неделя) return response
def trans (request) : tStart = clock() # проверка на аутентификацию if not request.user.is_authenticated(): return HttpResponseRedirect("/not-denice") dimention_to_template = {} # словарь, для передачи шаблону template = "trans.html" # шаблон NumViz = 0 # как будто первый визит if 'NumVisit' in request.COOKIES: # стоят кукии, и это не первый визит NumViz = request.COOKIES['NumVisit'] # читаем из кук число визитов NumViz = int(NumViz) + 1 # увеличиваем порядковый номер визитов LangVariant = [] # действия для русского языка, как базового iNumItemsInClassify = TreeClassify.objects.aggregate(Count('id'))['id__count'] iNumRUItemsInLangMatch = TreeClassify.objects.aggregate(Count('sSectionName_ru'))['sSectionName_ru__count'] for i in LANGUAGE_TYPE: try: # пробуем получить инфу о файле FILENAME_FULL_CLASSIFIER_4TRBUB FullFileName = STATIC_BASE_PATH + u'/' + FILENAME_FULL_CLASSIFIER_4TRBUB_CSV + u"-" + i[0] + u'.csv' FileFullSize = os.path.getsize(FullFileName) FileFullTimestamp = datetime.fromtimestamp(os.path.getmtime(FullFileName)) except: FileFullSize = 0 FileFullTimestamp = 0 try: # пробуем получить инфу о файле FILENAME_UPDATE_CLASSIFIER_4TRBUB_CSV FullFileName = STATIC_BASE_PATH + u'/' + FILENAME_UPDATE_CLASSIFIER_4TRBUB_CSV + u"-" + i[0] + u'.csv' FileUpdateSize = os.path.getsize(FullFileName) FileUpdateTimestamp = datetime.fromtimestamp(os.path.getmtime(FullFileName)) except: FileUpdateSize = 0 FileUpdateTimestamp = 0 try: # пробуем получить инфу о файле FILENAME_2CHECK_CLASSIFIER_4TRBUB_CSV FullFileName = STATIC_BASE_PATH + u'/' + FILENAME_2CHECK_CLASSIFIER_4TRBUB_CSV + u"-" + i[0] + u'.csv' File2CheckSize = os.path.getsize(FullFileName) File2Checktamp = datetime.fromtimestamp(os.path.getmtime(FullFileName)) except: File2CheckSize = 0 File2CheckTimestamp = 0 q = LangMatch.objects.filter(sLangType=i[0]) iNumTotal = q.aggregate(Count('kTreeClassify_id')) # определение число дублей sqlFindDouble = "SELECT" \ " COUNT(classifier_langmatch.kTreeClassify_id) AS iNUM," \ " classifier_langmatch.kTreeClassify_id AS id " \ "FROM classifier_langmatch " \ "WHERE classifier_langmatch.sLangType = '%s' " \ " AND" \ " classifier_langmatch.bSectionTranslateActual IS TRUE " \ "GROUP BY classifier_langmatch.kTreeClassify_id " \ "HAVING COUNT(classifier_langmatch.sSectionNameForeign) > 1;" % i[0] iNumDoubles = len(list(LangMatch.objects.raw(sqlFindDouble))) sqlNoAddedToTranslate = "SELECT" \ " COUNT(TAB.kTreeClassify_id) AS id " \ "FROM (SELECT" \ " classifier_langmatch.kTreeClassify_id" \ " FROM classifier_langmatch" \ " WHERE (classifier_langmatch.sLangType = 'RUS'" \ " AND classifier_langmatch.bSectionTranslateActual = TRUE)" \ " OR classifier_langmatch.sLangType = '%s'" \ " GROUP BY classifier_langmatch.kTreeClassify_id" \ " HAVING COUNT(classifier_langmatch.kTreeClassify_id) = 1) AS TAB;" % i[0] iNumNoAddedToTranslate = LangMatch.objects.raw(sqlNoAddedToTranslate)[0].id # q2 = LangMatch.objects.filter(sLangType=i[0]).annotate(Count('id')) iNumActualNum = q.filter(bSectionTranslateActual=True).aggregate(Count('kTreeClassify_id')) iNumUnActualNum = q.filter(bSectionTranslateActual=False).aggregate(Count('kTreeClassify_id')) iNumNewItems = u"что-то-пошло-не-так-ОШИБКА" if i[0] == u"RUS": # для русского языка число новых разделов надо посчитать особым образом, # сравнивая реальные совпадения названий, а не только через id sqlNewRusClassifier = "SELECT" \ " COUNT(classifier_treeclassify.id) AS id " \ "FROM classifier_treeclassify" \ " LEFT OUTER JOIN classifier_langmatch" \ " ON classifier_langmatch.sSectionNameForeign = classifier_treeclassify.sSectionName_ru " \ "WHERE classifier_langmatch.sLangType IS NULL OR classifier_langmatch.sLangType <> 'RUS';" iNumNewItems = TreeClassify.objects.raw(sqlNewRusClassifier)[0].id else: iNumNewItems = iNumItemsInClassify - iNumDoubles - iNumActualNum['kTreeClassify_id__count'] LangVariant.append({ 'FILENAME_FULL_CLASSIFIER_4TRBUB': FILENAME_FULL_CLASSIFIER_4TRBUB_CSV + u"-" + i[0] + u'.csv', 'FILENAME_UPDATE_CLASSIFIER_4TRBUB': FILENAME_UPDATE_CLASSIFIER_4TRBUB_CSV + u"-" + i[0] + u'.csv', 'FILENAME_2CHECK_CLASSIFIER_4TRBUB': FILENAME_2CHECK_CLASSIFIER_4TRBUB_CSV + u"-" + i[0] + u'.csv', 'FULL_FILE_SIZE': FileFullSize, 'UPDATE_FILE_SIZE': FileUpdateSize, 'CHECK_FILE_SIZE': File2CheckSize, 'FULL_FILE_DATATIME': FileFullTimestamp, 'UPDATE_FILE_DATATIME': FileUpdateTimestamp, 'CHECK_FILE_DATATIME': File2CheckTimestamp, 'ITEM_PAIR': iNumDoubles, 'ITEM_NEW': iNumNewItems, 'ITEM_NO_ADD_TO_TRANSLATE': iNumNoAddedToTranslate, 'ITEM_TOTAL': iNumTotal['kTreeClassify_id__count'], 'ITEM_ACTUAL_N': iNumActualNum['kTreeClassify_id__count'], 'ITEM_UNACTUAL_N': iNumUnActualNum['kTreeClassify_id__count'], 'LANGUAGE_NAME': i[1], 'LANGUAGE_CODE': i[0] }) dimention_to_template.update({ 'LANG_WORKER': LangVariant }) # вывод дерева dimention_to_template.update({'NV': NumViz}) dimention_to_template.update({'TAU': float(clock()-tStart)}) response = render (request, template, dimention_to_template) response.set_cookie("NumVisit", NumViz, max_age=604800) ## ставим или перезаписывем куки (неделя) return response
def aliasmanager (request): tStart = clock() # проверка на аутентификацию # if not request.user.is_authenticated(): # return HttpResponseRedirect("/not-denice") dimention_to_template = {} template = "aliaser.html" # шаблон MarkRowWithID = [] if request.method == 'GET': if 'to_do' in request.GET: # MarkRowWithID = int(request.GET['to_do']) MarkRowWithID = request.GET['to_do'].split(',') for countSection in range(0, len(MarkRowWithID)): try: MarkRowWithID[countSection] = int(MarkRowWithID[countSection]) except: pass # MarkRowWithID.append(int(request.GET['to_do'])) if 'to_aka' in request.GET: try: dimention_to_template.update({'MAKE_AKA': [int(request.GET['to_aka'])]}) except: pass dimention_to_template.update({'MAKE_LIGHT': MarkRowWithID}) NumViz = 0 # как будто первый визит if 'NumVisit' in request.COOKIES: # стоят кукии, и это не первый визит NumViz = request.COOKIES['NumVisit'] # читаем из кук число визитов NumViz = int(NumViz) + 1 # увеличиваем порядковый номер визитов # поиск алаас-кандидатов qAliasCandidat = TreeClassify.objects.raw( u"SELECT" \ u" classifier_treeclassify.sSectionName_ru AS id," \ u" COUNT(classifier_treeclassify.sSectionName_ru) AS INTERSEC " \ u"FROM classifier_treeclassify " \ u"GROUP BY classifier_treeclassify.sSectionName_ru " \ u"HAVING COUNT(classifier_treeclassify.sSectionName_ru) > 1 " \ u"ORDER BY" \ u" INTERSEC," \ u" classifier_treeclassify.sSectionName_ru;" \ ) dimention_to_template.update({'NUM_T': len(list(qAliasCandidat))}) DimAlias = [] for count in qAliasCandidat: qInAlias = TreeClassify.objects.filter(sSectionName_ru=count.id).order_by('sbSortTree') InAliasSet = [] for iid in qInAlias: path = "" Chain = iid.lParentChain.split(',') for count_chain in Chain[0:-1]: queryTMP = TreeClassify.objects.get(id=int(count_chain)) path += queryTMP.sSectionName_ru + ' / ' ItemInAlias = { 'path_s': path, 'id_s': iid.id, 'alias_s': iid.kAlias_id } InAliasSet.append(ItemInAlias) # print InAliasSet DimAlias.append({ 'name': count.id, 'inset': InAliasSet }) #print count.id, count.INTERSEC #print DimAlias dimention_to_template.update({'ALIAS_ARR': DimAlias}) # dimention_to_template.update({'SOMETHING_DO_WITH_ID': 0}) dimention_to_template.update({'NV': NumViz}) dimention_to_template.update({'TAU': float(clock()-tStart)}) response = render (request, template, dimention_to_template) response.set_cookie("NumVisit", NumViz, max_age=604800) ## ставим или перезаписывем куки (неделя) return response