Commits

Anonymous committed 9399780 Draft

api explorer

Comments (0)

Files changed (6)

+import webapp2
+from urllib import urlencode
+import pprint, json, urllib2, cgi, re
+
+from utils import gae
+from filmaster_auth import FilmasterOAuthClient
+
+import settings
+
+import logging
+logger = logging.getLogger(__name__)
+
+class FilmasterClientMixin(object):
+    def __init__(self, *args, **kw):
+        super(FilmasterClientMixin, self).__init__(*args, **kw)
+        self.filmaster_client = FilmasterOAuthClient(
+                settings.FILMASTER_APP_KEY,
+                settings.FILMASTER_APP_SECRET,
+        )
+
+class FilmasterClientHandler(FilmasterClientMixin, gae.BaseHandler):
+    def pre_dispatch(self):
+        access_token = self.session.get('access_token')
+        if access_token is None:
+            self.authorize()
+            return True
+        self.filmaster_client.set_access_token(access_token)
+
+    def authorize(self):
+        request_token = self.filmaster_client.fetch_request_token()
+        self.session['request_token'] = str(request_token)
+        next = urlencode({'next': self.request.path_qs})
+        callback_url = self.request.host_url + '/auth-cb/?' + next
+        authorize_url = self.filmaster_client.get_authorize_url(
+                request_token, callback_url=callback_url)
+        self.response.status = 302
+        self.response.location = authorize_url
+
+class AuthHandler(FilmasterClientMixin, gae.BaseHandler):
+    def get(self):
+        request_token = self.session['request_token']
+        verifier = self.request.params.get('oauth_verifier')
+        next = self.request.params.get('next', '/')
+
+        access_token = self.filmaster_client.fetch_access_token(request_token, verifier)
+        self.session['access_token'] = str(access_token)
+        self.response.status = 302
+        self.response.location = next
+
+class ApiExplorer(FilmasterClientHandler):
+    API_VERSION = "1.1"
+    def get(self):
+        uri = self.request.params.get('uri', '/profile/')
+        method = self.request.params.get('method', 'get')
+        data = self.request.params.get('data', '{}')
+        try:
+            if method in ('post', 'put'):
+                args = (json.loads(data), )
+            else:
+                args = ()
+
+            out = getattr(self.filmaster_client, method)("/%s%s" % (self.API_VERSION, uri), *args)
+            out = json.dumps(out, sort_keys=True, indent=4)
+            out = self.create_links(out)
+            error = ''
+        except Exception, e:
+            out = ''
+            error = str(e)
+
+        self._response(
+                response=out,
+                uri=uri,
+                method=method,
+                error=error,
+                data=data,
+        )
+
+    post = get
+
+
+    API_LINK_RE = re.compile('"/%s([^"]+)"' % API_VERSION.replace('.', r'\.'))
+
+    @classmethod
+    def create_links(cls, text):
+        def f(m):
+            uri = m.group(1)
+            qs = urlencode({'uri': uri})
+            return '<a href="/api-explorer/?%s">"/%s%s"</a>' % (qs, cls.API_VERSION, uri)
+        text = cls.API_LINK_RE.sub(f, text)
+        return text
+
+    def _response(self, **params):
+        template = """
+            <html>
+            <head>
+            <style>
+                [name=data] {width: 100%%; }
+                .get .data, .delete .data {display: none;}
+                [name=uri] {width:800px;}
+            </style>
+            <title>Filmaster API Explorer</title>
+            </head>
+            <body>
+            <h2>Filmaster API Explorer</h2>
+            <form method='POST' action="." class="%(method)s">
+            <select name='method' onchange="this.parentNode.className=this.value">
+                <option value="get" %(get_selected)s >GET</option>
+                <option value="post" %(post_selected)s >POST</option>
+                <option value="put" %(put_selected)s>PUT</option>
+                <option value="delete" %(delete_selected)s>DELETE</option>
+            </select>
+            http://api.filmaster.pl/%(api_version)s<input type="text" name="uri" value="%(uri)s" />
+            <input type="submit" />
+            <section class="data">
+            <label>request data:</lablel>
+            <textarea name="data">%(data)s</textarea>
+            </section>
+            </form>
+            <h2>%(error)s</h2>
+            <pre>%(response)s</pre>
+            </body>
+            </html>
+        """
+        method = params.get('method')
+        params.update(
+                ("%s_selected" % name, name == method and 'selected' or '') 
+                for name in ('get', 'post', 'put', 'delete'))
+        params['api_version'] = self.API_VERSION
+        self.response.headers['Content-Type'] = 'text/html'
+        self.response.write(template % params)
+

