Python Examples
This practice shows how to write a simple program that downloads and analyzes some content using the snapshots provided by content servers.
We'll be using the Decentraland Foundation's server at peer.decentraland.org, and Python 3 as our language of choice.
This is what we'll do:
Query the status of the content server.
Select and download a snapshot with a list of entities.
Print the type and ID of all referenced entities.
Let's begin our script with some preparations. We'll use standard library modules only, but in real code you'll probably want a more comfortable HTTP client (like the requests library).
# Make an HTTP GET request, return a file-like HTTP response.
def fetch(path):
url = f"https://peer.decentraland.org/{path}"
headers = { "User-Agent": "urllib" } # important on some servers (if empty, 403 Forbidden)
request = urllib.request.Request(url, headers=headers)
response = urllib.request.urlopen(request)
return responseOur simple helper makes an HTTP GET request, and returns the file-like response object. Nothing fancy. Let's use it to hit the /about endpoint and check the server's status:
# Check the server status:
about = json.load(fetch('about'))
if not about['healthy']:
print("Server not healthy!")
sys.exit(1)If we get past this point, the server is up and running (we got a 200 response) and reports being operational. We can request the current set of snapshots (which comes in JSON array format):
Snapshot files (especially for the longer time ranges) can be very large. For a quick experiment, let's grab the smallest in the list by numberOfEntities:
To download the content, we need the hash field of snapshot. We get the file URL by appending it to the content root:
The file we selected is small enough to buffer in memory, but let's pretend we don't know that and stream it. The first line is the snapshot header, and every line after that contains a JSON object.
Let's check the header, always a good idea:
Now we can process all entities in the snapshot, reading the response line by line. For our humble purposes, process means printing the entity type and ID:
This loop will start streaming, parsing and printing lines like these until it's done with the snapshot:
Cheers! We've used the snapshot system to explore some of the available content in Decentraland.
Remember you can find the full script in GitHub, along with a more advanced example.
Last updated