Presentation is loading. Please wait.

Presentation is loading. Please wait.

Google App Engine Sessions and Cookies ae-09-session www.appenginelearn.com.

Similar presentations


Presentation on theme: "Google App Engine Sessions and Cookies ae-09-session www.appenginelearn.com."— Presentation transcript:

1 Google App Engine Sessions and Cookies ae-09-session www.appenginelearn.com

2 Cookies and Sessions Maintaining State in HTTP

3 High Level Summary The web is “stateless” The browser does not maintain a connection to the server while you are looking at a page. You may never come back to the same server Or it may be a long time Or it may be one second later

4 High Level Summary The web is “stateless” So we need a way for servers to know “which browser is this?” In the browser, state is stored in “Cookies” In the server, state is stored in “Sessions”

5 Some Web sites always seem to want to know who you are!

6 Other Web sites always seem to know who you are!

7 Browser Server GET Whole Page GET Whole Page Draw You watch the YouTube video for an 30 seconds How you see YouTube... Click

8 Browser Server GET Whole Page GET Whole Page How YouTube sees you... Draw Click

9 Multi-User When a server is interacting with many different browsers at the same time, the server needs to know *which* browser a particular request came from Request / Response initially was stateless All browsers looked identical This was was fine for static web pages But it was really really bad for "webapps" Those simple days did not last very long at all.

10 Web Cookies to the Rescue http://en.wikipedia.org/wiki/HTTP_cookie Technically, cookies are arbitrary pieces of data chosen by the Web server and sent to the browser. The browser returns them unchanged to the server, introducing a state (memory of previous events) into otherwise stateless HTTP transactions. Without cookies, each retrieval of a Web page or component of a Web page is an isolated event, mostly unrelated to all other views of the pages of the same site.

11 http://en.wikipedia.org/wiki/HTTP_cookie

12 Cookies In the Browser Cookies contain markers indicating the web addresses they come from The browser only sends a cookie to the web server that originally set it Cookies have an expiration date Some last for years Others are short-term and go away as soon as the browser is closed

13 Playing with Cookies Firefox's WebDeveloper plugin has a set of cookie features Other browsers have a way to view or change cookies

14

15 Cookies Identifying individual users across requests Making the web seem not to be stateless

16 Request / Response Again!

17 Browser Server GET Whole Page Fragment Redraw Update HTTP REQ HTTP REQ CookiesCookies Cookies Remember that cookies are only sent back to the host that set the cookie.

18 HTTP Request / Response Cycle http://www.oreilly.com/openbook/cgi/ch04_02.html Browser Web Server HTTP Request HTTP Response Internet Explorer, FireFox, Safari, etc. (Review)

19 HTTP Request / Response Cycle GET /index.html HTTP/1.1 Accept: www/source Accept: text/html User-Agent: Lynx/2.4 http://www.oreilly.com/openbook/cgi/ch04_02.html Browser Web Server HTTP Request We do our initial GET to a server. The server checks to see if we have a cookie with a particular name set. Since this is our first interaction, we have no cookies set for this host.

20 HTTP Request / Response Cycle http://www.oreilly.com/openbook/cgi/ch04_02.html Browser Web Server HTTP Response HTTP/1.1 200 OK Content-type: text/html Set-Cookie: sessid=123.. Welcome.... host: sessid=123 Along with the rest of the response, the server sets a cookie with some name (sessid) and sends it back along with the rest of the response.

21 HTTP Request / Response Cycle GET /index.html HTTP/1.1 Accept: www/source Accept: text/html Cookie: sessid=123 User-Agent: Lynx/2.4 http://www.oreilly.com/openbook/cgi/ch04_02.html Browser Web Server HTTP Request host: sessid=123 From that point forward, each time we send a GET or POST to the server, we include any cookies which were set by that host.

22 HTTP Request / Response Cycle http://www.oreilly.com/openbook/cgi/ch04_02.html Browser Web Server HTTP Response HTTP/1.1 200 OK Content-type: text/html Set-Cookie: name=chuck.. Welcome.... host: sessid=123 host:name=chuck On each response, the server can change a cookie value. Or add another cookie.

