1 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
7 from appengine_wrappers import urlfetch
8 from future import Future
10 class _AsyncFetchDelegate(object):
11 def __init__(self, rpc):
15 return self._rpc.get_result()
17 def _MakeHeaders(username, password):
18 headers = { 'Cache-Control': 'max-age=0' }
19 if username is not None and password is not None:
20 headers['Authorization'] = 'Basic %s' % base64.encodestring(
21 '%s:%s' % (username, password))
24 class AppEngineUrlFetcher(object):
25 """A wrapper around the App Engine urlfetch module that allows for easy
28 def __init__(self, base_path=None):
29 self._base_path = base_path
31 def Fetch(self, url, username=None, password=None):
32 """Fetches a file synchronously.
34 if self._base_path is not None:
35 url = '%s/%s' % (self._base_path, url)
36 return urlfetch.fetch(url, headers=_MakeHeaders(username, password))
38 def FetchAsync(self, url, username=None, password=None):
39 """Fetches a file asynchronously, and returns a Future with the result.
41 if self._base_path is not None:
42 url = '%s/%s' % (self._base_path, url)
43 rpc = urlfetch.create_rpc()
44 urlfetch.make_fetch_call(rpc, url, headers=_MakeHeaders(username, password))
45 return Future(delegate=_AsyncFetchDelegate(rpc))