Is there a way to pass a Python variable to Javascript without writing it to a file?

Viewed 550

Let's say I have a simple Python variable, such as the following:

x = 5

I'd like to create a web page that uses javascript to further process that variable, running on the same computer (a Raspberry Pi).

<!DOCTYPE html>
<html>
<body>

<script>
document.write(x);
</script>

</body>
</html>

Because the Raspberry Pi uses a micro SD card, I would like to limit the number of read/write cycles. Is there a way to store this Python variable in memory (or some other way) which could be accessed by the Javascript code?

I know some will suggest rewriting the Python code in Javascript, but I already have a large Python program that I would prefer NOT to have to rewrite due to time and the original effort involved in its creation. And if you are curious, I'm using the Javascript to display data with Highcharts - which is preferred for my project.

3 Answers

I can't think of a direct way of achieving this. But I think you could use socket-io on both sides and communicate through it.

EDIT:

As S.Pellegrino noted, depending on op's needs, building a REST API from what is called in the question a 'large Python program' might be a good option.

A couple ideas:

  1. Run a web server in your Python application and expose an endpoint that returns that data. In your Javascript app, call this API (accessible on 0.0.0.0) and consume the data. Caveat: you'll have to setup a web server in your Python app and keep it running.

Here's a better idea:

  1. Run a Redis instance on your Pi. Redis is an in-memory cache provider, and you can configure it not to persist any data to the disk. As such, it'll become an in-memory broker between your Python and Javascript applications. Redis runs as a local web server on your Pi and exposes endpoints for writing and reading data. From your Python app, call the Redis endpoint to write some data, and from your Javascript app, call Redis to read what you need.

https://redis.io/topics/ARM

Related