Skip to content

Commit

Permalink
Make S3 URL style configurable
Browse files Browse the repository at this point in the history
  • Loading branch information
grampajoe committed Feb 10, 2014
1 parent c2c002f commit 2883db1
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
16 changes: 14 additions & 2 deletions flask_s3.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,20 @@ def url_for(endpoint, **values):
scheme = 'http'
if app.config['S3_USE_HTTPS']:
scheme = 'https'
bucket_path = '%s.%s' % (app.config['S3_BUCKET_NAME'],
app.config['S3_BUCKET_DOMAIN'])

if app.config['S3_URL_STYLE'] == 'host':
url_format = '%(bucket_name)s.%(bucket_domain)s'
elif app.config['S3_URL_STYLE'] == 'path':
url_format = '%(bucket_domain)s/%(bucket_name)s'
else:
raise ValueError('Invalid S3 URL style: "%s"'
% app.config['S3_URL_STYLE'])

bucket_path = url_format % {
'bucket_name': app.config['S3_BUCKET_NAME'],
'bucket_domain': app.config['S3_BUCKET_DOMAIN'],
}

if app.config['S3_CDN_DOMAIN']:
bucket_path = '%s' % app.config['S3_CDN_DOMAIN']
urls = app.url_map.bind(bucket_path, url_scheme=scheme)
Expand Down
12 changes: 12 additions & 0 deletions tests/test_flask_static.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,18 @@ def test_url_for_cdn_domain(self):
exp = 'https://foo.cloudfront.net/static/bah.js'
self.assertEquals(self.client_get(ufs).data, exp)

def test_url_for_url_style_path(self):
"""Tests that the URL returned uses the path style."""
self.app.config['S3_URL_STYLE'] = 'path'
ufs = "{{url_for('static', filename='bah.js')}}"
exp = 'https://s3.amazonaws.com/foo/static/bah.js'
self.assertEquals(self.client_get(ufs).data, exp)

def test_url_for_url_style_invalid(self):
"""Tests that an exception is raised for invalid URL styles."""
self.app.config['S3_URL_STYLE'] = 'balderdash'
ufs = "{{url_for('static', filename='bah.js')}}"
self.assertRaises(ValueError, self.client_get, ufs)


class S3Tests(unittest.TestCase):
Expand Down

0 comments on commit 2883db1

Please sign in to comment.