Sign in

Google Cookbook - Google App Engine

Posted by genewoo on Tue 14 Apr 2009 in Datastore
EntityManager em = emf.createEntityManager();
Query query = em
.createQuery("select t from com.genewoo.entity.TestEntity t");
List result = query.getResultList();
StringBuffer sb = new StringBuffer();
for (TestEntity testEntity : result) {
sb.append(testEntity.getName()).append("");
}
em.close();



if you use TestEntity directly, you will get an exception message of "TestEntity". From log it will tell you the root cause is:
Caused by: org.datanucleus.exceptions.ClassNotResolvedException: TestEntity

Posted by patelgopal on Wed 08 Apr 2009 in Django
as i got frequent error of unicodedecodeerror , this code actually help me to overcome it. this one is actually copied from django directly, thinking might be helpful to others too.

def smart_str(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Returns a bytestring version of 's', encoded as specified in 'encoding'.
If strings_only is True, don't convert (some) non-string-like objects.
"""
if strings_only and isinstance(s, (types.NoneType, int)):
return s
if isinstance(s, str):
return unicode(s).encode(encoding, errors)
elif not isinstance(s, basestring):
try:
return str(s)
except UnicodeEncodeError:
if isinstance(s, Exception):
# An Exception subclass containing non-ASCII data that doesn't
# know how to print itself properly. We shouldn't raise a
# further exception.
return ' '.join([smart_str(arg, encoding, strings_only,
errors) for arg in s])
return unicode(s).encode(encoding, errors)
elif isinstance(s, unicode):
return s.encode(encoding, errors)
elif s and encoding != 'utf-8':
return s.decode('utf-8', errors).encode(encoding, errors)
else:
return s

Posted by rcaught on Sat 04 Apr 2009 in Python
#!/usr/bin/env python
import common
import config

#Disable app caching and caching of listed module names
#Remember to comment out the following line before uploading to production, so as not to affect performance
reload_modules = [common, config]

class MainHandler(webapp.RequestHandler):
def get(self):
#Do stuff


def runMainHandler():
application = webapp.WSGIApplication([
('/', MainHandler)
],
debug=True)
wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
try:
def main(reload_modules):
for module in reload_modules:
reload(module)
runMainHandler()
main(reload_modules)
except:
def main():
runMainHandler()
main()

Posted by vncprado on Wed 25 Mar 2009 in Python
isto é um teste...
import os
from google.appengine.ext.webapp import datastore


fim do teste
Posted by bsimpson on Mon 23 Mar 2009 in Django
Django's debug page can be very useful, but for security reasons, they recommend that you disable it before uploading your app to a public-facing server. Not only is changing it back and forth by hand tedious, but you run the risk of forgetting to do so. The following snippet will set debug to True when running on the SDK, but to False when deployed to App Engine:

DEBUG = os.getenv('SERVER_SOFTWARE').split('/')[0] == "Development" if os.getenv('SERVER_SOFTWARE') else False

Posted by fujinaka.tohru on Fri 06 Mar 2009 in Datastore
On bulk uploading from csv file, you may need to ignore some csv rows that don't match any condition to import.
To do it with the new bulk uploader, bulkloader.py, it is simple: return an empty array from HandleEntity() of your Loader class, like:

class ContactLoader(Loader):
def __init__(self):
Loader.__init__(self, 'Contact',
[('name', str),
('title', str)])
class PhoneNumberLoader(Loader):
def __init__(self):
Loader.__init__(self, 'PhoneNumber',
[('contact', lambda name: self.getContact(name)),
('number', db.PhoneNumber)])
def getContact(self, name):
contact = Contact.all().filter('name', name).get()
if contact:
return contact.key()
return None
def HandleEntity(self, entity):
if not entity.contact is None:
return entity
return [] # skip a csv row

Posted by gravix on Sun 01 Mar 2009 in Scalability
This example builds on what Austin Chau did. Modify his javascript.py as follows:
class JsAgg(webapp.RequestHandler):
def get(self):
data = memcache.get(key="JSAGG")
if data is None:
filenames = ["js/jquery.js",
"js/jquery_form.js",
"js/jquery_countDown.js",
"js/jquery_color.js",
"js/jquery_pulse.js",
"js/conquer-on-contact.js"]
data = ""
for filename in filenames:
data += minify(filename) + '\n'
memcache.add(key="JSAGG", value=data, time=memCacheExpire)
self.response.headers['Content-Type'] = 'text/javascript'
self.response.out.write(data)
# serving minified/aggregated javascript from mem cache
apps_binding.append(('/js_agg/', JsAgg))


Obviously change the filenames. Maybe someone clever can write something that includes all .js files automatically. Anyway for me this cut initial (non-cached) page load times by more than 60%.

A longer article that talks about my rationale for doing this is at http://changelog.bthomson.com/2009/02/reducing-page-load-time-on-google-app.html. Due to a bug in this tool I can't post the HTML code needed to load the Javascript here, but you can see it if you go to this site.

In response to the comment below, you'll need this in your app.yaml:
handlers:
- url: /js.*
script: javascript.py

Posted by rbawaskar on Sat 28 Feb 2009 in Users API
This is very handy and quick trick using decorators thatt require users authentication using appengine's users api.
def loginRequired(func):
def wrapper(self, *args, **kw):
user = users.get_current_user()
if not user:
self.redirect(users.create_login_url(self.request.uri))
else:
func(self, *args, **kw)
return wrapper



Usage:
class SearchHandler(webapp.RequestHandler)
@loginRequired
def get(self)
#Login specific actions goes here

Posted by KAgliano on Fri 20 Feb 2009 in Python
import os
from google.appengine.ext.webapp import datastore


The above line imports datastore
Posted by ericsk on Fri 20 Feb 2009 in Datastore
To store the users' avatars, you might use datastore entities:
from google.appengine.ext import db

class Avatar(db.Model):
content = db.BlobProperty() # the avatar's binary
updated = db.DateTimeProperty(auto_now=True)



To show an avatar (i.e. URL `/avatar/some_one.png` to an handler), the following codes might help caching:
from google.appengine.ext import webapp
from google.appengine.api import memcache
import time
from datetime import datetime

class AvatarHandler(webapp.RequestHandler):

def output_avatar(self):
if self.avatar is None:
self.avatar = Avatar.get_by_key_name('avatar_%s' % self.u)

# store the last modified timestamp to the memcache
memcache.set('avatar_%s_lastmod' % self.u,
int(time.mktime(self.avatar.updated.timetuple())),
60*60)

# set the cache headers
lastmod = self.avatar.updated
fmt = '%a, %d %b %Y %H:%M:%S GMT'
self.response.headers.update({
'Cache-Control': 'max-age=86400',
'Expires': (lastmod + timedelta(days=1)).strftime(fmt),
'Last-Modified': lastmod.strftime(fmt),
'Content-Type': 'image/png'
})
self.response.out.write(self.avatar.content)

def get(self, username):
self.avatar = None
self.u = username

# get the last modified timestamp from memcache
# if the cache is empty (or replaced), look up it from bigtable
lastmod = memcache.get('avatar_%s_lastmod' % self.u)
if lastmod is None:
self.avatar = Avatar.get_by_key_name('avatar_%s' % self.u)
lastmod = int(time.mktime(self.avatar.updated.timetuple()))
else:
lastmod = int(lastmod)

# check if the output is necessary.
if self.request.headers.has_key('If-Modified-Since'):
dt = self.request.headers['If-Modified-Since'].split(';')[0]
since = int(time.mktime(datetime.strptime(dt, '%a, %d %b %Y %H:%M:%S %Z').timetuple()))
if since > lastmod:
self.response.set_status(304)
else:
self.output_avatar()
else:
self.output_avatar()