当前位置: 首页>>代码示例>>Python>>正文


Python views.set_cookie函数代码示例

本文整理汇总了Python中mezzanine.utils.views.set_cookie函数的典型用法代码示例。如果您正苦于以下问题:Python set_cookie函数的具体用法?Python set_cookie怎么用?Python set_cookie使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了set_cookie函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: rating

def rating(request):
    """
    Handle a ``RatingForm`` submission and redirect back to its
    related object.
    """
    try:
        model = get_model(*request.POST["content_type"].split(".", 1))
        obj = model.objects.get(id=request.POST["object_pk"])
        url = obj.get_absolute_url() + "#rating-%s" % obj.id
        field = getattr(obj, request.POST["field_name"])
        if field.model != Rating:
            raise TypeError("Not a rating field.")
    except (KeyError, TypeError, AttributeError, ObjectDoesNotExist):
        # Something was missing from the post so abort.
        return HttpResponseRedirect("/")
    try:
        rating_value = int(request.POST["value"])
    except (KeyError, ValueError):
        return HttpResponseRedirect(url)
    rated = request.COOKIES.get("mezzanine-rating", "").split(",")
    cookie = "%(content_type)s.%(object_pk)s.%(field_name)s" % request.POST
    if cookie in rated:
        # Already rated so abort.
        return HttpResponseRedirect(url)
    field.add(Rating(value=rating_value))
    response = HttpResponseRedirect(url)
    rated.append(cookie)
    expiry = 60 * 60 * 24 * 365
    set_cookie(response, "mezzanine-rating", ",".join(rated), expiry)
    return response
开发者ID:n3ls0n,项目名称:mezzanine,代码行数:30,代码来源:views.py

示例2: rating

def rating(request):
    """
    Handle a ``RatingForm`` submission and redirect back to its
    related object.
    """
    try:
        model = get_model(*request.POST["content_type"].split(".", 1))
        obj = model.objects.get(id=request.POST["object_pk"])
        url = obj.get_absolute_url() + "#rating-%s" % obj.id
    except (KeyError, TypeError, AttributeError, ObjectDoesNotExist):
        # Something was missing from the post so abort.
        return HttpResponseRedirect("/")
    try:
        rating_value = int(request.POST["value"])
    except (KeyError, ValueError):
        return HttpResponseRedirect(url)
    ratings = request.COOKIES.get("mezzanine-rating", "").split(",")
    rating_string = "%s.%s" % (request.POST["content_type"],
                               request.POST["object_pk"])
    if rating_string in ratings:
        # Already rated so abort.
        return HttpResponseRedirect(url)
    obj.rating.add(Rating(value=rating_value))
    response = HttpResponseRedirect(url)
    ratings.append(rating_string)
    expiry = 60 * 60 * 24 * 365
    set_cookie(response, "mezzanine-rating", ",".join(ratings), expiry)
    return response
开发者ID:DanHoerst,项目名称:mezzanine,代码行数:28,代码来源:views.py

示例3: rating

def rating(request):
    """
    Handle a ``RatingForm`` submission and redirect back to its
    related object.
    """
    try:
        model = get_model(*request.POST["content_type"].split(".", 1))
        obj = model.objects.get(id=request.POST["object_pk"])
        url = obj.get_absolute_url() + "#rating-%s" % obj.id
    except (KeyError, TypeError, AttributeError, ObjectDoesNotExist):
        # Something was missing from the post so abort.
        return HttpResponseRedirect("/")
    try:
        rating_value = int(request.POST["value"])
    except (KeyError, ValueError):
        return HttpResponseRedirect(url)
    # There can only be one ``RatingField``, find its manager.
    for field in obj._meta.many_to_many:
        if isinstance(field, RatingField):
            rating_manager = getattr(obj, field.name)
            break
    else:
        raise TypeError("%s doesn't contain a RatingField." % obj)
    ratings = request.COOKIES.get("mezzanine-rating", "").split(",")
    rating_string = "%s.%s" % (request.POST["content_type"],
                               request.POST["object_pk"])
    if rating_string in ratings:
        # Already rated so abort.
        return HttpResponseRedirect(url)
    rating_manager.add(Rating(value=rating_value))
    response = HttpResponseRedirect(url)
    ratings.append(rating_string)
    expiry = 60 * 60 * 24 * 365
    set_cookie(response, "mezzanine-rating", ",".join(ratings), expiry)
    return response
