How do you get and set cookies in Zope and Plone? - plone

Documentation, and more importantly, some code examples would be very useful. I would prefer this to not be in protected scripts, but in the code that goes into modern packages.

Use the response.setCookie() method. You can reach the response object via the request object. The latter you can reach via acquisition (self.REQUEST), or in views by accessing the passed-in request object, usually via self.request:
self.request.response.setCookie(name, value, **options)
where options end up as extra cookie parameters. Thus, turning a cookie into a non-session cookie requires a expires='date' keyword, limiting the cookie to a path is a path='/somepath' keyword to the setCookie() method. The usual browser cookie rules apply here.
To expire a cookie already set in the browser, you could either use a expires='date in the past' keyword, or you could use the response.expireCookie() method, which does this for you:
self.request.response.expireCookie(name, **options)
In this case you can still include options like the path or other cookie flags, but the method will override the max_age and expires options to ensure the cookie is deleted by the browser.
Although you could use Zope's SESSION support, you really need to think through the scalability issues. For example, you need to think through how session data will be shared across a cluster if you use ZEO or RelStorage. It is generally preferable to avoid using SESSION altogether if scalability is going to be an issue.

To set cookies you use RESPONSE.setCookie.
>>> self.REQUEST.RESPONSE.setCookie('cookiename', 'cookievalue', expires='Wed, 22 June 2009 12:00:00 GMT')
The cookie will end up in the REQUEST in the next request.
>>> self.REQUEST['cookiename']
'cookievalue'
You "delete" the cookie by using None as a value.
**Note, though, that most of the times when people use cookies it's to store variables that have to do with sessions, and you can use self.REQUEST.SESSION for that, it's easier.

Related

JMeter: The purpose of User-defined Cookies for requests

I'm just trying to get going with JMeter, and I try to understand more about User-defined cookies.
What purpose do they fulfill when you add them with hard-coded values, like for instance if you define a cookie called A and give it a value B to a certain domain for your HTTP sampler?
Much grateful for all information!
There could be several possible reasons:
Replay user session without having to re-login (i.e. session hijacking) so you would be able to debug your test by running a single request rather than the whole sequence (open login page, login, navigate somewhere, do something, etc.)
The value doesn't have to be hard-coded, it may come from correlation or calculation by the JSR223 Pre-Processor
Negative test scenarios (providing invalid cookie value to check for anticipated error)
You name it
Some web sites have Javascript scripts executed on page load which are adding/removing/updating HTTP cookie(s)
The set() method of the cookies API sets a cookie containing the specified cookie data. This method is equivalent to issuing an HTTP Set-Cookie header during a request to a given URL.
JMeter isn't executing Javascript
JMeter is not a browser, it works at protocol level. As far as web-services and remote services are concerned, JMeter looks like a browser (or rather, multiple browsers); however JMeter does not perform all the actions supported by browsers. In particular, JMeter does not execute the Javascript found in HTML pages.
So in JMeter you can manually manipulate HTTP cookie as you expect your site to execute

Outputcaching not working with cookies

There was a weird issue yesterday about asp.net's outputcaching (webforms). We were using page-level caching (not partial caching) for a multi-lingual site (language is determined via querystring key) and for some purpose, caching stopped working for some languages. I kept track of GetVaryByCustomString method of Global.asax file but, it didnt worked. I will give more details in answer...
Perhaps you need to set the Shareable attribute on your cookies to true?
If a given HttpResponse contains one or more outbound cookies with
Shareable is set to false (the default value), output caching will be
suppressed for the response. This prevents cookies that contain
potentially sensitive information from being cached in the response
and sent to multiple clients. To allow a response containing cookies
to be cached, configure caching normally for the response, such as
using the OutputCache directive or MVC's [OutputCache] attribute, and
set all outbound cookies to have Shareable set to true.
https://msdn.microsoft.com/en-us/library/system.web.httpcookie.shareable(v=vs.110).aspx
Thanks to subversion, i kept track of recent commits. We made a mechanism allowing specific users to view some languages that have not been published yet, using cookies instead of session variables. This was the cause of problem. If a request comes to a language which is not the default language, this mechanism checks whether it should allow user to view page. And IMHO if you modify response's cookie collection, asp.net disables outputcache for that request. I tested it and it really disables cache if you add a cookie to response.

Client with ETag always performs conditional GET

