├── .gitignore ├── LICENSE.txt ├── README.rst ├── botocore_tornado ├── __init__.py ├── endpoint.py ├── operation.py ├── service.py └── session.py ├── setup.py └── test.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.gitignore.io 2 | 3 | ### Python ### 4 | # Byte-compiled / optimized / DLL files 5 | __pycache__/ 6 | *.py[cod] 7 | 8 | # C extensions 9 | *.so 10 | 11 | # Distribution / packaging 12 | .Python 13 | env/ 14 | build/ 15 | develop-eggs/ 16 | dist/ 17 | downloads/ 18 | eggs/ 19 | lib/ 20 | lib64/ 21 | parts/ 22 | sdist/ 23 | var/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | 46 | # Translations 47 | *.mo 48 | *.pot 49 | 50 | # Django stuff: 51 | *.log 52 | 53 | # Sphinx documentation 54 | docs/_build/ 55 | 56 | # PyBuilder 57 | target/ 58 | 59 | *.sublime-project 60 | *.sublime-workspace -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Simon Hewitt 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | botocore-tornado 2 | ================ 3 | 4 | This module provides subclasses of `botocore `__ 5 | classes that use the tornado AsyncHTTPClient to make requests. As far as 6 | possible, the api is kept the same as the botocore api, the only difference is 7 | that Operation.call returns a Future that is resolved when the http request is 8 | complete. 9 | 10 | 11 | Installation 12 | ------------ 13 | 14 | .. code-block:: bash 15 | 16 | pip install botocore-tornado 17 | 18 | 19 | Example 20 | ------- 21 | 22 | Uploading a file to S3: 23 | 24 | .. code-block:: python 25 | 26 | import botocore.session 27 | 28 | session = botocore.session.get_session() 29 | s3 = session.get_service('s3') 30 | endpoint = s3.get_endpoint(region) 31 | 32 | fp = open('./testfile.txt', 'rb') 33 | operation = s3.get_operation('PutObject') 34 | http_response, response_data = operation.call(endpoint, 35 | bucket=bucket, 36 | key=key + '/' + filename, 37 | body=fp) 38 | 39 | 40 | Using botocore-tornado: 41 | 42 | .. code-block:: python 43 | 44 | from tornado.ioloop import IOLoop 45 | from tornado import gen 46 | import botocore_tornado.session 47 | 48 | @gen.coroutine 49 | def main_async(): 50 | session = botocore_tornado.session.get_session() 51 | s3 = session.get_service('s3') 52 | endpoint = s3.get_endpoint(region) 53 | 54 | fp = open('./testfile.txt', 'rb') 55 | operation = s3.get_operation('PutObject') 56 | http_response, response_data = yield operation.call(endpoint, 57 | bucket=bucket, 58 | key=key + '/' + filename, 59 | body=fp) 60 | print response_data 61 | 62 | IOLoop.instance().run_sync(main_async) 63 | -------------------------------------------------------------------------------- /botocore_tornado/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = '0.93.1' 2 | -------------------------------------------------------------------------------- /botocore_tornado/endpoint.py: -------------------------------------------------------------------------------- 1 | import botocore.endpoint 2 | from tornado import gen 3 | from tornado.httpclient import AsyncHTTPClient, HTTPRequest 4 | 5 | 6 | class AsyncEndpoint(botocore.endpoint.Endpoint): 7 | """Subclass of Endpoint that uses AsyncHTTPClient to make requests. 8 | The make_request method is wrapped in a coroutine""" 9 | 10 | def __init__(self, *args, **kwargs): 11 | super(AsyncEndpoint, self).__init__(*args, **kwargs) 12 | self.http_client = AsyncHTTPClient() 13 | 14 | @gen.coroutine 15 | def _send_request(self, request_dict, operation_model): 16 | request = self.create_request(request_dict, operation_model) 17 | body = request.body 18 | # handle the case when body is a file-like object. HTTPRequest expects 19 | # it to be a string, so we just read all of it here. 20 | if body is not None and hasattr(body, 'read'): 21 | body = body.read() 22 | # for some reason, the default transport (httplib) defaults to sending 23 | # an empty string as the body, instead of nothing, so here we check 24 | # if this is a PUT method and default the body to the empty string 25 | elif body is None and request.method == 'PUT': 26 | body = '' 27 | http_request = HTTPRequest( 28 | url=request.url, headers=request.headers, 29 | method=request.method, body=body) 30 | http_response = yield self.http_client.fetch(http_request) 31 | protocol = operation_model.metadata['protocol'] 32 | response_dict = { 33 | 'headers': http_response.headers, 34 | 'status_code': http_response.code, 35 | } 36 | if response_dict['status_code'] >= 300: 37 | response_dict['body'] = http_response.body 38 | elif operation_model.has_streaming_output: 39 | response_dict['body'] = botocore.response.StreamingBody( 40 | http_response.body, response_dict['headers'].get('content-length')) 41 | else: 42 | response_dict['body'] = http_response.body 43 | parser = botocore.parsers.create_parser(protocol) 44 | parsed = parser.parse( 45 | response_dict, operation_model.output_shape) 46 | raise gen.Return((http_response, parsed)) 47 | 48 | 49 | class EndpointCreator(botocore.endpoint.EndpointCreator): 50 | def _get_endpoint(self, service_model, region_name, endpoint_url, 51 | verify, response_parser_factory): 52 | """Copied from botocore.endpoint.EndpointCreator._get_endpoint 53 | so that the custom get_endpoint_complex can be used""" 54 | service_name = service_model.signing_name 55 | endpoint_prefix = service_model.endpoint_prefix 56 | user_agent = self._user_agent 57 | event_emitter = self._event_emitter 58 | user_agent = self._user_agent 59 | return get_endpoint_complex(service_name, endpoint_prefix, 60 | region_name, endpoint_url, 61 | verify, user_agent, event_emitter, 62 | response_parser_factory) 63 | 64 | 65 | def get_endpoint(service, region_name, endpoint_url, verify=None): 66 | """Copied from botocore.endpoint.get_endpoint so that the custom 67 | get_endpoint_complex can be used""" 68 | service_name = getattr(service, 'signing_name', service.endpoint_prefix) 69 | endpoint_prefix = service.endpoint_prefix 70 | session = service.session 71 | event_emitter = session.get_component('event_emitter') 72 | user_agent = session.user_agent() 73 | return get_endpoint_complex(service_name, endpoint_prefix, 74 | region_name, endpoint_url, verify, user_agent, 75 | event_emitter) 76 | 77 | 78 | 79 | def get_endpoint_complex(service_name, endpoint_prefix, 80 | region_name, endpoint_url, verify, 81 | user_agent, event_emitter, 82 | response_parser_factory=None): 83 | """Copied from botocore.endpoint.get_endpoint_complex so that the 84 | AsyncEndpoint can be returned""" 85 | proxies = botocore.endpoint._get_proxies(endpoint_url) 86 | verify = botocore.endpoint._get_verify_value(verify) 87 | return AsyncEndpoint( 88 | region_name, endpoint_url, 89 | user_agent=user_agent, 90 | endpoint_prefix=endpoint_prefix, 91 | event_emitter=event_emitter, 92 | proxies=proxies, 93 | verify=verify, 94 | response_parser_factory=response_parser_factory) 95 | -------------------------------------------------------------------------------- /botocore_tornado/operation.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | import botocore.operation 4 | from botocore.signers import RequestSigner 5 | from tornado import gen 6 | 7 | logger = logging.getLogger(__name__) 8 | 9 | 10 | class AsyncOperation(botocore.operation.Operation): 11 | 12 | @gen.coroutine 13 | def call(self, endpoint, **kwargs): 14 | from .endpoint import AsyncEndpoint 15 | assert isinstance(endpoint, AsyncEndpoint) 16 | # from here on is copied from botocore.operation.Operation.call, with 17 | # the yield added on endpoint.make_request, and the response returned 18 | # through raising a gen.Return 19 | logger.debug("%s called with kwargs: %s", self, kwargs) 20 | # It probably seems a little weird to be firing two different 21 | # events here. The reason is that the first event is fired 22 | # with the parameters exactly as supplied. The second event 23 | # is fired with the built parameters. Generally, it's easier 24 | # to manipulate the former but at times, like with ReST operations 25 | # that build an XML or JSON payload, you have to wait for 26 | # build_parameters to do it's job and the latter is necessary. 27 | event = self.session.create_event('before-parameter-build', 28 | self.service.endpoint_prefix, 29 | self.name) 30 | self.session.emit(event, endpoint=endpoint, 31 | model=self.model, 32 | params=kwargs) 33 | request_dict = self.build_parameters(**kwargs) 34 | 35 | service_name = self.service.service_name 36 | service_model = self.session.get_service_model(service_name) 37 | 38 | signature_version, region_name = \ 39 | self._get_signature_version_and_region( 40 | endpoint, service_model) 41 | 42 | credentials = self.session.get_credentials() 43 | event_emitter = self.session.get_component('event_emitter') 44 | signer = RequestSigner(service_model.service_name, 45 | region_name, service_model.signing_name, 46 | signature_version, credentials, 47 | event_emitter) 48 | 49 | event = self.session.create_event('before-call', 50 | self.service.endpoint_prefix, 51 | self.name) 52 | # The operation kwargs is being passed in kwargs to support 53 | # handlers that still depend on this value. Eventually 54 | # everything should move over to the model/endpoint args. 55 | self.session.emit(event, endpoint=endpoint, 56 | model=self.model, 57 | params=request_dict, 58 | operation=self, 59 | request_signer=signer) 60 | 61 | # Here we register to the specific request-created event 62 | # for this operation. Since it's possible to run the same 63 | # operation in multiple threads, we used a lock to prevent 64 | # issues. It's possible a request will be signed more than 65 | # once. Once the request has been made, we unregister the 66 | # handler. 67 | def request_created(request, **kwargs): 68 | # This first check lets us quickly determine when 69 | # a request has already been signed without needing 70 | # to acquire the lock. 71 | if not getattr(request, '_is_signed', False): 72 | with self._lock: 73 | if not getattr(request, '_is_signed', False): 74 | signer.sign(self.name, request) 75 | request._is_signed = True 76 | 77 | event_emitter.register('request-created.{0}.{1}'.format( 78 | self.service.endpoint_prefix, self.name), request_created) 79 | 80 | try: 81 | response = yield endpoint.make_request(self.model, request_dict) 82 | finally: 83 | event_emitter.unregister('request-created.{0}.{1}'.format( 84 | self.service.endpoint_prefix, self.name), request_created) 85 | 86 | event = self.session.create_event('after-call', 87 | self.service.endpoint_prefix, 88 | self.name) 89 | self.session.emit(event, 90 | http_response=response[0], 91 | model=self.model, 92 | operation=self, 93 | parsed=response[1]) 94 | raise gen.Return(response) 95 | -------------------------------------------------------------------------------- /botocore_tornado/service.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | import botocore.service 4 | 5 | from .endpoint import EndpointCreator 6 | from .operation import AsyncOperation 7 | 8 | logger = logging.getLogger(__name__) 9 | 10 | 11 | class AsyncService(botocore.service.Service): 12 | 13 | def _create_operation_objects(self): 14 | logger.debug("Creating operation objects for: %s", self) 15 | operations = [] 16 | for operation_name in self._operations_data: 17 | data = self._operations_data[operation_name] 18 | data['name'] = operation_name 19 | model = self._model.operation_model(operation_name) 20 | op = AsyncOperation(self, data, model) 21 | operations.append(op) 22 | return operations 23 | 24 | def get_endpoint(self, region_name=None, is_secure=True, 25 | endpoint_url=None, verify=None): 26 | """ 27 | Return the Endpoint object for this service in a particular 28 | region. 29 | 30 | :type region_name: str 31 | :param region_name: The name of the region. 32 | 33 | :type is_secure: bool 34 | :param is_secure: True if you want the secure (HTTPS) endpoint. 35 | 36 | :type endpoint_url: str 37 | :param endpoint_url: You can explicitly override the default 38 | computed endpoint name with this parameter. If this arg is 39 | provided then neither ``region_name`` nor ``is_secure`` 40 | is used in building the final ``endpoint_url``. 41 | ``region_name`` can still be useful for services that require 42 | a region name independent of the endpoint_url (for example services 43 | that use Signature Version 4, which require a region name for 44 | use in the signature calculation). 45 | 46 | """ 47 | resolver = self.session.get_component('endpoint_resolver') 48 | region = self.session.get_config_variable('region') 49 | event_emitter = self.session.get_component('event_emitter') 50 | response_parser_factory = self.session.get_component( 51 | 'response_parser_factory') 52 | user_agent= self.session.user_agent() 53 | endpoint_creator = EndpointCreator(resolver, region, event_emitter, 54 | user_agent) 55 | kwargs = {'service_model': self._model, 'region_name': region_name, 56 | 'is_secure': is_secure, 'endpoint_url': endpoint_url, 57 | 'verify': verify, 58 | 'response_parser_factory': response_parser_factory} 59 | if self._has_custom_signature_version: 60 | kwargs['signature_version'] = self.signature_version 61 | 62 | return endpoint_creator.create_endpoint(**kwargs) 63 | 64 | 65 | def get_service(session, service_name, provider, api_version=None): 66 | """ 67 | Return a Service object for a given provider name and service name. 68 | 69 | :type service_name: str 70 | :param service_name: The name of the service. 71 | 72 | :type provider: Provider 73 | :param provider: The Provider object associated with the session. 74 | """ 75 | logger.debug("Creating service object for: %s", service_name) 76 | return AsyncService(session, provider, service_name) 77 | -------------------------------------------------------------------------------- /botocore_tornado/session.py: -------------------------------------------------------------------------------- 1 | import botocore.session 2 | import botocore_tornado.service 3 | 4 | 5 | class AsyncSession(botocore.session.Session): 6 | def get_service(self, service_name, api_version=None): 7 | """ 8 | Get information about a service. 9 | 10 | :type service_name: str 11 | :param service_name: The name of the service (e.g. 'ec2') 12 | 13 | :returns: :class:`botocore.service.Service` 14 | """ 15 | service = botocore_tornado.service.get_service(self, service_name, 16 | self.provider, 17 | api_version=api_version) 18 | event = self.create_event('service-created') 19 | self._events.emit(event, service=service) 20 | return service 21 | 22 | 23 | def get_session(env_vars=None): 24 | return AsyncSession(env_vars) 25 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | distutils/setuptools install script. 5 | """ 6 | 7 | import botocore_tornado 8 | 9 | from setuptools import setup, find_packages 10 | 11 | 12 | def read(filename): 13 | try: 14 | return open(filename).read() 15 | except (OSError, IOError): 16 | return "" 17 | 18 | 19 | setup( 20 | name='botocore-tornado', 21 | version=botocore_tornado.__version__, 22 | description='botocore subclasses that uses AsyncHTTPClient', 23 | long_description=read('README.rst'), 24 | author='Simon Hewitt', 25 | author_email='simon@qudos.com.com', 26 | url='https://github.com/qudos-com/botocore-tornado', 27 | scripts=[], 28 | packages=find_packages(exclude=['tests*']), 29 | package_dir={'botocore_tornado': 'botocore_tornado'}, 30 | include_package_data=True, 31 | install_requires=['botocore==0.93.0', 32 | 'tornado>=4.0.0'], 33 | license=read("LICENSE.txt"), 34 | classifiers=( 35 | 'Intended Audience :: Developers', 36 | 'Intended Audience :: System Administrators', 37 | 'Natural Language :: English', 38 | 'License :: OSI Approved :: MIT License', 39 | 'Programming Language :: Python', 40 | 'Programming Language :: Python :: 2.6', 41 | 'Programming Language :: Python :: 2.7', 42 | # not tested on python3 yet! 43 | # 'Programming Language :: Python :: 3', 44 | # 'Programming Language :: Python :: 3.3', 45 | ), 46 | ) 47 | -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | import botocore_tornado.session 2 | import botocore.session 3 | from tornado import gen 4 | from tornado.ioloop import IOLoop 5 | 6 | bucket = 'botocore-tornado-test' # change this to your bucket name 7 | key = 'xyzzy' # a subfolder under the bucket 8 | filename = 'testfile.txt' # the file we will put into S3 9 | region = 'us-east-1' # change this to your region 10 | acl = 'public-read' # we are going to set the ACL to public-read so we can access the file via a url 11 | 12 | 13 | @gen.coroutine 14 | def main_async(): 15 | session = botocore_tornado.session.get_session() 16 | session.set_debug_logger() 17 | session.set_debug_logger('botocore_tornado') 18 | s3 = session.get_service('s3') 19 | endpoint = s3.get_endpoint(region) 20 | 21 | print "=========================" 22 | print "====== ASYNC TEST =======" 23 | print "=========================" 24 | 25 | print 26 | print "uploading the file to s3" 27 | fp = open('./' + filename, 'rb') 28 | operation = s3.get_operation('PutObject') 29 | http_response, response_data = yield operation.call(endpoint, 30 | bucket=bucket, 31 | key=key + '/' + filename, 32 | body=fp) 33 | 34 | print http_response 35 | print response_data 36 | print 37 | print "getting s3 object properties of file we just uploaded" 38 | operation = s3.get_operation('GetObjectAcl') 39 | http_response, response_data = yield operation.call(endpoint, 40 | bucket=bucket, 41 | key=key + '/' + filename) 42 | print http_response 43 | print response_data 44 | print 45 | print "setting the acl to public-read" 46 | operation = s3.get_operation('PutObjectAcl') 47 | http_response, response_data = yield operation.call(endpoint, 48 | bucket=bucket, 49 | key=key + '/' + filename, 50 | acl=acl) 51 | print http_response 52 | print response_data 53 | print 54 | print "The url of the object is:" 55 | print 56 | print 'http://'+bucket+'.s3.amazonaws.com/' + key + '/' + filename 57 | operation = s3.get_operation('DeleteObject') 58 | http_response, response_data = yield operation.call(endpoint, 59 | bucket=bucket, 60 | key=key + '/' + filename) 61 | print http_response 62 | print response_data 63 | 64 | 65 | def main_sync(): 66 | session = botocore.session.get_session() 67 | session.set_debug_logger() 68 | s3 = session.get_service('s3') 69 | endpoint = s3.get_endpoint(region) 70 | 71 | print "=========================" 72 | print "====== SYNC TEST ========" 73 | print "=========================" 74 | 75 | print 76 | print "uploading the file to s3" 77 | 78 | fp = open('./' + filename, 'rb') 79 | operation = s3.get_operation('PutObject') 80 | http_response, response_data = operation.call(endpoint, 81 | bucket=bucket, 82 | key=key + '/' + filename, 83 | body=fp) 84 | print http_response 85 | print response_data 86 | print 87 | print "getting s3 object properties of file we just uploaded" 88 | operation = s3.get_operation('GetObjectAcl') 89 | http_response, response_data = operation.call(endpoint, 90 | bucket=bucket, 91 | key=key + '/' + filename) 92 | print http_response 93 | print response_data 94 | print 95 | print "setting the acl to public-read" 96 | operation = s3.get_operation('PutObjectAcl') 97 | http_response, response_data = operation.call(endpoint, 98 | bucket=bucket, 99 | key=key + '/' + filename, 100 | acl=acl) 101 | print http_response 102 | print response_data 103 | print 104 | print "The url of the object is:" 105 | print 106 | print 'http://'+bucket+'.s3.amazonaws.com/' + key + '/' + filename 107 | operation = s3.get_operation('DeleteObject') 108 | http_response, response_data = operation.call(endpoint, 109 | bucket=bucket, 110 | key=key + '/' + filename) 111 | print http_response 112 | print response_data 113 | 114 | 115 | if __name__ == '__main__': 116 | with open(filename, 'w') as f: 117 | f.write("botocore tornado upload test file") 118 | IOLoop.instance().run_sync(main_async) 119 | main_sync() 120 | --------------------------------------------------------------------------------