开发者ID:n1k0,项目名称:mezzanine,代码行数:35,代码来源:views.py

示例4: comment

def comment(request, template="generic/comments.html"):
    """
    Handle a ``ThreadedCommentForm`` submission and redirect back to its
    related object.
    """
    try:
        model = get_model(*request.POST["content_type"].split(".", 1))
        obj = model.objects.get(id=request.POST["object_pk"])
        if request.method != "POST":
            raise ObjectDoesNotExist()
    except (KeyError, TypeError, AttributeError, ObjectDoesNotExist):
        # Something was missing from the post so abort.
        return HttpResponseRedirect("/")
    form = ThreadedCommentForm(request, obj, request.POST or None)
    if form.is_valid():
        comment = form.get_comment_object()
        if request.user.is_authenticated():
            comment.user = request.user
        comment.by_author = request.user == getattr(obj, "user", None)
        comment.ip_address = request.META.get("HTTP_X_FORWARDED_FOR", request.META["REMOTE_ADDR"])
        comment.replied_to_id = request.POST.get("replied_to")
        comment.save()
        response = HttpResponseRedirect(comment.get_absolute_url())
        # Store commenter's details in a cookie for 90 days.
        cookie_expires = 60 * 60 * 24 * 90
        for field in ThreadedCommentForm.cookie_fields:
            cookie_name = ThreadedCommentForm.cookie_prefix + field
            cookie_value = request.POST.get(field, "")
            set_cookie(response, cookie_name, cookie_value, cookie_expires)
        return response
    else:
        # Show errors with stand-alone comment form.
        context = {"obj": obj, "posted_comment_form": form}
        return render(request, template, context)
开发者ID:Joe8Bit,项目名称:mezzanine,代码行数:34,代码来源:views.py

示例5: polling

def polling(request, slug=None):
    blog_posts = BlogPost.objects.published(for_user=request.user)
    blog_post = blog_posts.get(slug=slug)
    url = request.build_absolute_uri()
    url = url.split('/')
    url = '/'.join(url[:-2]) + '/'
    if not blog_post:
        return HttpResponse(json.dumps({'result':'Sorry, no such post'}), mimetype="application/json")
    try:
        rating_value = request.GET["value"]
    except (KeyError, ValueError):
        return HttpResponseRedirect(url)
    ratings = request.COOKIES.get("poll-rating", "").split(",")
    rating_string = "%s.%s" % ('blogpost',
                               blog_post.id)
    #"\054blog_fork.blogpost.2\054blog_fork.blogpost.1"
    if rating_string in ratings:
        # Already rated so abort.
        return HttpResponse(json.dumps({'result':'You have already voted'}), mimetype="application/json")
    if rating_value == 'up':
        blog_post.upvote +=1
        blog_post.save()
    if rating_value == 'down':
        blog_post.downvote +=1
        blog_post.save()
    response = HttpResponse(json.dumps({'result':rating_value}), mimetype="application/json") 
    ratings.append(rating_string)
    expiry = 60 * 60 * 24 * 365
    set_cookie(response, "poll-rating", ",".join(ratings), expiry)
    return response
开发者ID:B1aZer,项目名称:pure-cloud-1424,代码行数:30,代码来源:views.py

示例6: rating

def rating(request):
    """
    Handle a ``RatingForm`` submission and redirect back to its
    related object.
    """
    response = initial_validation(request, "rating")
    if isinstance(response, HttpResponse):
        return response
    obj, post_data = response
    url = add_cache_bypass(obj.get_absolute_url().split("#")[0])
    response = redirect(url + "#rating-%s" % obj.id)
    rating_form = RatingForm(request, obj, post_data)
    if rating_form.is_valid():
        rating_form.save()
        if request.is_ajax():
            # Reload the object and return the rating fields as json.
            obj = obj.__class__.objects.get(id=obj.id)
            rating_name = obj.get_ratingfield_name()
            json = {}
            for f in ("average", "count", "sum"):
                json["rating_" + f] = getattr(obj, "%s_%s" % (rating_name, f))
            response = HttpResponse(dumps(json))
        ratings = ",".join(rating_form.previous + [rating_form.current])
        set_cookie(response, "mezzanine-rating", ratings)
    return response
开发者ID:Gu1,项目名称:mezzanine,代码行数:25,代码来源:views.py

示例7: comment

def comment(request, template="generic/comments.html"):
    """
    Handle a ``ThreadedCommentForm`` submission and redirect back to its
    related object.
    """
    response = initial_validation(request, "comment")
    if isinstance(response, HttpResponse):
        return response
    obj, post_data = response
    form = ThreadedCommentForm(request, obj, post_data)
    if form.is_valid():
        url = obj.get_absolute_url()
        if is_spam(request, form, url):
            return redirect(url)
        comment = form.save(request)
        response = redirect(add_cache_bypass(comment.get_absolute_url()))
        # Store commenter's details in a cookie for 90 days.
        for field in ThreadedCommentForm.cookie_fields:
            cookie_name = ThreadedCommentForm.cookie_prefix + field
            cookie_value = post_data.get(field, "")
            set_cookie(response, cookie_name, cookie_value)
        return response
    elif request.is_ajax() and form.errors:
        return HttpResponse(dumps({"errors": form.errors}))
    # Show errors with stand-alone comment form.
    context = {"obj": obj, "posted_comment_form": form}
    response = render(request, template, context)
    return response
开发者ID:Gu1,项目名称:mezzanine,代码行数:28,代码来源:views.py

示例8: comment

def comment(request, template="generic/comments.html"):
    """
    Handle a ``ReviewForm`` submission and redirect back to its
    related object.
    """
    response = initial_validation(request, "comment")
    if isinstance(response, HttpResponse):
        return response
    obj, post_data = response
    form = ReviewForm(request, obj, request.POST )
    if form.is_valid():
        url = obj.get_absolute_url()
        if is_spam(request, form, url):
            return redirect(url)
        comment = form.save(request)
        response = redirect(add_cache_bypass(comment.get_absolute_url()))
        # Store commenter's details in a cookie for 90 days.
        for field in ReviewForm.cookie_fields:
            cookie_name = ReviewForm.cookie_prefix + field
            cookie_value = post_data.get(field, "")
            set_cookie(response, cookie_name, cookie_value)
        """
            Send activity feed to those who follow this vendor page.
        """
        if request.user.is_authenticated():
            action.send(obj, verb=settings.GOT_REVIEW_VERB, target=comment )
        return response
    elif request.is_ajax() and form.errors:
        return HttpResponse(dumps({"errors": form.errors}))
    # Show errors with stand-alone comment form.
    context = {"obj": obj, "posted_comment_form": form}
    response = render(request, template, context)
    return response
开发者ID:vadhawal,项目名称:mezzanine,代码行数:33,代码来源:views.py

示例9: set_device

def set_device(request, device=""):
    """
    Sets a device name in a cookie when a user explicitly wants to go
    to the site for a particular device (eg mobile).
    """
    response = redirect(add_cache_bypass(request.GET.get("next", "/")))
    set_cookie(response, "mezzanine-device", device, 60 * 60 * 24 * 365)
    return response
开发者ID:422053362,项目名称:mezzanine,代码行数:8,代码来源:views.py

示例10: product

def product(request, slug, template="shop/product.html",
            form_class=AddProductForm, extra_context=None):
    """
    Display a product - convert the product variations to JSON as well as
    handling adding the product to either the cart or the wishlist.
    """
    published_products = Product.objects.published(for_user=request.user)
    product = get_object_or_404(published_products, slug=slug)
    fields = [f.name for f in ProductVariation.option_fields()]
    variations = product.variations.all()
    variations_json = dumps([dict([(f, getattr(v, f))
        for f in fields + ["sku", "image_id"]]) for v in variations])
    to_cart = (request.method == "POST" and
               request.POST.get("add_wishlist") is None)
    initial_data = {}
    if variations:
        initial_data = dict([(f, getattr(variations[0], f)) for f in fields])
    initial_data["quantity"] = 1
    add_product_form = form_class(request.POST or None, product=product,
                                  initial=initial_data, to_cart=to_cart)
    if request.method == "POST":
        if add_product_form.is_valid():
            if to_cart:
                quantity = add_product_form.cleaned_data["quantity"]
                request.cart.add_item(add_product_form.variation, quantity)
                recalculate_cart(request)
                info(request, _("Item added to cart"))
                return redirect("shop_cart")
            else:
                skus = request.wishlist
                sku = add_product_form.variation.sku
                if sku not in skus:
                    skus.append(sku)
                info(request, _("Item added to wishlist"))
                response = redirect("shop_wishlist")
                set_cookie(response, "wishlist", ",".join(skus))
                return response
    related = []
    if settings.SHOP_USE_RELATED_PRODUCTS:
        related = product.related_products.published(for_user=request.user)
    context = {
        "product": product,
        "editable_obj": product,
        "images": product.images.all(),
        "variations": variations,
        "variations_json": variations_json,
        "has_available_variations": any([v.has_price() for v in variations]),
        "related_products": related,
        "add_product_form": add_product_form
    }
    context.update(extra_context or {})

    templates = [u"shop/%s.html" % str(product.slug), template]
    # Check for a template matching the page's content model.
    if getattr(product, 'content_model', None) is not None:
        templates.insert(0, u"shop/products/%s.html" % product.content_model)

    return TemplateResponse(request, templates, context)
开发者ID:raushanraj,项目名称:cartridge,代码行数:58,代码来源:views.py

示例11: comment

def comment(request, template="generic/comments.html"):
    """
    Handle a ``ThreadedCommentForm`` submission and redirect back to its
    related object.
    """

    post_data = request.POST
    settings.use_editable()
    if settings.COMMENTS_ACCOUNT_REQUIRED:
        if not request.user.is_authenticated():
            # Account required but user isn't authenticated - store
            # their post data in the session and redirect to login.
            request.session["unauthenticated_comment"] = post_data
            error(request, _("You must log in to comment. Please log in or "
                             "sign up, and your comment will be posted."))
            url = "%s?next=%s" % (settings.LOGIN_URL, reverse("comment"))
            return redirect(url)
        elif "unauthenticated_comment" in request.session:
            # User has logged in after post data being stored in the
            # session for an unauthenticated comment post, so use it.
            post_data = request.session.pop("unauthenticated_comment")

    try:
        model = get_model(*post_data["content_type"].split(".", 1))
        obj = model.objects.get(id=post_data["object_pk"])
    except (KeyError, TypeError, AttributeError, ObjectDoesNotExist):
        # Something was missing from the post so abort.
        return HttpResponseRedirect("/")

    form = ThreadedCommentForm(request, obj, post_data)
    if form.is_valid():
        url = obj.get_absolute_url()
        if is_spam(request, form, url):
            return redirect(url)
        comment = form.get_comment_object()
        if request.user.is_authenticated():
            comment.user = request.user
        comment.by_author = request.user == getattr(obj, "user", None)
        comment.ip_address = request.META.get("HTTP_X_FORWARDED_FOR",
                                              request.META["REMOTE_ADDR"]).split(',')[0].strip()
        comment.replied_to_id = post_data.get("replied_to")
        comment.save()
        comment_was_posted.send(sender=comment.__class__, comment=comment,
                                request=request)
        url = add_cache_bypass(comment.get_absolute_url())
        response = HttpResponseRedirect(url)
        # Store commenter's details in a cookie for 90 days.
        cookie_expires = 60 * 60 * 24 * 90
        for field in ThreadedCommentForm.cookie_fields:
            cookie_name = ThreadedCommentForm.cookie_prefix + field
            cookie_value = post_data.get(field, "")
            set_cookie(response, cookie_name, cookie_value, cookie_expires)
        return response
    else:
        # Show errors with stand-alone comment form.
        context = {"obj": obj, "posted_comment_form": form}
        return render(request, template, context)
开发者ID:waveaccounting,项目名称:mezzanine,代码行数:57,代码来源:views.py

示例12: set_device

def set_device(request, device=""):
    """
    Sets a device name in a cookie when a user explicitly wants to go
    to the site for a particular device (eg mobile).
    """
    url = request.GET.get("next", "/")
    url += "?" if "?" not in url else "&"
    url += "device-time=" + str(time()).replace(".", "")
    response = redirect(url)
    set_cookie(response, "mezzanine-device", device, 60 * 60 * 24 * 365)
    return response
开发者ID:van-nguyen,项目名称:mezzanine,代码行数:11,代码来源:views.py

示例13: remove_wishlist_item