I am working on a new API. With ETags enabled, Chrome always conditionally GETs a resource with a long cache lifetime, that is, Chrome no longer uses the cached version without first confirming the ETag.
Is this how ETags are supposed to work with GET?
If so, and considering that I don't need them for update race-checking, I will remove the ETags and alleviate the extra work my server is doing.
Edit
I would have expected Chrome to use the cached item according to the max-age until it expires and then use the conditional GET to update its cached-item.
As I write this, it has now occurred to me that it would not be able to 'update its cached-item' since the 304 contains no max-age to use to extend the expiry time.
So I guess with ETags enabled, a client will always conditionally GET unless there's a good reason to use the cached version, such as no network.
Thus, it appears that ETags harm server performance when no concurrency control is needed.
Edit
I think I've already guessed the answer (above) but here's the question in a nutshell:
When ETags are enabled and the Max-Age is far in the future, should User Agents always use conditional GET instead of using the previously cached, fresh response?
How you load your page in the browser might be relevant here:
If you press Ctrl and reload the page using the refresh button, that will cause an unconditional reload of your resources with 200s returned.
If you just reload using the refresh button (or equivalent key like F5), conditional requests will be sent and 304s will be returned for static resources.
If you press enter in the address box, add the page to your bookmarks and load from there, or visit the page from a hyperlink, the cache max-age should work as expected.
With ETags enabled, Chrome always conditionally GETs a resource with a long cache lifetime, [...] Is this how ETags are supposed to work with GET?
The answer is in the RFC:
10.3.5 304 Not Modified
If the client has performed a conditional GET request and access is
allowed, but the document has not been modified, the server SHOULD
respond with this status code.
So, yes.
If this is not the answer you expect, you might want to include some actual traffic in your question that shows the order of request-response pairs that you expect and that you actually get.
considering that I don't need them for update race-checking
If you're not going to use conditional requests (If-Match and the likes), you may indeed omit the ETag calculation and processing.

Google Analytics in a cookie-free environment (brightscript)

I'm implementing analytics event and page view tracking on a Roku box (brightscript). That part isn't so important, but know that JS is not an option, nor is cookie setting. I can set variables, but they're not typical cookies. Ok - so I've implemented a great solution (google-analytics-for-roku-developers/) and all is well - EXCEPT!!
Analytics doesn't seem to track uniques, and is listing ZERO. It is tracking events beautifully, however :)
Here's a sample of my URI request (decoded for clarity):
http://www.google-analytics.com/__utm.gif?utmwv=1&utmn=1736644096&utmsr=720p HDTV&utmsc=24-bit&utmul=en-us&utmje=0&utmfl=-&utmdt=RokuPageView&utmhn=Home&utmr=-&utmp=Home&utmac=UA-5035974-13&utmcc=__utma=1394882688.2097034752.1347384621.1347384621.1347384621.2;+__utmb=1394882688;+__utmc=1394882688;+__utmz=1394882688.1347384621.2.2.utmccn=(direct)|utmcsr=(direct)|utmcmd=(none);+__utmv=1394882688.13C1CJ109560;
so, question #1 - I understand from the docs that the __utma is the element that tracks uniques. Do you see anything there that's wrong?
question #2 - The development code I implemented sends a NEW random cookie for EACH EVENT. That seems wrong to me. I'm considering changing it to a session-based cookie that persists through all events. That's when I'm way beyond my understanding. Any guidance on this?
I think the answer to #2 is the answer to #1. Basically, you need to emulate how a browser handles cookies within your code. A "session cookie" is just a cookie, that is, a value passed as an HTTP header along with the request and response -- what makes it a session cookie is that it's expiration date is set to the past, which tells the browser to delete it when the browser instance closes.
Cookies are pretty straightforward -- a mechanism to get around the fact that HTTP is stateless (has no memory). If you pass an HTTP header Set-cookie: <value> in the response, the client is supposed to remember the value and pass it back in a Cookie: <value> header in subsequent requests. (There's a bit more to cookies relating to domains and expiration, and so on, but it's not that much).
So if your client (the Roku) has some mechanism for persistance, then you just need to store any new cookie, then before setting a new random one, check the header and if the cookie has been stored, just send it back as is. You'll probably need to implement some sort of task that cleans up expired cookies periodically, and so on.
Do not fear the cookie. It's just a header (with browser-imparted magical powers).

Check cookies in asp.net

I want to check if a user has cookies enabled.
Most solutions involve:
1. creating a cookie
2. redirect the user to a custom page or the same page.
3. Read the cookie.
The issue I have is in the 2nd step. Should I use a query string while doing a response.redirect so that in the next trip I know the cookie has already been set and that I should try to read it? What if the user hard codes the URL(along with that query string) in the browser, while accessing the website?
Also, if I find that the cookies are enabled and I set a session variable to say that cookies are enabled on this browser, so dont check again in that session. Is that OK?
If session is available, is that a good enough indicator that cookies are enabled?
I want to minimize these double trips to each page for checking cookies.
I would use javascript to make an asynchronous request and check to see if the cookies that were set were handed back in this request.
Never pass a querystring. You already hinted at it above, but what if some trickster figures our the url and decides they want to pass their own querystring?
If the user has cookies set up, you can set the session and check that.
Always check the session.
instead of using this technique which involves multiple steps and pages, and extra waiting time for the enduser, can't you just use the HttpBrowserCapabilities class? This particular class has a Cookies property:
HttpBrowserCapabilities.Cookies Property
Grz, Kris.
As per my knowledge I know Two ways to check whether browser enables/accepting cookies
By using "Request.Browser.Cookies"
By using Javascript/Jquery
Example:
if (Request.Browser.Cookies)
{
Response.Write("Welcome To Hello World Cookies Accepted by the browser");
}
else
{
Response.Write("Good Bye To Hello World. Cookie diabled in your browser. Enable cookies and Try again... Cool..");
}

Resources