Last active
August 29, 2015 14:06
Revisions
-
dmitric revised this gist
Sep 18, 2014 . No changes.There are no files selected for viewing
-
dmitric revised this gist
Sep 18, 2014 . 1 changed file with 5 additions and 3 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -147,15 +147,17 @@ def _call(self, http_method, callback=None, **kwargs): # reset self.url self.reset_url() httpclient_args = [copy_of_url] httpclient_kwargs = { 'method': http_method } if http_method in ['GET', 'DELETE']: if kwargs: copy_of_url += '?' + urllib.urlencode(self._nested_dict_to_url(kwargs)) httpclient_kwargs['headers'] = self._generate_headers(copy_of_url) httpclient_args = [copy_of_url] elif http_method != 'GET' and kwargs: body = json.dumps(kwargs) -
dmitric revised this gist
Sep 8, 2014 . 1 changed file with 1 addition and 1 deletion.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -9,7 +9,7 @@ POST /buttons maps to api.buttons.post or GET accounts/:account_id maps to api.accounts.id(account_id).get ### Example usage -
dmitric revised this gist
Sep 8, 2014 . 1 changed file with 4 additions and 3 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -2,13 +2,14 @@ I __hate__ using third party language libraries because they are often just a crappier more OOP'd version of a nice rest api. Here's a sample framework for automatically generating call chains that map to the RESTful url. Just define the verbs and nouns you want to use in the resources set. And when the API changes or adds new endpoint, just toss em in there too! POST /buttons maps to api.buttons.post or GET accounts/:account_id: maps to api.accounts.id(account_id).get ### Example usage -
dmitric revised this gist
Sep 8, 2014 . 1 changed file with 1 addition and 1 deletion.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -2,7 +2,7 @@ I __hate__ using third party language libraries because they are often just a crappier more OOP'd version of a nice rest api. Here's a sample framework for automatically generating call chains that map to the RESTful url. Just define the verbs and nouns you want to use in the resources set. And when the api changes or adds new endpoint, just toss em in there too! "POST /buttons" maps to "api.buttons.post" -
dmitric revised this gist
Sep 8, 2014 . 1 changed file with 1 addition and 1 deletion.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -2,7 +2,7 @@ I __hate__ using third party language libraries because they are often just a crappier more OOP'd version of a nice rest api. Here's a sample framework for automatically generating call chains that map to the RESTful url. Just define the verbs and nouns you want to use in the resources set. "POST /buttons" maps to "api.buttons.post" -
dmitric revised this gist
Sep 8, 2014 . 1 changed file with 3 additions and 1 deletion.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,6 +1,8 @@ I __hate__ using third party language libraries because they are often just a crappier more OOP'd version of a nice rest api. Here's a sample framework for automatically generating call chains that map to the RESTful url. Just define what you want in the resources set. "POST /buttons" maps to "api.buttons.post" -
dmitric renamed this gist
Sep 8, 2014 . 1 changed file with 0 additions and 0 deletions.There are no files selected for viewing
File renamed without changes. -
dmitric revised this gist
Sep 8, 2014 . 2 changed files with 24 additions and 20 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,11 +1,31 @@ I __hate__ using third party language libraries because they are often just a crappier more OOP'd version of a nice rest api. Here's a sample framework for automatically generating call chains that map the the RESTful url. "POST /buttons" maps to "api.buttons.post" or "GET accounts/:account_id" maps to "api.accounts.id(account_id).get" ### Example usage ``` response = yield gen.Task(self.backend.coinbase.buttons.post, **{ "account_id": options.coinbase_account_id, "button": { "name": "Fund Journalism", "type": "buy_now", "subscription": False, "price_string": "0.0105", "price_currency_iso": "BTC", "custom": bitcoin_topic.hash(), "description": "Testing", "callback_url": callback_url, "variable_price": True, "choose_price": True, "custom_secure": True } }) ``` This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,16 +0,0 @@ -
dmitric revised this gist
Sep 8, 2014 . 1 changed file with 3 additions and 1 deletion.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,4 +1,6 @@ I hate using third party language libraries because they are often just a crappier more OOP'd version of a nice rest api. Here's a sample framework for automatically generating call chains that map the the RESTful url. EG. -
dmitric created this gist
Sep 8, 2014 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,9 @@ I hate using third party language libraries because they are often just a crappier more OOP'd version of a nice rest api. Here's a framework for automatically generating call chains that map the the RESTful url EG. "POST /buttons" maps to "api.buttons.post" or "GET accounts/:account_id" maps to "api.accounts.id(account_id).get" This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,201 @@ # -*- coding: utf-8 -*- # Copyright 2014 Dmitri Cherniak # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __all__ = ['Coinbase'] import urllib import functools import hashlib import hmac import time import json from tornado import httpclient, escape from tornado.options import define, options define("coinbase_api_secret") define("coinbase_api_key") class Coinbase(object): api_hostname = 'coinbase.com/api' api_version = 'v1' resources = set([ 'buttons', 'account_changes', 'account', 'balance', 'primary', 'addresses', 'create_order', 'orders', 'buys', 'contacts', 'currencies', 'exchange_rates', 'orders', 'recurring_payments', 'reports', 'sells', 'users' ]) def __init__(self, api_key=None, api_secret=None, blocking=False): self.api_key = api_key if api_key else options.coinbase_api_key self.api_secret = api_secret if api_secret else options.coinbase_api_secret self.blocking = blocking self.url = None if blocking: self.httpclient_instance = httpclient.HTTPClient() else: self.httpclient_instance = httpclient.AsyncHTTPClient() def __getattr__(self, name): ''' Builds API URL. Example: tornado_coinbase.Coinbase().buttons.post ''' if name in self.__class__.resources: self.url = '/'.join([self.url or self.api_endpoint, name]) return self else: raise AttributeError(name) def __repr__(self): return "%s(api_key=%s, url=%s)" % (self.__class__.__name__, self.api_key, self.url) @property def api_endpoint(self): return 'https://%s/%s' % (self.__class__.api_hostname, self.__class__.api_version) def id(self, id): ''' Append ID to constructed URL. Example: tornado_coinbase.Coinbase().buttons.id('code').orders.get(callback=lambda x: x) ''' self.url = '/'.join([self.url or self.api_endpoint, str(id)]) return self def reset_url(self): self.url = None def get(self, **kwargs): return self._call_check_blocking_first('GET', **kwargs) def post(self, **kwargs): return self._call_check_blocking_first('POST', **kwargs) def put(self, **kwargs): return self._call_check_blocking_first('PUT', **kwargs) def delete(self, **kwargs): return self._call_check_blocking_first('DELETE', **kwargs) def _call_check_blocking_first(self, http_method, **kwargs): if self.blocking: http_response = self._call(http_method, **kwargs) return self._parse_response(None, http_response) else: return self._call(http_method, **kwargs) def _generate_headers(self, url, body=None): nonce = int(time.time() * 1e6) message = str(nonce) + url + ('' if body is None else body) signature = hmac.new(self.api_secret.encode(), message.encode(), hashlib.sha256).hexdigest() headers = { 'ACCESS_KEY': self.api_key, 'ACCESS_SIGNATURE': signature, 'ACCESS_NONCE': str(nonce), 'Accept': 'application/json' } if body: headers.update({'Content-Type':'application/json'}) return headers def _call(self, http_method, callback=None, **kwargs): copy_of_url = self.url # reset self.url self.reset_url() httpclient_args = [copy_of_url] httpclient_kwargs = { 'method': http_method } if http_method == 'GET' or http_method == 'DELETE' and kwargs: httpclient_kwargs['headers'] = self._generate_headers(copy_of_url) httpclient_args = [copy_of_url + '?' + urllib.urlencode(self._nested_dict_to_url(kwargs))] elif http_method != 'GET' and kwargs: body = json.dumps(kwargs) httpclient_kwargs['headers'] = self._generate_headers(copy_of_url, body=body) httpclient_kwargs['body'] = body if not self.blocking: httpclient_args.append(functools.partial(self._parse_response, callback)) return self.httpclient_instance.fetch(*httpclient_args, **httpclient_kwargs) def _nested_dict_to_url(self, d): """ We want post vars of form: {'foo': 'bar', 'nested': {'a': 'b', 'c': 'd'}} to become (pre url-encoding): foo=bar&nested[a]=b&nested[c]=d """ stk = [] for key, value in d.items(): if isinstance(value, dict): n = {} for k, v in value.items(): n["%s[%s]" % (key, k)] = v stk.extend(self._nested_dict_to_url(n)) else: stk.append((key, value)) return stk def _parse_response(self, callback, response): """Parse a response from the API""" try: res = escape.json_decode(response.body) except Exception, e: e.args += ('API response was: %s' % response,) raise e if callback: callback(res) else: return res This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,16 @@ response = yield gen.Task(self.backend.coinbase.buttons.post, **{ "account_id": options.coinbase_account_id, "button": { "name": "Fund Journalism", "type": "buy_now", "subscription": False, "price_string": "0.0105", "price_currency_iso": "BTC", "custom": bitcoin_topic.hash(), "description": "Testing", "callback_url": callback_url, "variable_price": True, "choose_price": True, "custom_secure": True } })