filmaster_auth.py

 
     API_BASE_URL = "http://api.filmaster.com"
     BASE_URL = 'http://filmaster.com'
+    
+    API_BASE_URL = "http://api.filmaster.pl"
+    BASE_URL = 'http://filmaster.pl'
 
     REQUEST_TOKEN_URL = BASE_URL + '/oauth/request/token/'
     ACCESS_TOKEN_URL = BASE_URL + '/oauth/access/token/'
 import webapp2
 
 from fbapp import FBApp
-from samplewebapp import SampleApp, SampleAppAuth
+from apiexplorer import AuthHandler, ApiExplorer
 import settings
 
 app = webapp2.WSGIApplication([
-        ('/', SampleApp),
-        ('/auth-cb/', SampleAppAuth),
-        ('/fbapp/', FBApp),
+        (r'/api-explorer/', ApiExplorer),
+        (r'/auth-cb/', AuthHandler),
+        (r'/fbapp/', FBApp),
 ], debug=True, config=settings.WEBAPP_CONFIG)
 
 

samplewebapp.py

-import webapp2
-import pprint, json, urllib2, cgi
-
-from utils import gae
-from filmaster_auth import FilmasterOAuthClient
-
-import settings
-
-import logging
-logger = logging.getLogger(__name__)
-
-class FilmasterClientMixin(object):
-    def dispatch(self):
-        self.filmaster_client = FilmasterOAuthClient(
-                settings.FILMASTER_APP_KEY,
-                settings.FILMASTER_APP_SECRET,
-        )
-        return super(FilmasterClientMixin, self).dispatch()
-
-class SampleApp(FilmasterClientMixin, gae.BaseHandler):
-    def authorize(self):
-        request_token = self.filmaster_client.fetch_request_token()
-        self.session['request_token'] = str(request_token)
-        authorize_url = self.filmaster_client.get_authorize_url(request_token, callback_url = self.request.host_url+'/auth-cb/')
-        self.response.status = 302
-        self.response.location = authorize_url
-
-    def get(self):
-        access_token = self.session.get('access_token')
-        if access_token is None:
-            return self.authorize()
-        self.filmaster_client.set_access_token(access_token)
-        profile = self.filmaster_client.get('/1.1/profile/')
-        out = pprint.pformat(profile)
-
-        self.response.headers['Content-Type'] = 'text/plain'
-        self.response.write(out)
-
-    class AppError(Exception):
-        pass
-
-class SampleAppAuth(FilmasterClientMixin, gae.BaseHandler):
-    def get(self):
-        request_token = self.session['request_token']
-        verifier = self.request.params.get('oauth_verifier')
-        access_token = self.filmaster_client.fetch_access_token(request_token, verifier)
-        self.session['access_token'] = str(access_token)
-        self.response.status = 302
-        self.response.location = '/'
-
 
     pprint(client.put('/1.1/profile/', {'latitude': '52.3', 'longitude': '21'}))
 
-#    pprint(client.get('/1.1/profile/showtimes/%s/?limit=5&include=channels.channel' % datetime.date.today()))
+    today = datetime.date.today()
+    showtimes = client.get('/1.1/profile/showtimes/%s/?limit=50&include=film' % today)
+    for s in showtimes['objects']:
+        print s['film']['title']
+        print s['film']['guess_rating']
 
-#    pprint(client.get('/1.1/profile/channels/?type=2'))
+    pprint(client.get('/1.1/profile/meta/film/jestes-bogiem/?include=channels&date=%s' % today))
         self.session_store = sessions.get_store(request=self.request)
 
         try:
+            if self.pre_dispatch():
+                return
             # Dispatch the request.
             webapp2.RequestHandler.dispatch(self)
         finally:
             # Save all sessions.
             self.session_store.save_sessions(self.response)
 
+    def pre_dispatch(self):
+        return False
+
     @webapp2.cached_property
     def session(self):
         # Returns a session using the default cookie key.