Search code examples
pythonurlurlopentranscrypt

How can I read the contents of an URL with Transcrypt? Where is urlopen() located?


In Transcrypt I try to read JSON data from a URL, so I try:

import urllib.request    
data = urllib.request.urlopen(data_url)

But I get the error "Import error, can't find [...] urllib.request". So urllib.request doesn't seem to be support; strangely though the top-level import urllib works, but with this I do not get to the urlopen() function...

Any idea where urlopen() is located in Transcrypt? Or is there another way to retrieve URLs?


Solution

  • I don't believe Transcrypt has the Python urllib library available. You will need to use a corresponding JavaScript library instead. I prefer axios, but you can also just use the built in XMLHttpRequest() or window.fetch()

    Here is a Python function you can incorporate that uses window.fetch():

    def fetch(url, callback):
        def check_response(response):
            if response.status != 200:
                console.error('Fetch error - Status Code: ' + response.status)
                return None
            return response.json()
    
        prom = window.fetch(url)
        resp = prom.then(check_response)
        resp.then(callback)
        prom.catch(console.error)
    

    Just call this fetch function from your Python code and pass in the URL and a callback to utilize the response after it is received.