Skip to content
Advertisement

How to create temporary URL in OpenStack using python-swiftclient?

I’m using the python-swiftclient to connect to an OpenStack Object Store. Following some examples from the documentation I can now upload a file:

container = 'new-container'
local_file_path = 'file.txt'

conn = Connection(**OBJECT_STORE_INFO)
with open(local_file_path, 'r') as local:
    r = conn.put_object(
        container,
        local_file_path,
        contents=local.read(),
        content_type='application/zip'
    )
    print("File created")

This works great and I now want to create a temporary URL for that file. In the sources I found the function generate_temp_url(), which needs at least four arguments: path, seconds, key, method

For the path, the documentation says:

:param path: The full path to the Swift object or prefix if
    a prefix-based temporary URL should be generated. Example:
    /v1/AUTH_account/c/o or /v1/AUTH_account/c/prefix.

and I’m having trouble finding this path. I tried a couple variations (my local path, the URL of the file I get from the web interface) but nothing works. I can get the headers about the file

resp_headers = conn.head_object(container, local_file_path)

which returns this:

{'content-length': '12', 'accept-ranges': 'bytes', 'last-modified': 'Wed, 10 Feb 2021 16:10:19 GMT', 
'etag': '4d79d5df13513c295916112b9b3e25e0', 'x-timestamp': '1612973418.28837', 
'content-type': 'text/plain', 'x-trans-id': 'tx045dc3b415374a81a9a80-00602407c4', 
'date': 'Wed, 10 Feb 2021 16:20:20 GMT', 'age': '0', 'via': 'our.objectstore.com'}

But that doesn’t show any helpful information.

In this documentation it gives the following example:

Example: /v1/AUTH_account/c/o or: http://saio:8080/v1/AUTH_account/c/o

The direct url to my file is: https://8d078638c1a547c09e0b5f34834554f1.ourobjectstore.com/new-container/file.txt

So that doesn’t resemble the URLs in the example at all.

What is happening here? Where can I find this so called “path” so that I can create the temp URL?

Advertisement

Answer

In the end @RakshaSaini wrote the first comment pointing me to the official documentation here. It contained an example which didn’t work, but was close enough. I adjusted it as follows and now it works for us:

import hmac
from hashlib import sha1
from time import time
method = 'GET'
duration_in_seconds = 60 * 60 * 24  # 24 hours
expires = int(time() + duration_in_seconds)
path = '/new-container/file.txt'
key = b'the-temp-url-key'
hmac_body = f'{method}n{expires}n{path}'.encode('utf-8')
sig = hmac.new(key, hmac_body, sha1).hexdigest()
url = f'https://tenantid.ourobjectstore.com{path}?temp_url_sig={sig}&temp_url_expires={expires}'
print("URL", url)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement