Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ### app.yaml
- application: engineapp
- version: 1
- runtime: python27
- api_version: 1
- threadsafe: yes
- handlers:
- - url: /favicon\.ico
- static_files: favicon.ico
- upload: favicon\.ico
- - url: .*
- script: main.app
- libraries:
- - name: webapp2
- version: "2.5.2"
- ### MAIN.py
- #!/usr/bin/env python
- #
- # Copyright 2007 Google Inc.
- #
- # Licensed under the Apache License, Version 2.0 (the "License");
- # you may not use this file except in compliance with the License.
- # You may obtain a copy of the License at
- #
- # http://www.apache.org/licenses/LICENSE-2.0
- #
- # Unless required by applicable law or agreed to in writing, software
- # distributed under the License is distributed on an "AS IS" BASIS,
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- # See the License for the specific language governing permissions and
- # limitations under the License.
- #
- import webapp2
- #class MainHandler(webapp2.RequestHandler):
- # def get(self):
- # self.response.write('Hello world!')
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- import getopt
- import logging
- import os
- import signal
- import sys
- import tempfile
- import traceback
- import os
- BASE_DIR = os.path.dirname(os.path.dirname(__file__))
- logging.basicConfig(
- filename=os.path.join(BASE_DIR, 'gae.log'),
- filemode='a',
- level=logging.DEBUG,
- format='%(levelname)-8s %(asctime)s %(filename)s:%(lineno)s] %(message)s')
- from google.appengine.ext.webapp import template
- from google.appengine.ext import ndb
- import datetime
- import logging
- import os.path
- import webapp2
- from webapp2_extras import auth
- from webapp2_extras import sessions
- from webapp2_extras.auth import InvalidAuthIdError
- from webapp2_extras.auth import InvalidPasswordError
- try:
- import json
- except ImportError:
- try:
- import simplejson as json
- except ImportError:
- try:
- from django.utils import simplejson as json
- except ImportError:
- try:
- from webapp2_extras import json
- except ImportError:
- logging.critical('No compatible JSON adapter found.')
- class BaseHandler(webapp2.RequestHandler):
- @webapp2.cached_property
- def auth(self):
- """Shortcut to access the auth instance as a property."""
- return auth.get_auth()
- @webapp2.cached_property
- def user_info(self):
- """Shortcut to access a subset of the user attributes that are storedin the session.
- The list of attributes to store in the session is specified in
- config['webapp2_extras.auth']['user_attributes'].
- :returns
- A dictionary with most user information"""
- return self.auth.get_user_by_session()
- @webapp2.cached_property
- def user(self):
- """Shortcut to access the current logged in user.
- Unlike user_info, it fetches information from the persistence layer and
- returns an instance of the underlying model.
- :returns
- The instance of the user model associated to the logged in user."""
- u = self.user_info
- return self.user_model.get_by_id(u['user_id']) if u else None
- @webapp2.cached_property
- def user_model(self):
- """Returns the implementation of the user model.
- It is consistent with config['webapp2_extras.auth']['user_model'], if set."""
- return self.auth.store.user_model
- @webapp2.cached_property
- def session(self):
- """Shortcut to access the current session."""
- return self.session_store.get_session(backend="datastore")
- def render_template(self, view_filename, params=None):
- if not params:
- params = {}
- user = self.user_info
- params['user'] = user
- path = os.path.join(os.path.dirname(__file__), 'templates', view_filename)
- self.response.out.write(template.render(path, params))
- def display_message(self, message):
- """Utility function to display a template with a simple message."""
- params = { 'message': message }
- self.render_template('webJN/message.html', params)
- # this is needed for webapp2 sessions to work
- def dispatch(self):
- # Get a session store for this request.
- self.session_store = sessions.get_store(request=self.request)
- try:
- # Dispatch the request.
- webapp2.RequestHandler.dispatch(self)
- finally:
- # Save all sessions.
- self.session_store.save_sessions(self.response)
- class MainHandler(BaseHandler):
- def get(self):
- # lets use session
- # To set a key
- #self.session['foo'] = 'bar'
- # To get a value:
- #foo = self.session.get('foo')
- # getting sessions values.. + coookie + http header
- #self.response.write('Hello world!')
- cookie_value = str("whatever I wanted the value to be")
- self.response.headers.add_header('Set-Cookie', 'user_id=' + cookie_value + '; Path=/')
- id = str()
- id = datetime.datetime.now().isoformat()
- self.session['cookie'] = id
- cookie = self.session.get('cookie')
- header = self.request.headers
- #return webapp2.Response('Hello, world!')
- self.response.write(header)
- logging.info(cookie)
- logging.info(cookie_value)
- class wwwHandler(BaseHandler):
- def get(self):
- session_store = sessions.get_store(request=self.request)
- cookie_name = session_store.config['cookie_name']
- session_id = self.request.cookies[cookie_name]
- self.response.out.write('<html><body>')
- self.response.out.write('Session id: %s' % session_id)
- self.response.out.write("</body></html>")
- config = {}
- config['webapp2_extras.sessions'] = {
- 'secret_key': 'my-super-secret-key',
- }
- app = webapp2.WSGIApplication([
- ('/', MainHandler),
- ('/www', wwwHandler),
- ], config=config, debug=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement