Advertisement
simbha

webapp2sessions ^> | <^ bible-guide

Feb 3rd, 2015
417
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.94 KB | None | 0 0
  1. ### app.yaml
  2.  
  3. application: engineapp
  4. version: 1
  5. runtime: python27
  6. api_version: 1
  7. threadsafe: yes
  8.  
  9. handlers:
  10. - url: /favicon\.ico
  11.   static_files: favicon.ico
  12.   upload: favicon\.ico
  13.  
  14. - url: .*
  15.   script: main.app
  16.  
  17. libraries:
  18. - name: webapp2
  19.   version: "2.5.2"
  20.  
  21.  
  22.  
  23.  
  24.  
  25. ### MAIN.py
  26.  
  27. #!/usr/bin/env python
  28. #
  29. # Copyright 2007 Google Inc.
  30. #
  31. # Licensed under the Apache License, Version 2.0 (the "License");
  32. # you may not use this file except in compliance with the License.
  33. # You may obtain a copy of the License at
  34. #
  35. #     http://www.apache.org/licenses/LICENSE-2.0
  36. #
  37. # Unless required by applicable law or agreed to in writing, software
  38. # distributed under the License is distributed on an "AS IS" BASIS,
  39. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40. # See the License for the specific language governing permissions and
  41. # limitations under the License.
  42. #
  43. import webapp2
  44.  
  45. #class MainHandler(webapp2.RequestHandler):
  46. #    def get(self):
  47. #        self.response.write('Hello world!')
  48.  
  49.  
  50. #!/usr/bin/env python
  51. # -*- coding: utf-8 -*-
  52.  
  53. import getopt
  54. import logging
  55. import os
  56. import signal
  57. import sys
  58. import tempfile
  59. import traceback
  60. import os
  61. BASE_DIR = os.path.dirname(os.path.dirname(__file__))
  62.  
  63. logging.basicConfig(
  64.     filename=os.path.join(BASE_DIR, 'gae.log'),
  65.     filemode='a',
  66.     level=logging.DEBUG,
  67.     format='%(levelname)-8s %(asctime)s %(filename)s:%(lineno)s] %(message)s')
  68.  
  69. from google.appengine.ext.webapp import template
  70. from google.appengine.ext import ndb
  71. import datetime
  72. import logging
  73. import os.path
  74. import webapp2
  75.  
  76. from webapp2_extras import auth
  77. from webapp2_extras import sessions
  78.  
  79. from webapp2_extras.auth import InvalidAuthIdError
  80. from webapp2_extras.auth import InvalidPasswordError
  81.  
  82. try:
  83.     import json
  84. except ImportError:
  85.     try:
  86.         import simplejson as json
  87.     except ImportError:
  88.         try:
  89.             from django.utils import simplejson as json
  90.         except ImportError:
  91.             try:
  92.                 from webapp2_extras import json
  93.             except ImportError:
  94.                 logging.critical('No compatible JSON adapter found.')
  95.  
  96.  
  97. class BaseHandler(webapp2.RequestHandler):
  98.  
  99.     @webapp2.cached_property
  100.     def auth(self):
  101.         """Shortcut to access the auth instance as a property."""
  102.         return auth.get_auth()
  103.  
  104.     @webapp2.cached_property
  105.     def user_info(self):
  106.         """Shortcut to access a subset of the user attributes that are storedin the session.
  107.        The list of attributes to store in the session is specified in
  108.        config['webapp2_extras.auth']['user_attributes'].
  109.        :returns
  110.        A dictionary with most user information"""
  111.         return self.auth.get_user_by_session()
  112.  
  113.     @webapp2.cached_property
  114.     def user(self):
  115.         """Shortcut to access the current logged in user.
  116.        Unlike user_info, it fetches information from the persistence layer and
  117.        returns an instance of the underlying model.
  118.        :returns
  119.        The instance of the user model associated to the logged in user."""
  120.         u = self.user_info
  121.         return self.user_model.get_by_id(u['user_id']) if u else None
  122.  
  123.     @webapp2.cached_property
  124.     def user_model(self):
  125.         """Returns the implementation of the user model.
  126.        It is consistent with config['webapp2_extras.auth']['user_model'], if set."""
  127.         return self.auth.store.user_model
  128.  
  129.     @webapp2.cached_property
  130.     def session(self):
  131.         """Shortcut to access the current session."""
  132.         return self.session_store.get_session(backend="datastore")
  133.  
  134.     def render_template(self, view_filename, params=None):
  135.         if not params:
  136.             params = {}
  137.         user = self.user_info
  138.         params['user'] = user
  139.         path = os.path.join(os.path.dirname(__file__), 'templates', view_filename)
  140.         self.response.out.write(template.render(path, params))
  141.  
  142.     def display_message(self, message):
  143.         """Utility function to display a template with a simple message."""
  144.         params = { 'message': message }
  145.         self.render_template('webJN/message.html', params)
  146.  
  147.     # this is needed for webapp2 sessions to work
  148.     def dispatch(self):
  149.         # Get a session store for this request.
  150.         self.session_store = sessions.get_store(request=self.request)
  151.         try:
  152.             # Dispatch the request.
  153.             webapp2.RequestHandler.dispatch(self)
  154.  
  155.         finally:
  156.             # Save all sessions.
  157.             self.session_store.save_sessions(self.response)
  158.  
  159.  
  160. class MainHandler(BaseHandler):
  161.     def get(self):
  162.         # lets use session
  163.         # To set a key
  164.         #self.session['foo'] = 'bar'
  165.         # To get a value:
  166.         #foo = self.session.get('foo')
  167.         # getting sessions values.. + coookie + http header
  168.         #self.response.write('Hello world!')
  169.         cookie_value = str("whatever I wanted the value to be")
  170.         self.response.headers.add_header('Set-Cookie', 'user_id=' + cookie_value + '; Path=/')
  171.         id = str()
  172.         id = datetime.datetime.now().isoformat()
  173.         self.session['cookie'] = id
  174.         cookie = self.session.get('cookie')
  175.         header = self.request.headers
  176.         #return webapp2.Response('Hello, world!')
  177.         self.response.write(header)
  178.         logging.info(cookie)
  179.         logging.info(cookie_value)
  180.  
  181. class wwwHandler(BaseHandler):
  182.     def get(self):
  183.         session_store = sessions.get_store(request=self.request)
  184.         cookie_name = session_store.config['cookie_name']
  185.         session_id = self.request.cookies[cookie_name]
  186.         self.response.out.write('<html><body>')
  187.         self.response.out.write('Session id: %s' % session_id)
  188.         self.response.out.write("</body></html>")
  189.  
  190.  
  191.  
  192.  
  193.  
  194. config = {}
  195.  
  196. config['webapp2_extras.sessions'] = {
  197.     'secret_key': 'my-super-secret-key',
  198. }
  199.  
  200.  
  201.  
  202.  
  203. app = webapp2.WSGIApplication([
  204.     ('/', MainHandler),
  205.     ('/www', wwwHandler),
  206. ], config=config, debug=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement