Monday, 3 December 2012

Google App Engine Code Behind

This developers template is written in Python 2.7 for the latest Google App Engine with HRD (2012/13).
See it in action here: http://eventvoting.appspot.com

The aim is that it runs immediately in the Google App Engine tool without extra work for the developer. Unzip, load it and its up and running. You have forms, datastore connection already there.

************************************************** START

import os

import logging
import cgi
import datetime
import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from util.sessions import Session
from google.appengine.ext import db
from google.appengine.api import users

class Greeting(db.Model):
  content = db.StringProperty(multiline=True)
  date = db.DateTimeProperty(auto_now_add=True)
  contact1 = db.StringProperty()
  contact2 = db.StringProperty()

# DeveloperHandler start
 
class DeveloperHandler(webapp.RequestHandler):

  def get(self): # fires when a form is action get or just an http call
    adict = {"key one":"value one from DeveloperHandler Get ","key two":"value two from DeveloperHandler Get" }
    ano1 = dict(adict)
    greetings = db.GqlQuery("SELECT * "
                            "FROM Greeting "
                            "ORDER BY date DESC LIMIT 3")
    Render(self, 'developer.htm', {'mytest':ano1, 'testmessage':'String passed from code-behind class DeveoperHandler Get','greetings' : greetings })


  def post(self): # fires when a form is posted

    greeting = Greeting()
    if(self.request.get('content')):
       greeting.content = self.request.get('content')
    else:
       greeting.content = ' test comment, bla bla bla '  
    if(self.request.get('contact1')):
       greeting.contact1 = self.request.get('contact1')
    else:
       greeting.contact1 = ' test data..stuff...stuff.. '
    greeting.contact2 = self.request.get('contact2')    
    greeting.put()
#    self.redirect('/developer')
    adict = {'This is a key':'This is a value  from DeveloperHandler Post','this is another key':'and this is another value  from DeveloperHandler Post' }
    ano2 = dict(adict)
    greetings = db.GqlQuery("SELECT * "
                            "FROM Greeting "
                            "ORDER BY date DESC LIMIT 3")
    Render(self, 'developer.htm', {'mytest':ano2,'greetings' : greetings, 'testmessage':'String passed from code-behind class DeveloperHandler Post' })
# DeveloperHandler end

class User(db.Model):
  account = db.StringProperty()
  password = db.StringProperty()
  logging.info(' checking if User fires or not   ')

def Render(handler, tname = 'index.htm', values = { }):
  temp = './templates/' + tname
  if not os.path.isfile(temp):
     return False

  newval = dict(values)
  newval['path'] = handler.request.path
  # logging.info(' values are   '+str(values))
  handler.session = Session() # goes to session, invalidates and sets a new cookie if its new
  if(new_cookie_set):
      handler.response.headers.add_header("Set-Cookie", newcookie)
  if 'username' in handler.session:
     newval['username'] = handler.session['username']
     handler.session['sessy'] = ' a test string in the session' # adding this for coder's interest
     newval['sessy'] = handler.session['sessy']
  outstr = template.render(temp, newval)
  handler.response.out.write(outstr)
  return True

class LoginHandler(webapp.RequestHandler):

  def get(self):
    Render(self, 'login.htm')
     
  def post(self):
    global x
    x = self.request.cookies.get('my_session_id')
    self.session = Session()
    acct = self.request.get('account')
    pw = self.request.get('password')
    self.session.delete_item('username')
    if pw == '' or acct == '':
      Render(
          self,
          'login.htm',
          {'error' : 'Please specify Email and Password'} ) # written into login screen (django template)
     
      return
    que = db.Query(User)
    que = que.filter('account =',acct.lower())
    que = que.filter('password = ',pw)

    results = que.fetch(limit=1)
    if len(results) > 0 :
      self.session['username'] = acct
      dicty = {"My first key":"My first value from LoginHandler Post","My second key":"My second value from LoginHandler Post" }
      ano3 = dict(dicty)
#      self.redirect("developer.htm")
      greetings = db.GqlQuery("SELECT * "
                            "FROM Greeting "
                            "ORDER BY date DESC LIMIT 3")
      Render(self, 'developer.htm', {'greetings':greetings, 'mytest':ano3, 'testmessage':'String message passed from the code-behind class LoginHandler Post' })
    else:
      Render(
          self,
          'login.htm',
          {'error' : 'Email or password incorrect'} )
         
class RegisterHandler(webapp.RequestHandler):

  def get(self):
      Render(self, 'register.htm')

  def post(self):
    global x
    x = self.request.cookies.get('my_session_id')
    self.session = Session()
    acct = self.request.get('account')
    pw = self.request.get('password')

   
    if not "@" in acct:
      Render(
          self,
          'register.htm',
          {'error' : 'Email address not correct'} )
      return
     
    if not "." in acct:
      Render(
          self,
          'register.htm',
          {'error' : 'Email address not correct'} )
      return

    if len(acct) < 8:
      Render(
          self,
          'register.htm',
          {'error' : 'Email address not correct'} )
      return
     
    if pw == '' or acct == '':
      Render(
          self,
          'register.htm',
           {'error' : 'Please fill in all fields'} )
      return
     
    if len(pw)<3:
      Render(
          self,
          'register.htm',
          {'error' : 'Password needs to be longer'} )
      return

    # Check if the user  exists
    que = db.Query(User).filter('account =',acct.lower())
    results = que.fetch(limit=1)

    if len(results) > 0 :
      Render(
          self,
          'register.htm',
          {'error' : 'Account Already Exists'} )
      return

    newuser = User(account=acct.lower(), password=pw);
    newuser.put();
    self.session['username'] = acct
    self.newdict = dict({"one":"valueoneRegisterHandler","two":"valuetwoRegisterHandler"})  
  # Render(self,'developer.htm',{ })
    self.redirect('developer.htm')

class LogoutHandler(webapp.RequestHandler):

  def get(self):
    global x
    x = self.request.cookies.get('my_session_id')
    self.session = Session()
    self.session.delete_item('username')
    Render(self, 'login.htm')

class MainHandler(webapp.RequestHandler):
  x = ' '
  newcookie = 'StartValueMainHandler'
  new_cookie_set = False
  def get(self):
    global new_cookie_set
    global x
    global newcookie
    new_cookie_set = False
    x = self.request.cookies.get('my_session_id')
    newcookie = 'valueinMainHandler'
    if Render(self,self.request.path) :
      return
    Render(self,'index.htm')
   
myapp = webapp.WSGIApplication([
     ('/login', LoginHandler),
     ('/register', RegisterHandler),  
     ('/logout', LogoutHandler),
     ('/sign', DeveloperHandler),
     ('/developer', DeveloperHandler),
     ('/.*', MainHandler)],
     debug=True)
****************************************************** END
Here is the developer page with live data in red from the code behind above:

ENJOY

Skeleton Responsive on Google App Engine

I have put a standard Skeleton template responsive design - suitable for desktops to smart phones on the Google App Engine with code behind and connection to google's high replication datastore:



The website looks like this in a smart phone (3 columns are displayed as one column):



There is code behind written in python 2.7 and ready to run in the app engine tool locally or in the cloud. It is connected already to the high replication datastore.

For developers its an ideal template to get you going fast. Then adapt it how you like.

Try it here:
http://eventvoting.appspot.com

Let me know how you get on with it. :)


Sunday, 16 September 2012

Talking Location for DevFest Hackathon

Some people need to listen to their location rather than look at it. This app does just that.
It speaks your location as soon as it is opened.

I developed it at Google DevFest Hackathon 15th Sept 2012.


Here it is in Eclipse, but get the source code below or get the App in the Google App Store - Play



IT WAS DEVELOPED IN ECLIPSE FOR ANDROID.

As a first approximate location it uses WiFi or 3G. If the user wants better accuracy and is in view of satellites they can get a GPS fix by clicking on 'to GPS'.

It uses fairly standard code that I have tweaked so that it 'speaks'.

Source code is here:

Its also in Google Play as an Android App:

Email me for joint work on this project (rodsit _at_ gmail dot com)