def home(request): if request.method=='POST': username = request.POST['username'] password = request.POST['password'] if User.objects.filter(uname=username, passwd=password).exists(): permissions = Permissions.objects.filter(user=User.objects.get(uname=username, passwd=password)) team_set = set() for permission in permissions: team_set.add(permission.team) context = {"teams": list(team_set)} response = HttpResponse() response = render(request, 'home/choice.html', context) response.set_cookie( key='sesid', value=User.objects.filter(uname=username, passwd=password).get().ses_id ) response.set_cookie( key='username', value=User.objects.filter(uname=username, passwd=password).get().uname ) return response else: return HttpResponse("<html><h1>Invalid Details</h1></html>") elif logged_in(request): permissions = Permissions.objects.filter(user=User.objects.get(uname=request.COOKIES['username'])) team_set = set() for permission in permissions: team_set.add(permission.team) context = {"teams": list(team_set)} return render(request, 'home/choice.html', context) else: return render(request, 'home/login.html')
def load (request, slug): '''Recives slug URL, checks the database, sets meieraha.data cookie if the URL is valid and redirects the browser to main page.''' template = loader.get_template('redirect.html') # response = HttpResponseRedirect(redirect_to='/') response = HttpResponse(template.render(Context({}))) try: bubbles = Bubbles.objects.get(slug=slug) except Bubbles.MultipleObjectsReturned: bubbles = Bubbles.objects.filter(slug__exact=slug)[0] except Bubbles.DoesNotExist: return response max_age = 60 expires = datetime.datetime.strftime(datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age), "%a, %d-%b-%Y %H:%M:%S GMT") response.set_cookie('meieraha.data', slug, max_age=max_age, expires=expires, domain=None, # max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN or None, secure=None), # secure=settings.SESSION_COOKIE_SECURE or None) return response
def rpc(request, method_name, null=False): if method_name[:1] == '_': return HttpResponseServerError('cant call private method') _log_call(request.browser_id, method_name, request.POST.copy()) args = { 'request': request } try: for k, v in request.POST.items(): args[k.encode('ascii')] = json.loads(v) except UnicodeEncodeError: return HttpResponseServerError('non-ascii chars received') except JSONDecodeError: return HttpResponseServerError('invalid json') rpc_module = null_rpc_views if null else rpc_views try: func = getattr(rpc_module, method_name) except AttributeError: return HttpResponseServerError('no method named ' + method_name) try: result = func(**args) except TypeError: result = {'error': 'Incorrect number of arguments'} user_message = result and result.pop("_user_message", None) response = HttpResponse(json.dumps(result), "application/json") if user_message is not None: response.set_cookie( "_user_message", user_message["body"], expires= cookie_date(time.time() +6), path="/") return response
def get(self, request, *args, **kwargs): args_dict = request.GET.copy() args_dict.update({ "test_suite_pk": kwargs["pk"], "measure_name": kwargs["mname"] }) cmd = [ settings.PYTHON_EXE, os.path.join(settings.BASE_DIR, "bin", "plot_png.py"), args_dict.urlencode(safe='/%') ] print "Plot png: %s" % cmd[-1] result = subprocess.check_output(cmd, env=os.environ.copy()).strip() qdict = QueryDict(result) fname = qdict.get("fname") alarm = qdict.get("alarm") if fname and fname != "": f = open(fname, 'rb') response = HttpResponse(f.read(), 'image/png') f.close() m_path = reverse( 'appmonitor:measure', args=[kwargs["pk"], kwargs["mname"]] ) response.set_cookie("alarm_state", alarm, path=m_path) return response else: f = open('appmonitor/static/appmonitor/nodata.png', 'rb') response = HttpResponse(f.read(), 'image/png') f.close() return response
def init_query_list(request, annotatorID): t = template.Template(open('templates/init_queries.html').read()) tlist = list(Task.objects.filter(task_id__lte=12)) c = template.Context({'tasks': tlist, 'tasknum': len(tlist)}) response = HttpResponse(t.render(c)) response.set_cookie('annotatorID', value=annotatorID, max_age=None, expires=None, path='/', domain=None, secure=None) return response
def post(self, request, *args, **kwargs): if not request.is_ajax(): return HttpResponseBadRequest() else: if 'st_contact_city' not in request.POST: return HttpResponseBadRequest() else: st_contact_city = request.POST['st_contact_city'] try: curr_contact = Contact.objects.get(city=st_contact_city) contact_id = curr_contact.id except: curr_contact = False contact_id = False response = HttpResponse() if not curr_contact: cookies = request.COOKIES contact_id = False if 'st_contact_id' in cookies: contact_id = cookies['st_contact_id'] response.set_cookie('st_contact_id', contact_id, 1209600) return response
def login(req): try: response = HttpResponse() response.delete_cookie('username') except: pass if req.method == 'POST': uf = UserForm(req.POST) response = req.POST if uf.is_valid(): #获取表单用户密码 username = uf.cleaned_data['username'] password = uf.cleaned_data['password'] #获取的表单数据与数据库进行比较 user = User.objects.filter(username__exact = username,password__exact = password) if user: #比较成功,跳转index response = HttpResponseRedirect('/BookManage/index/') #将username写入浏览器cookie,失效时间为3600 response.set_cookie('username',username,3600) return response else: #比较失败,还在login return HttpResponseRedirect('/BookManage/login/') else: uf = UserForm() return render_to_response('login.html',{'uf':uf},context_instance=RequestContext(req))
def test_ip_address(self): response = HttpResponse() response.set_cookie(key='a', value='a', domain=None) # IP addresses should not be mutated request = self.factory.get('/', host='192.0.43.10') cookies = self.middleware.process_response(request, response).cookies self.assertEqual(cookies['a']['domain'], '')
def post(self,request, *args, **kwargs): count = smart_str(request.POST.get("count") ) dish_id =smart_str(request.POST["id"]); response = HttpResponse("yes") max_age =365 * 24 * 60 * 60 expires = datetime.datetime.strftime(datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age), "%a, %d-%b-%Y %H:%M:%S GMT") if request.COOKIES.get('dishes'): j = request.COOKIES['dishes'] json1 =json.loads(j) data =[] flag = False for one in json1: if one['dish_id'] ==dish_id: one['count']=count data.append(one) flag = True else: data.append(one) if not flag: item = {} item['dish_id']=dish_id item['count']=count data.append(item) response.set_cookie('dishes', json.dumps(data), max_age= max_age, expires=expires) else: json1 ={} json1['dish_id']=dish_id json1['count']=count response.set_cookie('dishes', json.dumps([json1,]), max_age= max_age, expires=expires) return response;
def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) if form.is_valid(): lang_code = request.POST.get('language', None) next = request.REQUEST.get('next', None) if request.is_ajax(): response = HttpResponse(json.dumps({'success': True}), mimetype='application/json') else: response = HttpResponseRedirect(next) if lang_code and check_for_language(lang_code): if hasattr(request, 'session'): request.session[settings.LANGUAGE_COOKIE_NAME] = lang_code else: response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code) return response if request.is_ajax(): errors = ' '.join(form.non_field_errors()) for fieldname, errorlist in form.errors.items(): if fieldname in form.fields: errors += ' ' + form.fields[fieldname].label + ': ' errors += ' '.join(errorlist) else: errors += ' '.join(errorlist) return HttpResponse(json.dumps({'success': False, 'error_message': errors}), mimetype='application/json') return self.form_invalid(form)
def test_cache_write_unpickable_object(self): update_middleware = UpdateCacheMiddleware() update_middleware.cache = cache fetch_middleware = FetchFromCacheMiddleware() fetch_middleware.cache = cache factory = RequestFactory() request = factory.get('/cache/test') request._cache_update_cache = True get_cache_data = FetchFromCacheMiddleware().process_request(request) assert get_cache_data is None response = HttpResponse() content = 'Testing cookie serialization.' response.content = content response.set_cookie('foo', 'bar') update_middleware.process_response(request, response) get_cache_data = fetch_middleware.process_request(request) assert get_cache_data is not None assert get_cache_data.content == content.encode('utf-8') assert get_cache_data.cookies == response.cookies update_middleware.process_response(request, get_cache_data) get_cache_data = fetch_middleware.process_request(request) assert get_cache_data is not None assert get_cache_data.content == content.encode('utf-8') assert get_cache_data.cookies == response.cookies
def render_to_response(request, template_name, context_dict={}, cookies={}): context = RequestContext(request, context_dict) t = loader.get_template(template_name) response = HttpResponse(t.render(context)) for k, v in cookies.items(): response.set_cookie(k, v) return response
def home(request): """ request: URL: get/token/anonymous POST: return: { "statusOk", 0 ou 1 "statusId", # Status (voire README) "statusName", # nom (description) du status } """ statusOk = 0 statusId = 200 statusName = "OK" try: response = HttpResponse() response.set_cookie("token", ""); response.set_cookie("nameormail", ""); except BaseException: print("Failed to se the the token...") text = { "statusOk": statusOk, "statusId": statusId, "statusName": statusName, } response.write(json.dumps(text)) # On converti le JSON en String pour le renvoyer return response
def upvote(request, video_shortlink): """Add an upvote to a video.""" response = HttpResponse(mimetype='application/json') if video_shortlink in request.COOKIES: response.status_code = 403 response.content = json.dumps({'error': 'already voted'}) return response video = get_object_or_none(Video, shortlink=video_shortlink) if video is not None: try: video.upvote() except socket.timeout: log.warning('Timeout connecting to celery to upvote video ' 'shortlink: %s' % video_shortlink) response.status_code = 500 response.content = json.dumps({'error': 'celery timeout'}) else: response.set_cookie(str(video_shortlink), value='1', httponly=False, max_age=settings.VOTE_COOKIE_AGE) response.content = json.dumps({'success': 'success'}) else: response.status_code = 404 response.content = json.dumps({'error': 'video not found'}) return response
def test_max_age_expiration(self): "Cookie will expire if max_age is provided" response = HttpResponse() response.set_cookie('max_age', max_age=10) max_age_cookie = response.cookies['max_age'] self.assertEqual(max_age_cookie['max-age'], 10) self.assertEqual(max_age_cookie['expires'], cookie_date(time.time()+10))
def syn_login(self,uid): ''' 同步登录 @param uid ''' #检查是否允许 if settings.API_SYNLOGIN: #获取对应用户 try: user=User.objects.extra(where=['reference_id=%s'],params=[uid])[0] username=user.username except: username='' # from django.contrib.auth import login,get_backends # backend=get_backends()[0] # user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__) # login(self.request,user) resp=HttpResponse() resp['P3P: CP']='CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR' value=Discuz.discuzAuthcodeEncode('%s,%s' % (uid,username), settings.API_KEY) resp.set_cookie(settings.UC_COOKIE_KEY, value, 86400*365,86400*365) return resp return HttpResponse(settings.API_RETURN_FORBIDDEN)
def loginForm(request): c=RequestContext(request) if request.method=='POST': # query=User.objects.filter(user=user) # result={} # if len(query)==0: # query=User.objects.filter(email=user) # if len(query)==0: # result['result']='userDoesNotExist' # if len(query)==1: # usersPassword=query[0].password # usersSalt=query[0].salt # if (hashlib.sha512(password+usersSalt).hexdigest()==usersPassword): # result['result']='OK' # else: # result['result']='invalidCredentials' # elif len(query)>1: # result['result']='somethingWentHorriblyWrong' user=request.POST.get('username') password=request.POST.get('password') persist=True if request.POST.get('persist')=='true' else False result=userHandling.login(user,password,persist) #Change this from false response=HttpResponse(json.dumps(result)) if (result['result']=='OK'): exp=None if persist: exp=datetime.date.today()+datetime.timedelta(14,0) print 'Expires:', print exp response.set_cookie('sessionId',result['sessionId'],path='/',expires=exp) return response
def test_cache_write_unpickable_object(self): update_middleware = UpdateCacheMiddleware() update_middleware.cache = self.cache fetch_middleware = FetchFromCacheMiddleware() fetch_middleware.cache = self.cache request = self._get_request_cache('/cache/test') get_cache_data = FetchFromCacheMiddleware().process_request(request) self.assertEqual(get_cache_data, None) response = HttpResponse() content = 'Testing cookie serialization.' response.content = content response.set_cookie('foo', 'bar') update_middleware.process_response(request, response) get_cache_data = fetch_middleware.process_request(request) self.assertNotEqual(get_cache_data, None) self.assertEqual(get_cache_data.content, content.encode('utf-8')) self.assertEqual(get_cache_data.cookies, response.cookies) update_middleware.process_response(request, get_cache_data) get_cache_data = fetch_middleware.process_request(request) self.assertNotEqual(get_cache_data, None) self.assertEqual(get_cache_data.content, content.encode('utf-8')) self.assertEqual(get_cache_data.cookies, response.cookies)
def get_messages(request): """ Get messages for the user """ import urlparse if request.user.is_authenticated(): msgs = BroadcastMessage.objects.current().for_auth_users() else: msgs = BroadcastMessage.objects.current().for_unauth_users() # exclude by those seen excluded_session = decode_excluded(request.session.get("excluded_broadcasts", "")) excluded_cookie = decode_excluded(request.COOKIES.get("excluded_broadcasts", "")) excluded = excluded_session | excluded_cookie msgs = msgs.exclude(pk__in=list(excluded)) # filter them by the HTTP_REFERER url_parts = urlparse.urlparse(request.META.get('HTTP_REFERER', '/')) path = url_parts.path valid_messages = [msg for msg in msgs if re.match(msg.url_target, path)] msg_list = [] for msg in valid_messages: msg_list.append(msg.msg_info()) if msg.show_frequency == BroadcastMessage.SHOW_ONCE: excluded_cookie.add(msg.pk) elif msg.show_frequency == BroadcastMessage.SHOW_ONCE_SESSION: excluded_session.add(msg.pk) request.session['excluded_broadcasts'] = encode_excluded(excluded_session) response = HttpResponse(json.dumps(msg_list), content_type="application/json") response.set_cookie('excluded_broadcasts', encode_excluded(excluded_cookie)) return response
def set_district(request): try: state = request.POST["state"] if state != "XX" and state not in us.statenames: raise Exception() district = int(request.POST["district"]) except: return HttpResponseBadRequest() # Who represents? from person.models import Person mocs = None if state != "XX": mocs = [p.id for p in Person.from_state_and_district(state, district)] # Form response. response = HttpResponse( json.dumps({ "status": "ok", "mocs": mocs }), content_type="application/json") if request.user.is_authenticated(): # Save to database. prof = request.user.userprofile() prof.congressionaldistrict = "%s%02d" % (state, district) prof.save() else: # Save in cookie. response.set_cookie("cong_dist", json.dumps({ "state": state, "district": district }), max_age=60*60*24*21) return response
def receive_code(request, uuid): task = get_object_or_404(Task.objects.select_related('course'), uuid=uuid) script = request.POST['sourcecode'] cookie_name = task.course.slug + '-locals' _locals = request.COOKIES.get(cookie_name, '') data = { 'script': script, 'tests': task.test_code, 'locals': _locals, 'filename': task.filename, 'file_content': task.file_content, } response = requests.post(settings.RUNNER_URL, data) result = json.loads(response.content) return_code = result['returncode'] if not return_code and task.success_message: result['message'] = task.success_message elif not return_code: result['message'] = MESSAGES[0] else: result['message'] = MESSAGES[1] content = json.dumps(result) response = HttpResponse(content=content, content_type='application/json') response.set_cookie(cookie_name, result['locals'], max_age=60*60) return response
def test_bad_cookie(self): """ Regression test for #18403 """ r = HttpResponse() r.set_cookie("a:.b/", 1) self.assertEqual(len(r.cookies.bad_cookies), 1)
def register(request): logger.info("request: %s", request) retDict = {} status = {'code':0,'description':'success'} sid = str() form = forms.UserForm(request.POST) if form.is_valid(): userName = form.cleaned_data['userName'] passWord = form.cleaned_data['passWord'] user = models.Info(user_name =userName, passWord=passWord) now = datetime.datetime.now() user.create_time = now user.update_time = now logger.info('注册用户:%s', user) user.save() #保存缓存key:user-sid,value:id conn = redis.Redis() sid = getSid(user.id, now) conn.set('user-'+sid,user.id) conn.expire('user-'+sid,60*60*24*7) result = {'userName':userName} retDict['result'] = result else: status['code'] = '10001' status['description'] = 'common-fail' retDict['result'] = {} retDict['status'] = status response = HttpResponse(json.dumps(retDict,ensure_ascii=False)) if sid: response.set_cookie('sid',sid) return response
def alerts_list(request): if not request.authenticated_email: return render(request, 'alerts/list_unauthenticated.html', {'title': 'Email alerts'}) user = User.objects.get(email=request.authenticated_email) if request.session.get('pending_alert'): Subscription.objects.get_or_create_by_query(request.session['pending_alert'], user) del request.session['pending_alert'] subscriptions = Subscription.objects.filter(user=user).select_related('topic') t = loader.get_template('alerts/list.html') c = RequestContext(request, { 'user': user, 'subscriptions': subscriptions, 'title': 'Your email alerts' }) resp = HttpResponse(t.render(c)) resp.set_cookie( key='enable-alerts', value='y', max_age=60*60*24*90, httponly=False ) return resp
def tryLogin(request): data = request.POST googleID = data['id'] response = HttpResponse("success") # Try to grab user from db if they have already logged in try: existingUser = User.objects.get(googleID=googleID) response.set_cookie('id', existingUser.googleID) except User.DoesNotExist: try: # otherwise, look for pre-created user to match precreatedUser = User.objects.get(email=data['emails[0][value]']) precreatedUser.name = data['displayName'] precreatedUser.image = data['result[image][url]'].split('?')[0] precreatedUser.googleID=googleID precreatedUser.save() response.set_cookie('id', googleID) response.set_cookie('first_login', True) except Exception as e: try: print "Exception: %s (user not in database)" % e # user is not in database at all name = data['displayName'] image = data['result[image][url]'].split('?')[0] email = data['emails[0][value]'] newUser = User(name=name, email=email, googleID=googleID, image=image, relevant_tags=[]) newUser.save() response.set_cookie('id', newUser.googleID) response.set_cookie('first_login', True) except Exception as e: print e except Exception as e: print "Exception: %s (unexpected error)" % e return response
def render_as_json(data_dict, cookie_dict=None): response = HttpResponse(json.dumps(data_dict), content_type='application/json') if cookie_dict: for k, v in cookie_dict.items(): response.set_cookie(k, v) return response
def email_login(request, user, email, password, remember, redirect_to=None): if not hasattr(user, 'backend'): user.backend = 'email_auth.backends.EmailBackend' from django.contrib.auth import login login(request, user) if request.session.test_cookie_worked(): request.session.delete_test_cookie() response = HttpResponse() # handle "remember me" cookie # effacer le cookie s'il existe response.delete_cookie('django_email_auth') if remember: try: cookie_data = encodestring('%s:%s' % (email, password)) max_age = 30 * 24 * 60 * 60 expires = datetime.datetime.strftime( datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age), "%a, %d-%b-%Y %H:%M:%S GMT" ) response.set_cookie('django_email_auth', cookie_data, max_age=max_age, expires=expires) except UnicodeEncodeError: pass # send signal "user just logged in" user_logged_in.send(sender=request.user, request=request) # retourner à la vue appelante response.status_code = 302 if redirect_to: response['Location'] = iri_to_uri(redirect_to) else: response['Location'] = settings.LOGIN_REDIRECT_URL return response
def set_color(request): if "fcolor" in request.GET: res = HttpResponse("Your color is %s" % (request.GET['fcolor'],)) res.set_cookie('fcolor', request.GET['fcolor']) return res else: return HttpResponse("You didn't give a color")
def main(request): flatpage = get_object_or_404(FlatPage, url = '/ladmin/') t = get_template('ladmin/main.html') html = t.render(Context(locals())) response = HttpResponse(html) response.set_cookie('IAmAdmin', 'true', max_age = 31536000) return response
def language(request, language='en-gb'): response = HttpResponse("setting language to %s" % language) response.set_cookie('lang', language) request.session['lang'] = language return response
def set_cookie2(request, key=None, value=None): response = HttpResponse('Cookie 有效時間1小時!') response.set_cookie(key, value, max_age=3600) return response
def cookie_set(request): response = HttpResponse("<h1>设置Cookie,请查看响应报文头</h1>") response.set_cookie('h1', 'test') print("234523452345") return response
def do_request(self, request, url, method, data): # HTTP call try: url = iri_to_uri(url) # Request creation proto, host, cgi, param, query = urlparse.urlparse(url)[:5] # manage proxies with authentication (get it from environment) proxy = None for proxy_name in settings.NOT_PROXY_FOR: if host.startswith(proxy_name): proxy = urllib2.ProxyHandler({}) # no proxy break if not proxy: #Host is not included in the NOT_PROXY_FOR list => proxy is needed! proxy = urllib2.ProxyHandler() # proxies from environment opener = urllib2.build_opener(proxy) # Adds original request Headers to the request headers = {} for header in request.META.items(): header_name = header[0].lower() if header_name == 'content_type' and header[1]: headers["content-type"] = header[1] elif header_name == 'cookie' or header_name == 'http_cookie': cookie_parser = Cookie.SimpleCookie(header[1]) # Remove EzWeb cookies if hasattr(settings, 'SESSION_COOKIE_NAME'): del cookie_parser[settings.SESSION_COOKIE_NAME] if hasattr( settings, 'CSRF_COOKIE_NAME' ) and settings.CSRF_COOKIE_NAME in cookie_parser: del cookie_parser[settings.CSRF_COOKIE_NAME] content = ', '.join([ cookie_parser[key].OutputString() for key in cookie_parser ]) if content != '': headers['Cookie'] = content elif self.http_headerRE.match( header_name ) and not header_name in self.blacklisted_http_headers: fixed_name = header_name.replace("http_", "", 1).replace('_', '-') headers[fixed_name] = header[1] protocolVersion = self.protocolRE.match( request.META['SERVER_PROTOCOL']) if protocolVersion != None: protocolVersion = protocolVersion.group(1) else: protocolVersion = '1.1' hostName = self.hostRE.match(request.META['HTTP_HOST']) if hostName != None: hostName = hostName.group(1) else: hostName = socket.gethostname() via_header = "%s %s (EzWeb-python-Proxy/1.1)" % (protocolVersion, hostName) headers["Via"] = via_header if (method == 'POST' or method == 'PUT') and not 'content-type' in headers: # Add Content-Type (Servlets bug) headers['content-type'] = "application/x-www-form-urlencoded" # Remote user header if not request.user.is_anonymous(): headers['Remote-User'] = request.user.username # Open the request try: res = self._do_request(opener, method, url, data, headers) except urllib2.URLError, e: if e.reason[0] == errno.ECONNREFUSED: return HttpResponse(status=504) else: return HttpResponseNotFound(e.reason) # Add content-type header to the response res_info = res.info() if ('Content-Type' in res_info): response = HttpResponse(res.read(), mimetype=res_info['Content-Type']) else: response = HttpResponse(res.read()) # Set status code to the response response.status_code = res.code # Add all the headers received from the response headers = res.headers for header in headers: header_lower = header.lower() if header_lower == 'set-cookie': cookie_parser = Cookie.SimpleCookie() cookies = res.headers.getheaders(header) for i in range(len(cookies)): cookie_parser.load(cookies[i]) for key in cookie_parser: response.set_cookie( key, cookie_parser[key].value, expires=cookie_parser[key]['expires'], path=cookie_parser[key]['path'], domain=cookie_parser[key]['domain']) elif header_lower == 'via': via_header = via_header + ', ' + headers[header] elif is_valid_header(header_lower): response[header] = headers[header] response['Via'] = via_header return response
def set_cookie(request): # 1. resp = HttpResponse("哦了") resp.set_cookie('aaa', 'bbb') return resp
def setcookie(request): response = HttpResponse("Cookie Set") response.set_cookie('sname', 'javatpoint.com') response.set_cookie('semail', '*****@*****.**') return response
def set_cookies(request): response = HttpResponse('set_cookies') # 创建response对象 response.set_cookie('name', '01') # 对象.set_cookie return response
def login_auth(request): print("X IN LOGIN AUTH") if (request.method != 'POST'): return redirect('/login') if (not (request.POST.get('email') and request.POST.get('password'))): #TODO error handling, give them error messages return redirect('/login') print("X IN LOGIN AUTH2") input_email = request.POST['email'] input_password = request.POST['password'] #see if provided credentials are legal TODO, length pass, is an eail, etc #query database for given email userResult = Calendo_User.objects.raw( 'SELECT * FROM webapp_calendo_user WHERE "Email"=%s', [request.POST['email']]) print("X IN LOGIN AUTH3") #if not exactly 1 row, error if (len(list(userResult)) != 1): print("oh shits") return redirect('/login?auth_failed=true&noUser=true') userOfInterest = userResult[0] print("X IN LOGIN AUTH4") #Hash given password. Check with database. error back if not right signer = Signer() input_password_enc = signer.sign(input_password) input_password_enc = input_password_enc[input_password_enc.find(":") + 1:] print("X IN LOGIN AUTH41") if (input_password_enc == userOfInterest.Password): print("X IN LOGIN AUTH42") #If still hasnt confrmed password, error it if (not (userOfInterest.isConfirmed)): #TODO let user know they have to confirm their email return render(request, 'webapp/home.html', {'userResult': userResult[0]}) #create token in database TODO print("X IN LOGIN AUTH5") session_token = login_token_generator() token_death_date = int(time.time()) + 60 * 2 insertSessionTokenResult = Session(SessionId=session_token, UserId=userOfInterest.id, UserEmail=userOfInterest.Email, DeathDate=token_death_date) insertSessionTokenResult.save() print("X IN LOGIN AUTH6") t = loader.get_template('webapp/home_redirect.html') c = {'userResult': userResult[0]} response = HttpResponse(t.render(c, request)) response.set_cookie('calendo_session_token', session_token) print("Cook that was set:") print("Cook that was set:") print("Cook that was set:") print("Cook that was set:") print("Cook that was set:") print("Cook that was set:") print(session_token) print("OH YES BABY") return response else: print("OH NOOOOOOOOO") return redirect('./home.html')
def switch_language(request): lang = request.GET.get("lang", None) translation.activate(lang) response = HttpResponse(status=200) response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang) return response
def set_cookie(request, key=None, value=None): response = HttpResponse('Cookie 儲存完畢!') response.set_cookie(key, value) return response
def test_max_age_int(self): response = HttpResponse() response.set_cookie("max_age", max_age=10.6) self.assertEqual(response.cookies["max_age"]["max-age"], 10)
#重新分析数据 cmd = 'cd {dir};python manage.py analysis -a url={url} -a name={name} -a guid={guid} -a ' \ 'product_id={product_id};'. \ format(url = url, name = 'jd', dir = settings.BASE_DIR, guid = data.get('guid'), product_id = product_id) subprocess.Popen(cmd, shell=True) else: data[ 'info'] = '传入网址有误,请检查后重新输入,请输入以下格式的网址:\n%s' % 'https://item.jd.com/3995645.html' except Exception, e: logging.error('run spider exception:%s' % e) data['info'] = '出现错误,错误原因:%s' % e response = HttpResponse(json.dumps(data), content_type="application/json") response.set_cookie('status', data.get('status')) response.set_cookie('guid', data.get('guid')) return response def randitem(request): data = { 'status': 'failure', 'guid': '0', 'info': '', } try: is_rand = request.POST.get('rand') if is_rand == 'true': data['status'] = 'success' data['guid'] = str(uuid.uuid4())
def test_max_age_timedelta(self): response = HttpResponse() response.set_cookie("max_age", max_age=timedelta(hours=1)) self.assertEqual(response.cookies["max_age"]["max-age"], 3600)
def setCookie_views(request): resp = HttpResponse('添加Cookie成功') resp.set_cookie('username', 'Wang Wc', 60 * 60 * 24 * 7) return resp
def test_unicode_cookie(self): """HttpResponse.set_cookie() works with Unicode data.""" response = HttpResponse() cookie_value = "清風" response.set_cookie("test", cookie_value) self.assertEqual(response.cookies["test"].value, cookie_value)
def process_response(self, request: HttpRequest, response: HttpResponse) -> HttpResponse: if getattr(response, "asynchronous", False): # This special Tornado "asynchronous" response is # discarded after going through this code path as Tornado # intends to block, so we stop here to avoid unnecessary work. return response try: request.get_host() except DisallowedHost: # If we get a DisallowedHost exception trying to access # the host, (1) the request is failed anyway and so the # below code will do nothing, and (2) the below will # trigger a recursive exception, breaking things, so we # just return here. return response if (not request.path.startswith("/static/") and not request.path.startswith("/api/") and not request.path.startswith("/json/")): subdomain = get_subdomain(request) if subdomain != Realm.SUBDOMAIN_FOR_ROOT_DOMAIN: try: get_realm(subdomain) except Realm.DoesNotExist: return render(request, "zerver/invalid_realm.html", status=404) """ If request.session was modified, or if the configuration is to save the session every time, save the changes and set a session cookie or delete the session cookie if the session has been emptied. """ try: accessed = request.session.accessed modified = request.session.modified empty = request.session.is_empty() except AttributeError: pass else: # First check if we need to delete this cookie. # The session should be deleted only if the session is entirely empty if settings.SESSION_COOKIE_NAME in request.COOKIES and empty: response.delete_cookie( settings.SESSION_COOKIE_NAME, path=settings.SESSION_COOKIE_PATH, domain=settings.SESSION_COOKIE_DOMAIN, ) else: if accessed: patch_vary_headers(response, ('Cookie', )) if (modified or settings.SESSION_SAVE_EVERY_REQUEST) and not empty: if request.session.get_expire_at_browser_close(): max_age = None expires = None else: max_age = request.session.get_expiry_age() expires_time = time.time() + max_age expires = http_date(expires_time) # Save the session data and refresh the client cookie. # Skip session save for 500 responses, refs #3881. if response.status_code != 500: try: request.session.save() except UpdateError: raise SuspiciousOperation( "The request's session was deleted before the " "request completed. The user may have logged " "out in a concurrent request, for example.") host = request.get_host().split(':')[0] # The subdomains feature overrides the # SESSION_COOKIE_DOMAIN setting, since the setting # is a fixed value and with subdomains enabled, # the session cookie domain has to vary with the # subdomain. session_cookie_domain = host response.set_cookie( settings.SESSION_COOKIE_NAME, request.session.session_key, max_age=max_age, expires=expires, domain=session_cookie_domain, path=settings.SESSION_COOKIE_PATH, secure=settings.SESSION_COOKIE_SECURE or None, httponly=settings.SESSION_COOKIE_HTTPONLY or None, samesite=settings.SESSION_COOKIE_SAMESITE, ) return response
def test_unicode_cookie(self): "Verify HttpResponse.set_cookie() works with unicode data." response = HttpResponse() cookie_value = '清風' response.set_cookie('test', cookie_value) self.assertEqual(force_str(cookie_value), response.cookies['test'].value)
class AffectMiddlewareResponseTest(TestCase): def setUp(self): self.criteria = Criteria.objects.create( name='test_crit', max_cookie_age=0) self.request = RequestFactory().get('') self.request.affected_persist = {} self.response = HttpResponse('test response') self.mw = AffectMiddleware() self.mock = mox.Mox() def tearDown(self): self.mock.UnsetStubs() def test_persist_cookie(self): self.request.affected_persist[self.criteria] = True self.mock.StubOutWithMock(self.response, 'set_cookie') self.response.set_cookie( 'dac_test_crit', value=True, max_age=None, secure=False) self.mock.ReplayAll() resp = self.mw.process_response(self.request, self.response) self.mock.VerifyAll() self.assertEqual(resp.content, 'test response') def test_persist_cookie_with_max_age(self): self.criteria.max_cookie_age = 1200 self.request.affected_persist[self.criteria] = False self.mock.StubOutWithMock(self.response, 'set_cookie') self.response.set_cookie( 'dac_test_crit', value=False, max_age=1200, secure=False) self.mock.ReplayAll() resp = self.mw.process_response(self.request, self.response) self.mock.VerifyAll() self.assertEqual(resp.content, 'test response') def test_testing_cookie(self): self.request.affected_tests = {self.criteria: True} self.mock.StubOutWithMock(self.response, 'set_cookie') self.response.set_cookie( 'dact_test_crit', value=True, max_age=None, secure=False) self.mock.ReplayAll() resp = self.mw.process_response(self.request, self.response) self.mock.VerifyAll() self.assertEqual(resp.content, 'test response') def test_testing_cookie_with_max_age(self): self.criteria.max_cookie_age = 1200 self.request.affected_tests = {self.criteria: False} self.mock.StubOutWithMock(self.response, 'set_cookie') self.response.set_cookie( 'dact_test_crit', value=False, max_age=1200, secure=False) self.mock.ReplayAll() resp = self.mw.process_response(self.request, self.response) self.mock.VerifyAll() self.assertEqual(resp.content, 'test response')
def set_cookie(request): resp = HttpResponse('成功响应数据到客户端') expires = 60 * 60 * 24 * 365 resp.set_cookie('USERID', '66998877', expires) return resp
def login(request): # 開啟影片檔案 cap = cv2.VideoCapture(0) # Dlib 的人臉偵測器 detector = dlib.get_frontal_face_detector() # 以迴圈從影片檔案讀取影格,並顯示出來 while (1): ret, frame = cap.read() # 偵測人臉 face_rects, scores, idx = detector.run(frame, 0) # 取出所有偵測的結果 for i, d in enumerate(face_rects): x1 = d.left() y1 = d.top() x2 = d.right() y2 = d.bottom() text = "%2.2f(%d)" % (scores[i], idx[i]) # 以方框標示偵測的人臉 cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 4, cv2.LINE_AA) # 標示分數 # cv2.putText(frame, text, (x1, y1), cv2.FONT_HERSHEY_DUPLEX, # 0.7, (255, 255, 255), 1, cv2.LINE_AA) # 顯示結果 cv2.imshow("face detect & take photo", frame) if cv2.waitKey(20) & 0xFF == ord(' '): cv2.imwrite("./photo/static/images/pred.jpg", frame) break #將檔案上傳至Linux t = paramiko.Transport((ip, 22)) t.connect(username=account, password=password) sftp = paramiko.SFTPClient.from_transport(t) remotepath = '/home/' + account + '/test/test-data/pred.jpg' localpath = './photo/static/images/pred.jpg' sftp.put(localpath, remotepath) #上传文件 sftp.close() t.close() ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip, 22, account, password) stdin, stdout, stderr = ssh.exec_command( "cd test/; python3 Face-Recognition-Predect.py labels.txt") getname = stdout.readlines() ssh.close() # print(getname) getname = getname[-3].split()[0][:-4] # print(getname[:-4]) name = {} if getname == 'Predic': name["name"] = 'error' response = HttpResponse( "<script>alert('登入失敗,請看著鏡頭重新登入');location.href='/photo/login'</script>" ) print('Face Error') else: name["name"] = getname response = HttpResponse( "<script>alert('Hi! " + getname + "');location.href='/member/memberarea'</script>") response.set_cookie("name", getname) print(getname) print('登入成功') return response
def cookie_set(request): response = HttpResponse("<h1>设置Cookie,请查看响应报文头</h1>") response.set_cookie('h1', 'ki') return response
def language(request, language='it'): response = HttpResponse("setting language to %s" % language) response.set_cookie('lang', language) request.session['lang'] = language return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
def setcookie(request): response = HttpResponse("Cookie Set") response.set_cookie("java", "python") return response
def set_cookie(request): response = HttpResponse('cookie save') response.set_cookie('name', 'le', max_age=10) return response
def cnmm(req: HttpRequest): resp = HttpResponse() resp.set_cookie(key='xlly_s', value=1, secure=True) return resp
def remember_ip_address(request): ip_address = request.GET['ip_address'] resp = HttpResponse() resp.set_cookie('ip_address', ip_address) return resp
def user_cookie(request): response = HttpResponse('ok') response.set_cookie('name', 'gy', max_age=3600) return response
def setcookie(request): html = HttpResponse("<h1>Dataflair Django Tutorial</h1>") html.set_cookie('dataflair', 'Hello this is your Cookies', max_age=None) return html
def set_cookie(request): rsp = HttpResponse() rsp.set_cookie('username', 'fanxiaowei', 3600) return rsp
def call_wsgi_app(wsgi_app, request, path_info): """ Call the ``wsgi_app`` with ``request`` and return its response. :param wsgi_app: The WSGI application to be run. :type wsgi_app: callable :param request: The Django request. :type request: :class:`django_wsgi.handler.DjangoWSGIRequest` :param path_info: The ``PATH_INFO`` to be used by the WSGI application. :type path: :class:`basestring` :raises django_wsgi.exc.ApplicationCallError: If ``path_info`` is not the last portion of the ``PATH_INFO`` in ``request``. :return: The response from the WSGI application, turned into a Django response. :rtype: :class:`django.http.HttpResponse` """ webob_request = request.webob new_request = webob_request.copy() # Moving the portion of the path consumed by the current view, from the # PATH_INTO to the SCRIPT_NAME: if not request.path_info.endswith(path_info): raise ApplicationCallError("Path %s is not the last portion of the " "PATH_INFO in the original request (%s)" % (path_info, request.path_info)) consumed_path = request.path_info[:-len(path_info)] new_request.path_info = path_info new_request.script_name = webob_request.script_name + consumed_path # If the user has been authenticated in Django, log him in the WSGI app: if request.user.is_authenticated: new_request.remote_user = request.user.username # Cleaning the routing_args, if any. The application should have its own # arguments, without relying on any arguments from a parent application: if "wsgiorg.routing_args" in request.environ: del new_request.environ['wsgiorg.routing_args'] # And the same for the WebOb ad-hoc attributes: if "webob.adhoc_attrs" in request.environ: del new_request.environ['webob.adhoc_attrs'] # Calling the WSGI application and getting its response: (status_line, headers, body) = new_request.call_application(wsgi_app) status_code_raw = status_line.split(" ", 1)[0] status_code = int(status_code_raw) # Turning its response into a Django response: cookies = SimpleCookie() django_response = HttpResponse(body, status=status_code) for (header, value) in headers: if header.upper() == "SET-COOKIE": if PY2 and isinstance(value, text_type): # It can't be Unicode: value = value.encode("us-ascii") cookies.load(value) else: django_response[header] = value # Setting the cookies from Django: for (cookie_name, cookie) in cookies.items(): cookie_attributes = { 'key': cookie_name, 'value': cookie.value, 'expires': cookie['expires'], 'path': cookie['path'], 'domain': cookie['domain'], } if cookie['max-age']: # Starting in Django 1.3 it performs arithmetic operations # with 'Max-Age' cookie_attributes['max_age'] = int(cookie['max-age']) django_response.set_cookie(**cookie_attributes) return django_response
def get_response(status,set,cookie): httpresponse = HttpResponse(set) httpresponse.status=status for key in cookie: httpresponse.set_cookie(key,cookie[key]) return httpresponse