本文整理汇总了Python中django.shortcuts.HttpResponse.set_cookie方法的典型用法代码示例。如果您正苦于以下问题:Python HttpResponse.set_cookie方法的具体用法?Python HttpResponse.set_cookie怎么用?Python HttpResponse.set_cookie使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.shortcuts.HttpResponse
的用法示例。
在下文中一共展示了HttpResponse.set_cookie方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: watch
# 需要导入模块: from django.shortcuts import HttpResponse [as 别名]
# 或者: from django.shortcuts.HttpResponse import set_cookie [as 别名]
def watch(request):
response = HttpResponse(status=200)
session = request.COOKIES.get('_sc', None)
if not session:
session = uuid.uuid4().hex
response.set_cookie('_sc', session, max_age=60 * 60 * 24 * 365)
http_referer = request.META.get('HTTP_REFERER', None)
if not http_referer:
return response
url_parts = urlparse(http_referer)
path_parts = utils.strip_path(url_parts.path)
if len(path_parts) > 1:
path = path_parts[1]
else:
path = path_parts[0]
ignore = False
query = url_parts.query
url_hash = hashlib.md5((path + query).encode('utf-8')).hexdigest()
before = (datetime.datetime.now() - datetime.timedelta(minutes=URL_TIMEOUT))
# if models.PageView.objects.filter(datetime__gt=before, session=session, url_hash=url_hash).exists():
# ignore = True
user = None
if request.user.is_authenticated():
user = request.user
if session and not ignore:
models.log_page_view(path=path, query=query, url_hash=url_hash, session=session, user=user)
return response
示例2: add_to_cart
# 需要导入模块: from django.shortcuts import HttpResponse [as 别名]
# 或者: from django.shortcuts.HttpResponse import set_cookie [as 别名]
def add_to_cart(request, tmplate_name = "index22.html"):
if request.user.is_authenticated():
postdata = request.POST.copy()
prod_name = postdata.get('prod_name', '')
power = float(postdata.get('opt_power','').replace(',','.'))
rad = float(postdata.get('radius','').replace(',','.'))
queryset = Linses.objects.all()
queryset = queryset.filter(fk_product__product_name__exact = prod_name)
queryset = queryset.filter(optical_power__exact = power)
queryset = queryset.filter(radius_of_cutvature__exact = rad)
qr = Product.objects.get(product_name = prod_name)
qs = qr.pk_product_id
request.session.__setitem__('cart', False)
# qs = qr.fk_product.pk_product_id
response = HttpResponse()
response.set_cookie('cart', value=False)
if request.session['cart'] == False:
us = request.user.id
aus = AuthUser.objects.get(id = us)
order1 = Order(order_status = 5, order_date = datetime.date.today(), fk_user = aus )
order1.save()
i = order1.pk_order_id
request.session["cart"] = True
request.session.__setitem__('cart_id', i)
order_prod1 = OrderProduct(fk_order = Order.objects.get(pk_order_id = i), fk_product = qr)
product_for_saving = Product.objects.get(pk_product_id = qs)
product_for_saving.balance = F('balance') - 1
product_for_saving.save()
order_prod1.save()
return render_to_response(template_name="index22.html")
return render_to_response()
示例3: set_color
# 需要导入模块: from django.shortcuts import HttpResponse [as 别名]
# 或者: from django.shortcuts.HttpResponse import set_cookie [as 别名]
def set_color(request):
if "favorite_color" in request.GET:
favorite_color=request.GET['favorite_color']
# Create an HttpResponse object...
response = HttpResponse("Your favorite color is now %s" %request.GET["favorite_color"])
# ... and set a cookie on the response
response.set_cookie("favorite_color",
request.GET["favorite_color"])
#return response
return render_to_response('color_form.html',{ 'favorite_color': favorite_color})
elif"favorite_color" in request.COOKIES:
#return HttpResponse("Your favorite color is %s" %request.COOKIES["favorite_color"])
return render_to_response('color_form.html', {'favorite_color': request.COOKIES["favorite_color"]})
else:
#return HttpResponse("You didn't give a favorite color.")
return render_to_response('color_form.html')
示例4: wish
# 需要导入模块: from django.shortcuts import HttpResponse [as 别名]
# 或者: from django.shortcuts.HttpResponse import set_cookie [as 别名]
def wish(request):
if is_login(request):
obj=wishlist()
obj.ou_id=userac.objects.get(u_id=request.GET['u'])
obj.op_id=product.objects.get(p_id=request.GET['p'])
obj.qty=1
obj.save()
return HttpResponse("ok wishlist added "+request.GET['p']+" "+request.GET['u'])
else:
obj=HttpResponse("ok wishlist added "+request.GET['p']+" "+request.GET['u'])
if "wishitem" in request.COOKIES:
pr=request.COOKIES['wishitem']
pr+=","+request.GET['p']
else:
pr=""+request.GET['p']
obj.set_cookie("wishitem",pr)
return obj
示例5: cartadd
# 需要导入模块: from django.shortcuts import HttpResponse [as 别名]
# 或者: from django.shortcuts.HttpResponse import set_cookie [as 别名]
def cartadd(request):
if is_login(request):
obj=cart()
obj.ou_id=userac.objects.get(u_id=request.GET['u'])
obj.op_id=product.objects.get(p_id=request.GET['p'])
obj.qty=1
obj.save()
return HttpResponse("ok cart added "+request.GET['p']+" "+request.GET['u'])
else:
obj=HttpResponse("ok cart added "+request.GET['p']+" "+request.GET['u'])
if "product" in request.COOKIES:
pr=request.COOKIES['product']
pr+=","+request.GET['p']
else:
pr=""+request.GET['p']
obj.set_cookie("product",pr)
return obj
示例6: activate_by_url
# 需要导入模块: from django.shortcuts import HttpResponse [as 别名]
# 或者: from django.shortcuts.HttpResponse import set_cookie [as 别名]
def activate_by_url(request):
response = HttpResponse()
if 'subscriber' in request.COOKIES:
subscriber_id = request.COOKIES['subscriber']
try:
subscriber = Subscribers.objects.get(subscriber_id=subscriber_id)
if subscriber.state is not CONFIRMED:
subscriber.state = CONFIRMED
subscriber.save()
# Начисление вознаграждения партнеру
make_reward_for(subscriber)
response.set_cookie('subscriber', None, 0, '/')
except Subscribers.DoesNotExist:
pass
return response
示例7: get_file
# 需要导入模块: from django.shortcuts import HttpResponse [as 别名]
# 或者: from django.shortcuts.HttpResponse import set_cookie [as 别名]
def get_file(request, fid):
"""
Handle file download. @param fid is the id of the file to
be downloaded. If the file is protected, the password given
as POST or GET parameter is checked before returning the file.
"""
# Check password
ok, val = check_pwd(request, fid, reverse('get_file', kwargs={ 'fid': fid}))
if not ok:
return val
# Get file description
f = File.objects.get(id=fid)
# Increase number of downloads
f.nb_dl += 1
f.save()
# Send file
content = ""
if f.iv is not None:
content = decrypt_file(f, request.GET["key"])
try:
# Decrypt filename
fname = decrypt_filename(f.title, val, f.iv)
except Exception:
fname = f.title
else:
fname = f.title
with open(f.path, 'rb+') as fl:
content = fl.read()
response = HttpResponse(content_type=mimetypes.guess_type(f.title)[0], content=content)
response['Content-Disposition'] = 'attachment; filename="%s"' % smart_str(fname)
response['Content-Length'] = f.size
response.set_cookie(key="fileReady", value=1, path="/dl")
# If the file has reached the max number of dl
if f.nb_dl >= f.max_dl:
# We delete it
f.delete()
pass
return response
示例8: oauth
# 需要导入模块: from django.shortcuts import HttpResponse [as 别名]
# 或者: from django.shortcuts.HttpResponse import set_cookie [as 别名]
def oauth(request):
"""网页授权获取用户信息"""
resp = HttpResponse(request.openid)
resp.set_cookie("openid", Helper.sign_cookie(request.openid))
return resp
示例9: subscribe
# 需要导入模块: from django.shortcuts import HttpResponse [as 别名]
# 或者: from django.shortcuts.HttpResponse import set_cookie [as 别名]
def subscribe(request, project_id):
response = HttpResponse()
if project_id and request.method == 'POST':
if 'delivery_id' in request.POST and 'field_name' in request.POST and 'field_email' in request.POST:
client_ip = get_client_ip(request)
# Информация с формы подписки
first_name = request.POST['field_name']
last_name = request.POST.get('field_last_name', '')
email = request.POST['field_email']
delivery_id = request.POST['delivery_id']
partner_id = request.COOKIES.get('partner', None)
try:
partner = User.objects.get(id=partner_id)
except User.DoesNotExist:
partner = None
view_time = request.POST.get('view_time', None)
view_time = int(view_time) if (isinstance(view_time, unicode) and view_time.isdigit()) else None
visitor = Visitors.objects.filter(ip_address=client_ip)[:1:-1]
referer = visitor[0].referer if len(visitor) == 1 else None
project = Projects.objects.get(id=project_id)
state = UNCONFIRMED
url = 'http://send.email-master.ru/sdk/examples/subscribe.php' + \
'?delivery_id=' + delivery_id + \
'&email=' + email + \
'&fname=' + first_name + \
'&lname=' + last_name
subscribe_response = urlopen(url)
subscribe_response_read = subscribe_response.read()
subscribe_result = json.loads(subscribe_response_read)
if subscribe_result['status'] == 'success':
# Получаем id нового подписчика
url = 'http://send.email-master.ru/sdk/examples/get_subscriber.php' + \
'?delivery_id=' + delivery_id + \
'&email=' + email
get_subscriber_response = urlopen(url)
get_subscriber_response_read = get_subscriber_response.read()
get_subscriber_result = json.loads(get_subscriber_response_read)
response = redirect(project.url_forward)
if get_subscriber_result['status'] == 'success':
subscriber_id = get_subscriber_result['data']['subscriber_uid']
# Записываем подписчика в таблицу с подписчиками
Subscribers.objects.create(project=project,
delivery_id=delivery_id,
partner=partner,
subscriber_id=subscriber_id,
email=email,
ip=client_ip,
referer=referer,
view_time=view_time,
state=state)
if project.check == URL:
response.set_cookie('subscriber', subscriber_id)
else:
response = HttpResponse('Во время подписки произошла ошибка! Введите другой E-mail адрес!')
return response
示例10: get_works_json
# 需要导入模块: from django.shortcuts import HttpResponse [as 别名]
# 或者: from django.shortcuts.HttpResponse import set_cookie [as 别名]
#.........这里部分代码省略.........
#if checked pending filter
q_obj_p = Q(work_start_date__lte = query_time) &\
Q(work_end_date__gt = query_time)\
if work_filter_pending == "true" else Q()
#if checked upcoming filter
q_obj_u = Q(work_start_date__gt = query_time)\
if work_filter_upcoming == "true" else Q()
#if checked completed filter
q_obj_c = Q(work_end_date__lt = query_time)\
if work_filter_completed == "true" else Q()
#if work number in filter
q_obj_df = Q(work_number__icontains = work_filter_number)\
if work_filter_number else Q()
#if work date filter from
if work_filter_from:
work_from_date = datetime.date(*[int(x) for x in work_filter_from.split("-")])
q_obj_ff = Q(work_start_date__gte = work_from_date)
else:
q_obj_ff = Q()
#if work date filter to
if work_filter_to:
work_to_date = datetime.date(*[int(x) for x in work_filter_to.split("-")])
q_obj_ft = Q(work_start_date__lte = work_to_date)
else:
q_obj_ft = Q()
work_objects = Work.objects.filter(q_obj_p | q_obj_u | q_obj_c).filter(q_obj_df).filter(q_obj_ff).filter(q_obj_ft)
list_works=[]
for work in work_objects:
dict_work={}
dict_work["slug"] = work.slug
dict_work["work_number"] = work.work_number
lang_obj = Language.objects.get(language_name=lang)
dict_work["work_type"] = WorkTypeDescription.objects.get(worktype=work.work_type, worktypelang=lang_obj).worktypedesc
dict_work["work_region"] = WorkRegionDescription.objects.get(workregionlang = lang_obj, workregion=work.work_region).workregdesc
dict_work["work_created_date"] = work.work_added.astimezone(local_tz).strftime('%d.%m.%Y %H:%M')
q_obj_filter_by_work = Q(notification_work__slug=work.slug)
q_obj_notif_type_n = Q(notification_type__notificationtype_name="notification")
q_obj_notif_type_c = Q(notification_type__notificationtype_name="cancel")
q_obj_notif_state_init = Q(notification_state__notificationstate_name="init")
q_obj_notif_state_sent = Q(notification_state__notificationstate_name="sent")
q_obj_notif_state_sent_err = Q(notification_state__notificationstate_name="sent_error")
q_obj_notif_state_init = Q(notification_state__notificationstate_name="init")
#notifications = Notification.objects.filter(notification_work__slug=work.slug)
init_notifications = Notification.objects.filter(q_obj_filter_by_work &\
q_obj_notif_state_init&\
q_obj_notif_type_n).count()
sent_notifications = Notification.objects.filter(q_obj_filter_by_work &\
q_obj_notif_state_sent&\
q_obj_notif_type_n).count()
sent_error_notifications = Notification.objects.filter(q_obj_filter_by_work &\
q_obj_notif_state_sent_err&\
q_obj_notif_type_n).count()
init_cancel_notifications = Notification.objects.filter(q_obj_filter_by_work &\
q_obj_notif_state_init &\
q_obj_notif_type_c).count()
sent_cancel_notifications = Notification.objects.filter(q_obj_filter_by_work,\
q_obj_notif_state_sent,\
q_obj_notif_type_c).count()
sent_error_cancel_notifications = Notification.objects.filter(q_obj_filter_by_work,\
q_obj_notif_state_sent_err,\
q_obj_notif_type_c).count()
dict_work["init_notifications"] = init_notifications
dict_work["sent_notifications"] = sent_notifications
dict_work["sent_error_notifications"] = sent_error_notifications
dict_work["init_cancel_notifications"] = init_cancel_notifications
dict_work["sent_cancel_notifications"] = sent_cancel_notifications
dict_work["sent_error_cancel_notifications"] = sent_error_cancel_notifications
if work.work_state.workstate_name != "Canceled":#WorkTypes.objects.get(
if work.work_start_date.astimezone(local_tz) > timezone.now() < work.work_end_date.astimezone(local_tz):
dict_work["work_state"] = "Upcoming"
if work.work_start_date.astimezone(local_tz) <= timezone.now() <= work.work_end_date.astimezone(local_tz):
dict_work["work_state"] = "Pending"
if work.work_start_date.astimezone(local_tz) < timezone.now() > work.work_end_date.astimezone(local_tz):
dict_work["work_state"] = "Completed"
else:
dict_work["work_state"] = "Canceled"
dict_work["work_start_date"] = work.work_start_date.astimezone(local_tz).strftime('%d.%m.%Y %H:%M')
dict_work["work_end_date"] = work.work_end_date.astimezone(local_tz).strftime('%d.%m.%Y %H:%M')
list_works.append(dict_work)
#TODO - fix the bug with sort by date (sorting based on day number only)
list_works = sorted(list_works, reverse=True, key=lambda x: x["work_created_date"])
works = simplejson.dumps(list_works)
response = HttpResponse(works, content_type='application/json')
response.set_cookie(key="filter_works", value=simplejson.dumps(work_filter_dict), max_age=365*24*60*60, expires=None, path='/')
return response