1

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?

halloleo
  • 9,216
  • 13
  • 64
  • 122

1 Answers1

2

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.

John S
  • 418
  • 4
  • 9
  • Thanks @JohnS. Yep, I guess that's the way to go. I just have used jQuery. Strange though that `import urllib` does _not_ give an error, while `import urllib.requests` _does_... – halloleo Jul 18 '20 at 10:45
  • That works too. Personally I prefer to keep code in the Python realm as much as possible. It keeps the linter happier as well as my brain. Also with jQuery you'll need to escape the $ using `__pragma__('alias', 'S', '$')` – John S Jul 18 '20 at 18:12