Source

filmaster-api-sample / apiexplorer.py

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

import time

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', '{}')
        out = ''
        error = ''

        try:
            if method in ('post', 'put'):
                args = (json.loads(data), )
            else:
                args = ()
            if method == 'get' or self.request.method == 'POST':
                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)
        except urllib2.HTTPError, e:
            error = "HTTPError %d" % e.code
            out = e.read()
        except Exception, e:
            error = repr(e)

        params = urlencode(dict(
            uri=uri.encode('utf-8'),
            method=method,
            data=data,
        ))
        permalink = "/api-explorer/?" + params

        self._response(
                response=out,
                uri=uri,
                method=method,
                error=error,
                data=data,
                permalink=permalink,
        )

    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" />
            <a href="%(permalink)s">#</a>
            <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)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.