本文整理汇总了Python中rest_framework.response.Response.set_cookie方法的典型用法代码示例。如果您正苦于以下问题:Python Response.set_cookie方法的具体用法?Python Response.set_cookie怎么用?Python Response.set_cookie使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rest_framework.response.Response
的用法示例。
在下文中一共展示了Response.set_cookie方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: post
# 需要导入模块: from rest_framework.response import Response [as 别名]
# 或者: from rest_framework.response.Response import set_cookie [as 别名]
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
if serializer.is_valid():
user = serializer.object.get('user') or request.user
token = serializer.object.get('token')
response_data = jwt_response_payload_handler(token, user, request)
response = Response(response_data)
response.data = {
'token': token,
'user':{
'alias': user.alias,
'email': user.email
}
}
if api_settings.JWT_AUTH_COOKIE:
expiration = (datetime.utcnow() +
api_settings.JWT_EXPIRATION_DELTA)
response.set_cookie(api_settings.JWT_AUTH_COOKIE,
token,
expires=expiration,
httponly=True)
return response
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
示例2: get
# 需要导入模块: from rest_framework.response import Response [as 别名]
# 或者: from rest_framework.response.Response import set_cookie [as 别名]
def get(self, request, *args, **kw):
ip = args[0]
details_request = IPDetails(ip, *args, **kw)
result = DetailsSerializer(details_request)
response = Response(result.data, status=status.HTTP_200_OK)
visit = Visit()
visit.endpoint = '/api/details/' + ip
visit.timestamp = get_epoch_timestamp()
visit.address = get_ip(request)
cookie = request.COOKIES.get("alienvaultid", None)
if cookie is None:
ck_val = create_random_string()
# set this cookie to expire in one year
response.set_cookie('alienvaultid', ck_val, max_age=31536000)
visitor = Visitor()
visitor.alienvaultid = ck_val
visitor.save()
else:
visitor = Visitor.objects.get(alienvaultid=cookie)
visit.visitor_id = visitor.id
visit.save()
return response
示例3: get_response
# 需要导入模块: from rest_framework.response import Response [as 别名]
# 或者: from rest_framework.response.Response import set_cookie [as 别名]
def get_response(self):
serializer_class = self.get_response_serializer()
if getattr(settings, 'REST_USE_JWT', False):
data = {
'user': self.user,
'token': self.token
}
serializer = serializer_class(instance=data,
context={'request': self.request})
else:
serializer = serializer_class(instance=self.token,
context={'request': self.request})
response = Response(serializer.data, status=status.HTTP_200_OK)
if getattr(settings, 'REST_USE_JWT', False):
from rest_framework_jwt.settings import api_settings as jwt_settings
if jwt_settings.JWT_AUTH_COOKIE:
from datetime import datetime
expiration = (datetime.utcnow() + jwt_settings.JWT_EXPIRATION_DELTA)
response.set_cookie(jwt_settings.JWT_AUTH_COOKIE,
self.token,
expires=expiration,
httponly=True)
return response
示例4: post
# 需要导入模块: from rest_framework.response import Response [as 别名]
# 或者: from rest_framework.response.Response import set_cookie [as 别名]
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
token, created = Token.objects.get_or_create(user=user)
auth_login(request, user)
response = Response({'token': token.key})
csrf_token = _get_new_csrf_string()
response.set_cookie('csrftoken', csrf_token)
return response
示例5: post
# 需要导入模块: from rest_framework.response import Response [as 别名]
# 或者: from rest_framework.response.Response import set_cookie [as 别名]
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data,
context={'request': request})
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
token, _ = Token.objects.get_or_create(user=user)
response = Response({'token': token.key})
if request.data.get('login'):
auth_login(self.request, user)
response.set_cookie('token', value=token)
response.set_cookie('user', value=user.username)
return response
示例6: create
# 需要导入模块: from rest_framework.response import Response [as 别名]
# 或者: from rest_framework.response.Response import set_cookie [as 别名]
def create(self, request):
# Read private key
private_key = request.POST.get('private_key', None)
if private_key is None:
return HttpResponseBadRequest(ERR_PRIVKEY_MISSING)
# Validate user key
try:
user_key = UserKey.objects.get(user=request.user)
except UserKey.DoesNotExist:
return HttpResponseBadRequest(ERR_USERKEY_MISSING)
if not user_key.is_active():
return HttpResponseBadRequest(ERR_USERKEY_INACTIVE)
# Validate private key
master_key = user_key.get_master_key(private_key)
if master_key is None:
return HttpResponseBadRequest(ERR_PRIVKEY_INVALID)
try:
current_session_key = SessionKey.objects.get(userkey__user_id=request.user.pk)
except SessionKey.DoesNotExist:
current_session_key = None
if current_session_key and request.GET.get('preserve_key', False):
# Retrieve the existing session key
key = current_session_key.get_session_key(master_key)
else:
# Create a new SessionKey
SessionKey.objects.filter(userkey__user=request.user).delete()
sk = SessionKey(userkey=user_key)
sk.save(master_key=master_key)
key = sk.key
# Encode the key using base64. (b64decode() returns a bytestring under Python 3.)
encoded_key = base64.b64encode(key).decode()
# Craft the response
response = Response({
'session_key': encoded_key,
})
# If token authentication is not in use, assign the session key as a cookie
if request.auth is None:
response.set_cookie('session_key', value=encoded_key)
return response
示例7: edit_profile
# 需要导入模块: from rest_framework.response import Response [as 别名]
# 或者: from rest_framework.response.Response import set_cookie [as 别名]
def edit_profile(request):
user = None
Sizzler = UserSizzler
json_data = request.JSON()
if request.user.is_authenticated():
user = request.user
Sizzler = UserUpdateSizzler
if json_data:
sizzle = Sizzler(user, data=json_data)
if sizzle.is_valid():
obj = sizzle.save()
if user is None:
obj.set_password(sizzle.validated_data['password'])
obj.save()
obj = authenticate(
username=sizzle.validated_data['username'],
password=sizzle.validated_data['password'])
login(request, obj)
else:
if 'password' in sizzle.validated_data:
obj.set_password(sizzle.validated_data['password'])
obj.save()
update_session_auth_hash(request, obj)
value = 'user'
if obj.phone and obj.biography:
value = 'speaker'
obj.send_verify(request, json_data['conf'])
response = Response({'status': 'OK'}, status=200)
response.set_cookie('angular_logged_in', value=value, httponly=False)
return response
else:
return Response({'errors': sizzle.errors}, status=400)
else:
sizzle = Sizzler(user)
return Response(sizzle.data, status=200)
示例8: create
# 需要导入模块: from rest_framework.response import Response [as 别名]
# 或者: from rest_framework.response.Response import set_cookie [as 别名]
def create(self, request, *args, **kwargs):
"""
Perform user login operation.
"""
serializer = self.get_serializer(data=request.DATA)
if serializer.is_valid():
user = serializer.validated_data['user']
if not user:
raise AuthenticationFailed(_('Bad credentials'))
login(request, user)
user_serializer = UserSerializer(user,
context={'request': request})
response = Response(user_serializer.data,
status=status.HTTP_201_CREATED)
if serializer.validated_data['remember_me']:
# Find user's access tokens
tokens = RememberMeToken.objects.filter(
user=user
).order_by('created')
# Remove oldest token
if tokens.count() == 5:
tokens[0].delete()
# Create new remember me token
token = RememberMeToken.objects.create(
user=user
)
response.set_cookie('remember_me_token',
value=token.key,
httponly=True,
expires=token.expiration)
return response
raise ParseError(serializer.errors)
示例9: login_view
# 需要导入模块: from rest_framework.response import Response [as 别名]
# 或者: from rest_framework.response.Response import set_cookie [as 别名]
def login_view(request):
json_data = request.JSON()
user = authenticate(
username=json_data.get('username'),
password=json_data.get('password'))
if user:
login(request, user)
value = 'user'
if user.phone and user.biography:
value = 'speaker'
response = Response({'status': 'OK'}, status=200)
response.set_cookie('angular_logged_in', value=value, httponly=False)
return response
return Response(
{'errors': {'username': ['Username or Password is incorrect.']}},
status=400)
示例10: get
# 需要导入模块: from rest_framework.response import Response [as 别名]
# 或者: from rest_framework.response.Response import set_cookie [as 别名]
def get(self, request, ip, *args, **kw):
"""
:param ip: str of the ip address the user wants a threat report for
:return: IPDetails
"""
ip_details = IPDetails(ip, *args, **kw)
serialize = DetailsSerializer(ip_details)
response = Response(serialize.data, status=status.HTTP_200_OK)
cookie = request.COOKIES.get(settings.COOKIE_NAME, None)
if cookie is None:
alien_vault = AlienVault()
else:
try:
alien_vault = AlienVault.objects.filter(alien_vault_id=cookie).get()
except:
alien_vault = AlienVault()
alien_vault.total_count += 1
alien_vault.valid_count += ip_details.is_valid and 1 or 0
alien_vault.error_count += ip_details.http_code > 299 and 1 or 0
alien_vault.save()
TrackVisits(alien_vault=alien_vault,
address = get_ip(request),
endpoint='api/threat/ip/%s'%ip).save()
expires = datetime.datetime.utcnow() + datetime.timedelta(seconds=settings.COOKIE_LIFETIME)
response.set_cookie(settings.COOKIE_NAME,
alien_vault.alien_vault_id,
max_age=settings.COOKIE_LIFETIME,
expires=expires.strftime('%a, %d-%b-%Y %H:%M:%S GMT'),
domain=settings.COOKIE_DOMAIN,
secure = settings.COOKIE_SECURE or None)
return response
示例11: get
# 需要导入模块: from rest_framework.response import Response [as 别名]
# 或者: from rest_framework.response.Response import set_cookie [as 别名]
def get(self, request, *args, **kwargs):
ip = kwargs['ip']
# User's source address
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
user_addr = x_forwarded_for.split(',')[0]
else:
user_addr = request.META.get('REMOTE_ADDR')
# Generate IPDetails object for serialization
details_request = IPDetails(ip, *args, **kwargs)
# Serialize object
result = DetailsSerializer(details_request)
response = Response(result.data, status=status.HTTP_200_OK)
# Set UTC time
current_datetime = datetime.utcnow()
epoch = int((current_datetime - datetime(1970, 1, 1)).total_seconds())
expires = addYear(current_datetime, 1)
# Handle Cookies
if 'alienvaultid' in request.COOKIES:
avid = request.COOKIES['alienvaultid']
response.set_cookie('last_visit', epoch, expires=expires)
else:
# Didn't find cookie, set one.
avid = ''.join(["%s" % random.randint(0, 9)
for num in range(0, 11)])
response.set_cookie('alienvaultid', avid, expires=expires)
response.set_cookie('last_visit', epoch, expires=expires)
user = User(alienvaultid=avid)
user.save()
visit = Visit(user=user,
address=user_addr,
timestamp=epoch,
endpoint=kwargs['endpoint'] + ip)
visit.save()
return response