Skip to content

Commit

Permalink
Update Google App Engine example. Thanks @jeunito!
Browse files Browse the repository at this point in the history
  • Loading branch information
martey committed Dec 18, 2012
2 parents 96afefc + 1bbcfbd commit 86ff558
Show file tree
Hide file tree
Showing 3 changed files with 103 additions and 40 deletions.
11 changes: 8 additions & 3 deletions examples/appengine/app.yaml
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
application: facebook-example
application: facebook-example-py27
version: 1
runtime: python
runtime: python27
api_version: 1
threadsafe: true

handlers:
- url: /.*
script: example.py
script: example.app

libraries:
- name: jinja2
version: latest
4 changes: 2 additions & 2 deletions examples/appengine/example.html
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
<div>
Upload photo test:
<form method="post">
Enter URL to URLFecth from:<input type="text" name="url"/>
Enter URL to URLFetch from:<input type="text" name="url"/>
<input type="submit"/>
</form>
</div>
Expand All @@ -28,7 +28,7 @@
FB.init({appId: '{{ facebook_app_id }}', status: true, cookie: true,
xfbml: true});
FB.Event.subscribe('{% if current_user %}auth.logout{% else %}auth.login{% endif %}', function(response) {
window.location.reload();
{% if current_user %} window.location = "/logout" {% else %} window.location.reload(); {% endif %}
});
};
(function() {
Expand Down
128 changes: 93 additions & 35 deletions examples/appengine/example.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,24 +16,31 @@

"""
A barebones AppEngine application that uses Facebook for login.
Make sure you add a copy of facebook.py (from python-sdk/src/) into this
directory so it can be imported.
"""
1. Make sure you add a copy of facebook.py (from python-sdk/src/)
into this directory so it can be imported.
2. Don't forget to tick Login With Facebook on your facebook app's
dashboard and place the app's url wherever it is hosted
3. Place a random, unguessable string as a session secret below in
config dict.
4. Fill app id and app secret.
5. Change the application name in app.yaml.
"""
FACEBOOK_APP_ID = "your app id"
FACEBOOK_APP_SECRET = "your app secret"

import facebook
import os.path
import wsgiref.handlers
import logging
import webapp2
import os
import jinja2
import urllib2

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
from google.appengine.api.urlfetch import fetch
from webapp2_extras import sessions

config = {}
config['webapp2_extras.sessions'] = dict(secret_key='')


class User(db.Model):
Expand All @@ -45,7 +52,7 @@ class User(db.Model):
access_token = db.StringProperty(required=True)


class BaseHandler(webapp.RequestHandler):
class BaseHandler(webapp2.RequestHandler):
"""Provides access to the active Facebook user in self.current_user
The property is lazy-loaded on first access, using the cookie saved
Expand All @@ -55,48 +62,99 @@ class BaseHandler(webapp.RequestHandler):
"""
@property
def current_user(self):
if not hasattr(self, "_current_user"):
self._current_user = None
cookie = facebook.get_user_from_cookie(
self.request.cookies, FACEBOOK_APP_ID, FACEBOOK_APP_SECRET)
if self.session.get("user"):
# User is logged in
return self.session.get("user")
else:
# Either used just logged in or just saw the first page
# We'll see here
cookie = facebook.get_user_from_cookie(self.request.cookies,
FACEBOOK_APP_ID,
FACEBOOK_APP_SECRET)
if cookie:
# Store a local instance of the user data so we don't need
# a round-trip to Facebook on every request
# Okay so user logged in.
# Now, check to see if existing user
user = User.get_by_key_name(cookie["uid"])
if not user:
# Not an existing user so get user info
graph = facebook.GraphAPI(cookie["access_token"])
profile = graph.get_object("me")
user = User(key_name=str(profile["id"]),
id=str(profile["id"]),
name=profile["name"],
profile_url=profile["link"],
access_token=cookie["access_token"])
user = User(
key_name=str(profile["id"]),
id=str(profile["id"]),
name=profile["name"],
profile_url=profile["link"],
access_token=cookie["access_token"]
)
user.put()
elif user.access_token != cookie["access_token"]:
user.access_token = cookie["access_token"]
user.put()
self._current_user = user
return self._current_user
# User is now logged in
self.session["user"] = dict(
name=user.name,
profile_url=user.profile_url,
id=user.id,
access_token=user.access_token
)
return self.session.get("user")
return None

def dispatch(self):
"""
This snippet of code is taken from the webapp2 framework documentation.
See more at
http://webapp-improved.appspot.com/api/webapp2_extras/sessions.html
"""
self.session_store = sessions.get_store(request=self.request)
try:
webapp2.RequestHandler.dispatch(self)
finally:
self.session_store.save_sessions(self.response)

@webapp2.cached_property
def session(self):
"""
This snippet of code is taken from the webapp2 framework documentation.
See more at
http://webapp-improved.appspot.com/api/webapp2_extras/sessions.html
"""
return self.session_store.get_session()


class HomeHandler(BaseHandler):
def get(self):
path = os.path.join(os.path.dirname(__file__), "example.html")
args = dict(current_user=self.current_user,
facebook_app_id=FACEBOOK_APP_ID)
self.response.out.write(template.render(path, args))
template = jinja_environment.get_template('example.html')
self.response.out.write(template.render(dict(
facebook_app_id=FACEBOOK_APP_ID,
current_user=self.current_user
)))

def post(self):
url = self.request.get('url')
file = urllib2.urlopen(url)
graph = facebook.GraphAPI(self.current_user.access_token)
graph.put_photo(file, "Test Image")
graph = facebook.GraphAPI(self.current_user['access_token'])
response = graph.put_photo(file, "Test Image")
photo_url = ("http://www.facebook.com/"
"photo.php?fbid={0}".format(response['id']))
self.redirect(str(photo_url))


class LogoutHandler(BaseHandler):
def get(self):
if self.current_user is not None:
self.session['user'] = None

def main():
logging.getLogger().setLevel(logging.DEBUG)
util.run_wsgi_app(webapp.WSGIApplication([(r"/", HomeHandler)]))
self.redirect('/')

jinja_environment = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__))
)

if __name__ == "__main__":
main()
app = webapp2.WSGIApplication(
[('/', HomeHandler), ('/logout', LogoutHandler)],
debug=True,
config=config
)

0 comments on commit 86ff558

Please sign in to comment.