23 HTTP Request / Response Cycle GET /index.html HTTP/1.1 Accept: www/source Accept: text/html Cookie: sessid=123,name=Chuck User-Agent: Lynx/2.4 http://www.oreilly.com/openbook/cgi/ch04_02.html Browser Web Server HTTP Request From that point forward, each time we send a GET or POST to the server, we include all the cookies which were set by that host. host: sessid=123 host:name=chuck

24 Security We ony send cookies back to the host that originally set the cookie The browser has *lots* of cookies for lots of hosts To see all Cookies: Firefox -> Preferences -> Privacy -> Show Cookies

25 The Firefox Web Developer Plugin Shows Cookies for the Current Host.

26 Two Kinds of Cookies Long-lived - who you are - account name - last access time You can close and reopen your browser and it is still there Temporary - used to identify your session It goes away when you close the browser

27

28 Using Cookies to Support Sessions and Login / Logout

29 Some Web sites always seem to want to know who you are!

30 In The Server - Sessions In most server applications, as soon as we meet a new browser we create a session We set a session cookie to be stored in the browser which indicates the session id in use The creation and destruction of sessions is generally handled by a web framework or some utility code that we just use to manage the sessions

31 Session Identifier A large, random number that we place in a browser cookie the first time we encounter a browser. This number is used to pick from the many sessions that the server has active at any one time. Server software stores data in the session which it wants to have from one request to another from the same browser. Shopping cart or login information is stored in the session in the server

32 Server Session 97 Browser C cook=97 Request Response index:“Please log in” cook=97 Create Session

33 Server Session 97 Browser C cook=97 Typing We now have a session established but are not yet logged in.

34 Login / Logout Having a session is not the same as being logged in. Generally you have a session the instant you connect to a web site The Session ID cookie is set when the first page is delivered Login puts user information in the session (stored in the server) Logout removes user information from the session

35 Server Session 97 Browser C cook=97 Request login: if good: set user Click cook=97

36 Server Session 97 user=phil Browser C cook=97 Request login: if good: set user Click Response cook=97

37 Server Session 97 user=phil Browser C cook=97

38 Using Sessions for Other Stuff

39 Server Browser A cook=10 Browser B cook=46 Session 10 user=chuckbal=$1000 Session 46 user=janbal=$400

40 Server Session 10 user=chuckbal=$1000 Session 46 user=janbal=$500 Browser A cook=10 Browser B cook=46 withdraw:bal=bal-100

41 Server Session 10 user=chuckbal=$1000 Session 46 user=janbal=$500 Browser A cook=10 Browser B cook=46 withdraw:bal=bal-100 Click

42 Server Session 10 user=chuckbal=$1000 Session 46 user=janbal=$500 Browser A cook=10 Browser B cook=46 cook=46 withdraw:bal=bal-100

43 Server Session 10 user=chuckbal=$1000 Session 46 user=janbal=$400 Browser A cook=10 Browser B cook=46 cook=46 withdraw:bal=bal-100 Response Request

44 Review...

45 High Level Summary The web is “stateless” - the browser does not maintain a connection to the server while you are looking at a page. Yu may never come back to the same server - or it may be a long time - or it may be one second later So we need a way for servers to know “which browser is this?” In the browser state is stored in “Cookies” In the server state is stored in “Sessions”

46 Browser Server GET Whole Page GET Whole Page Draw You watch the YouTube video for an 30 seconds How you see YouTube... Click

47 Browser Server Draw Click GET Whole Page GET Whole Page

48 Browser Server Draw Click GET Whole Page GET Whole Page Session 42 cook=42 cook=42

49 Cookie/Session Summary Cookies take the stateless web and allow servers to store small “breadcrumbs” in each browser. Session IDs are large random numbers stored in a cookie and used to maintain a session on the server for each of the browsers connecting to the server Server software stores sessions *somewhere* - each time a request comes back in, the right session is retrieved based on the cookie Server uses the session as a scratch space for little things