def remove_wishlist_item(request):
	if request.method == 'POST':
		skus = request.wishlist
		sku = request.POST.get("sku")
        if sku in skus:
        	skus.remove(sku)
        	message = _("Item removed from wishlist")
        	messages.info(request, message)
        response = render(request,'messages.html')
        set_cookie(response, "wishlist", ",".join(skus))
        return response
开发者ID:davit-gh,项目名称:flaunt,代码行数:11,代码来源:views.py

示例14: product

def product(request, slug, template="shop/product.html"):
    """
    Display a product - convert the product variations to JSON as well as
    handling adding the product to either the cart or the wishlist.
    """
    published_products = Product.objects.published(for_user=request.user)
    product = get_object_or_404(published_products, slug=slug)
    fields = [f.name for f in ProductVariation.option_fields()]
    variations = product.variations.all()
    variations_json = simplejson.dumps([dict([(f, getattr(v, f))
                                        for f in fields + ["sku", "image_id"]])
                                        for v in variations])
    to_cart = (request.method == "POST" and
               request.POST.get("add_wishlist") is None)
    initial_data = {}
    if variations:
        initial_data = dict([(f, getattr(variations[0], f)) for f in fields])
    initial_data["quantity"] = 1
    add_product_form = AddProductForm(request.POST or None, product=product,
                                      initial=initial_data, to_cart=to_cart)
    if request.method == "POST":
        if add_product_form.is_valid():
            if to_cart:
                quantity = add_product_form.cleaned_data["quantity"]
                request.cart.add_item(add_product_form.variation, quantity)
                recalculate_discount(request)
                recalculate_billship_tax(request)
                info(request, _("Item added to cart"))
                return redirect("shop_cart")
            else:
                skus = request.wishlist
                sku = add_product_form.variation.sku
                if sku not in skus:
                    skus.append(sku)
                info(request, _("Item added to wishlist"))
                response = redirect("shop_wishlist")
                set_cookie(response, "wishlist", ",".join(skus))
                return response
    context = {
        "product": product,
        "editable_obj": product,
        "images": product.images.all(),
        "variations": variations,
        "variations_json": variations_json,
        "has_available_variations": any([v.has_price() for v in variations]),
        "related_products": product.related_products.published(
                                                      for_user=request.user),
        "add_product_form": add_product_form
    }
    templates = [u"shop/%s.html" % unicode(product.slug), template]
    return render(request, templates, context)
开发者ID:jbmckeon,项目名称:cartridge,代码行数:51,代码来源:views.py.BASE.7588.py

示例15: wishlist

def wishlist(request, template="shop/wishlist.html",
             form_class=AddProductForm, extra_context=None):
    """
    Display the wishlist and handle removing items from the wishlist and
    adding them to the cart.
    """

    if not settings.SHOP_USE_WISHLIST:
        raise Http404

    skus = request.wishlist
    error = None
    if request.method == "POST":
        to_cart = request.POST.get("add_cart")
        add_product_form = form_class(request.POST or None,
                                      to_cart=to_cart)
        if to_cart:
            if add_product_form.is_valid():
                request.cart.add_item(add_product_form.variation, 1)
                recalculate_cart(request)
                message = _("Item added to cart")
                url = "shop_cart"
            else:
                error = list(add_product_form.errors.values())[0]
        else:
            message = _("Item removed from wishlist")
            url = "shop_wishlist"
        sku = request.POST.get("sku")
        if sku in skus:
            skus.remove(sku)
        if not error:
            info(request, message)
            response = redirect(url)
            set_cookie(response, "wishlist", ",".join(skus))
            return response

    # Remove skus from the cookie that no longer exist.
    published_products = Product.objects.published(for_user=request.user)
    f = {"product__in": published_products, "sku__in": skus}
    wishlist = ProductVariation.objects.filter(**f).select_related("product")
    wishlist = sorted(wishlist, key=lambda v: skus.index(v.sku))
    context = {"wishlist_items": wishlist, "error": error}
    context.update(extra_context or {})
    response = TemplateResponse(request, template, context)
    if len(wishlist) < len(skus):
        skus = [variation.sku for variation in wishlist]
        set_cookie(response, "wishlist", ",".join(skus))
    return response
开发者ID:CoffenHu,项目名称:cartridge,代码行数:48,代码来源:views.py


注:本文中的mezzanine.utils.views.set_cookie函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。