50 Programming and Sessions

51 First Look: Sessions are Magic! Sessions are usually part of the built-in web application framework Ruby on Rails Java Web Applications PHP The framework does all the cookie setting and data finding

52 First Look: Sessions are Magic! In our controller code we simply ask to create and/or access a session We treat the session like a dictionary storing whatever we like in the session under a set of string keys that we choose

53 Session Rules Keep them small - we don’t want to put too much in the session or we start taxing memory and other storage resources and slowing down our application Focus on data that is used on nearly every incoming request - the lookup key of the current user - the email address of the current user Sessions generally go away when the user closes their browser (cookie is lost) or after a period of inactivity (1-3 hours)

54 Session Uses Indication of the current user - management of the login and log out process Shopping cart - items / quantities

55 Our Magic - sessions.py Since the Google Application Engine does not provide a session capability, we need to add one - extending our application Download from http://www.appenginelearn.com/downloads/util.zip Install in your application in the directory util to make it available in your application

56 Using the Session from util.sessions import Session class LogoutHandler(webapp.RequestHandler): def get(self): self.session = Session() self.session.delete('username') doRender(self, 'index.htm') The Session() call either establishes a session or accesses the current session.

57 Inside the Session() call We use a session cookie to look up our session If the cookie exists and the session exists, return that session If not pick a large random number as the session key, make a session and set a temporary cookie with the session key as its value

58 The Login/Logout Pattern We use a key named ‘username’ in the session to indicate that the user is logged in If the key is missing the user is logged out If the key is present, its value is the account of the logged in user (e.g. “csev”)

59 def post(self): self.session = Session() acct = self.request.get('account') pw = self.request.get('password') logging.info("Checking account="+acct+" pw="+pw) self.session.delete('username') if pw == "" or acct == "": doRender(self,"login.htm",{'error' : 'Please specify Acct/PW'} ) elif pw == "secret": self.session['username'] = acct doRender(self,"index.htm",{ } ) else: doRender(self,"login.htm",{'error' : 'Incorrect password'} ) Get the Session Log out previous user Log in new user

60 Logout from util.sessions import Session class LogoutHandler(webapp.RequestHandler): def get(self): self.session = Session() self.session.delete('username') doRender(self, 'index.htm') Get the Session Log out previous user

61 Navigation We want to have the Login / Logout button flip when we log in or out and we want to see the name of the current logged in user.

62 <a href="topics.htm" {% ifequal path '/topics.htm' %} class="selected" {% endifequal %} >Topics {% ifequal username None %} <a href="/login" {% ifequal path '/login' %} class="selected" {% endifequal %} >Login {% else %} Logout ({{username}}) {% endifequal %} In the view template, we send an additional context variable to the template called “username” if the user is logged in. We use logic in the template to either generate the Login link or the Logout + account name link. _base.htm

63 def doRender(self, tname = "index.htm", values = { }): logging.info(tname) temp = os.path.join(os.path.dirname(__file__),'templates/'+tname) if not os.path.exists(temp): return False # Make a copy of the dictionary and add basic values newval = dict(values) if not 'path' in newval: path = self.request.path newval['path'] = self.request.path if not 'username' in newval: self.session = Session() if 'username' in self.session: newval['username'] = self.session["username"] outstr = template.render(temp, newval) self.response.out.write(outstr) return True We check to see if the username is in the session and if username is in the session we add it to the context variables to be passed into the template.

64 Summary The Cookies and Session work together to give us a relatively simply way to programmatically stash data associated with a particular user/browser While the mechanisms are a bit complex, the session pattern turns out to be pretty simple to use in our applications The Google Application Engine does not provide us with a Session feature - so we need to write or borrow some code Clever use of session is important to application performance


Download ppt "Google App Engine Sessions and Cookies ae-09-session www.appenginelearn.com."

Similar presentations


Ads by Google