Jump to content

How do I pass a function to & from JavaScript and Python?

Go to solution Solved by Eigenvektor,

The only way to communicate between front-end (e.g. JavaScript) and back-end (e.g. Python) is by sending requests. JavaScript code is executed by the browser, running on the user's computer. To communicate with the Python process running on your server, you need some form of network requests/responses between them. One typical example would be a REST API over HTTP(S).

 

5 hours ago, DefinitelyRus said:

What if I want to be able to process data first and then send it, how do I go about doing such?

You would process the data in JavaScript, then send it to the Python process. You can't call Python functions directly. Even if JS/Python are running on the same machine, you need some form of Inter-Process Communication (IPC), which is essentially the same, except it doesn't necessarily have to go over the network first.

 

It's basically the same as calling a method and passing method arguments and getting a return value. Except the arguments go over the network in some format suitable for exchange (e.g. JSON) and the method's return value is likewise passed back over the network.

 

5 hours ago, DefinitelyRus said:

A janky alternative I thought of doing instead is constantly updating a JSON file or pushing the JSON string to JavaScript using some REST API, but that leads to unnecessary hardware load and can be inaccurate.

What do you mean by inaccurate in this context? Using e.g. a REST API and sending JSON to and fro is exactly how this stuff works. You can use protocols other than HTTP(S), you can use concepts other than REST and you can use an interchange format other than JSON. But the basic mechanism remains the same:

 

You send a request containing data ("method call with arguments"), the server does something with it ("the method executes") and you receive a response ("the return value").

 

Of course there are some differences. While a method call can typically only fail due to invalid arguments, you get the added complexity of possible errors due to e.g. network outage that you need to take into account.

 

5 hours ago, DefinitelyRus said:

Edit: I should probably mention... The API I made is a framework for an RPG game, handling mechanics like character stats and interactions. The website's purpose is to give the game proper visuals and effects, The reason I'm not adapting it to a Python-based game engine instead is because (1) I want to fully understand the basics of bridging front-end and back-end and (2) because I don't want to rewrite some 4000 lines of code and debug any issues that typically stem from that.

In a game like this, the website is typically used to show these stats, while the server is responsible for storing them and also making sure the data remains valid. E.g. when someone opens the website, the website sends a request to the back-end that says "give me all available characters". The response could contain a list of character names and icons/images and/or basic stats.

 

This list is then shown to the user (in a visually appealing format). The user can click on a character, which triggers another request like: "Give me details for character X". The response contains the details, which are then presented to the user. If the user edits the character, a request with updated information is sent to the server, who updates the character's stats, then responds with the updated stats. The server validates the information, to make sure the stats are correct/acceptable.

 

To be more user friendly, the website will usually do the same, because it can do so without sending a request. But ultimately the server needs to validate the data, because you don't know whether the request is coming from your front-end, or if someone is making these calls directly in an attempt to cheat.

Context: I want to build some kind of website from scratch using an existing API I built for Python. As such, I want to be able to call functions from JavaScript to Python. I know it is possible to send/request data, but only readily available ones (at least from what my limited knowledge suggests). What if I want to be able to process data first and then send it, how do I go about doing such?

 

I have looked around and posted something similar before:

How do developers send/request/receive data between front-end and back-end? (LTT Forums; by me)
Flask: Communication between JS and Python (Stack Overflow)

Is it possible to call a Python function from a JavaScript function? (Reddit)

 

... However, these don't quite answer the question I'm having. It appears to be possible but I don't know where to start or what to look for. A janky alternative I thought of doing instead is constantly updating a JSON file or pushing the JSON string to JavaScript using some REST API, but that leads to unnecessary hardware load and can be inaccurate. Please advise, thanks. 😄

 

Edit: I should probably mention... The API I made is a framework for an RPG game, handling mechanics like character stats and interactions. The website's purpose is to give the game proper visuals and effects, The reason I'm not adapting it to a Python-based game engine instead is because (1) I want to fully understand the basics of bridging front-end and back-end and (2) because I don't want to rewrite some 4000 lines of code and debug any issues that typically stem from that.

Edited by DefinitelyRus
Appendix

"USB 3.2 Gen 2x2"

Link to post
Share on other sites

The only way to communicate between front-end (e.g. JavaScript) and back-end (e.g. Python) is by sending requests. JavaScript code is executed by the browser, running on the user's computer. To communicate with the Python process running on your server, you need some form of network requests/responses between them. One typical example would be a REST API over HTTP(S).

 

5 hours ago, DefinitelyRus said:

What if I want to be able to process data first and then send it, how do I go about doing such?

You would process the data in JavaScript, then send it to the Python process. You can't call Python functions directly. Even if JS/Python are running on the same machine, you need some form of Inter-Process Communication (IPC), which is essentially the same, except it doesn't necessarily have to go over the network first.

 

It's basically the same as calling a method and passing method arguments and getting a return value. Except the arguments go over the network in some format suitable for exchange (e.g. JSON) and the method's return value is likewise passed back over the network.

 

5 hours ago, DefinitelyRus said:

A janky alternative I thought of doing instead is constantly updating a JSON file or pushing the JSON string to JavaScript using some REST API, but that leads to unnecessary hardware load and can be inaccurate.

What do you mean by inaccurate in this context? Using e.g. a REST API and sending JSON to and fro is exactly how this stuff works. You can use protocols other than HTTP(S), you can use concepts other than REST and you can use an interchange format other than JSON. But the basic mechanism remains the same:

 

You send a request containing data ("method call with arguments"), the server does something with it ("the method executes") and you receive a response ("the return value").

 

Of course there are some differences. While a method call can typically only fail due to invalid arguments, you get the added complexity of possible errors due to e.g. network outage that you need to take into account.

 

5 hours ago, DefinitelyRus said:

Edit: I should probably mention... The API I made is a framework for an RPG game, handling mechanics like character stats and interactions. The website's purpose is to give the game proper visuals and effects, The reason I'm not adapting it to a Python-based game engine instead is because (1) I want to fully understand the basics of bridging front-end and back-end and (2) because I don't want to rewrite some 4000 lines of code and debug any issues that typically stem from that.

In a game like this, the website is typically used to show these stats, while the server is responsible for storing them and also making sure the data remains valid. E.g. when someone opens the website, the website sends a request to the back-end that says "give me all available characters". The response could contain a list of character names and icons/images and/or basic stats.

 

This list is then shown to the user (in a visually appealing format). The user can click on a character, which triggers another request like: "Give me details for character X". The response contains the details, which are then presented to the user. If the user edits the character, a request with updated information is sent to the server, who updates the character's stats, then responds with the updated stats. The server validates the information, to make sure the stats are correct/acceptable.

 

To be more user friendly, the website will usually do the same, because it can do so without sending a request. But ultimately the server needs to validate the data, because you don't know whether the request is coming from your front-end, or if someone is making these calls directly in an attempt to cheat.

Remember to either quote or @mention others, so they are notified of your reply

Link to post
Share on other sites

On 4/9/2022 at 1:40 AM, DefinitelyRus said:

Context: I want to build some kind of website from scratch using an existing API I built for Python. As such, I want to be able to call functions from JavaScript to Python. I know it is possible to send/request data, but only readily available ones (at least from what my limited knowledge suggests). What if I want to be able to process data first and then send it, how do I go about doing such?

 

I have looked around and posted something similar before:

How do developers send/request/receive data between front-end and back-end? (LTT Forums; by me)
Flask: Communication between JS and Python (Stack Overflow)

Is it possible to call a Python function from a JavaScript function? (Reddit)

 

... However, these don't quite answer the question I'm having. It appears to be possible but I don't know where to start or what to look for. A janky alternative I thought of doing instead is constantly updating a JSON file or pushing the JSON string to JavaScript using some REST API, but that leads to unnecessary hardware load and can be inaccurate. Please advise, thanks. 😄

 

Edit: I should probably mention... The API I made is a framework for an RPG game, handling mechanics like character stats and interactions. The website's purpose is to give the game proper visuals and effects, The reason I'm not adapting it to a Python-based game engine instead is because (1) I want to fully understand the basics of bridging front-end and back-end and (2) because I don't want to rewrite some 4000 lines of code and debug any issues that typically stem from that.

 

Flask(Python web framework library) lets you do this thing exactly. Follow a flask tutorial to get a better understanding of how it works and you will understand how to pass information between the two. Probably not the answer you want, but it is the one you need. Build a simple website using Flask and I promise you will understand how to accomplish your goal.

CPU: Ryzen 5950X Ram: Corsair Vengeance 32GB DDR4 3600 CL14 | Graphics: GIGABYTE GAMING OC RTX 3090 |  Mobo: GIGABYTE B550 AORUS MASTER | Storage: SEAGATE FIRECUDA 520 2TB PSU: Be Quiet! Dark Power Pro 12 - 1500W | Monitor: Acer Predator XB271HU & LG C1

 

Link to post
Share on other sites

On 4/9/2022 at 1:30 PM, Eigenvektor said:

What do you mean by inaccurate in this context?

In cases where extremely time-sensitive info needs to be transferred, like in fast-paced reflex based games. I suppose that's an issue that will be present regardless because of network latency, so it was sort of redundant for me to ask. 😅

On 4/9/2022 at 1:30 PM, Eigenvektor said:

In a game like this, the website is typically used to show these stats, while the server is responsible for storing them and also making sure the data remains valid. E.g. when someone opens the website, the website sends a request to the back-end that says "give me all available characters". The response could contain a list of character names and icons/images and/or basic stats.

 

This list is then shown to the user (in a visually appealing format). The user can click on a character, which triggers another request like: "Give me details for character X". The response contains the details, which are then presented to the user. If the user edits the character, a request with updated information is sent to the server, who updates the character's stats, then responds with the updated stats. The server validates the information, to make sure the stats are correct/acceptable.

 

To be more user friendly, the website will usually do the same, because it can do so without sending a request. But ultimately the server needs to validate the data, because you don't know whether the request is coming from your front-end, or if someone is making these calls directly in an attempt to cheat.

My intention with this was to have Python do 99% of the data processing while the front-end is literally just a pretty face and nothing else. But yeah, I should consider doing this instead. It'll solve the problem I was having too. Thanks so much!

"USB 3.2 Gen 2x2"

Link to post
Share on other sites

13 hours ago, Remixt said:

 

Flask(Python web framework library) lets you do this thing exactly. Follow a flask tutorial to get a better understanding of how it works and you will understand how to pass information between the two. Probably not the answer you want, but it is the one you need. Build a simple website using Flask and I promise you will understand how to accomplish your goal.

I'll look into this as well. Though, I think I'll have to redo some code anyway. Thanks still! 😄 

"USB 3.2 Gen 2x2"

Link to post
Share on other sites

6 hours ago, DefinitelyRus said:

In cases where extremely time-sensitive info needs to be transferred, like in fast-paced reflex based games. I suppose that's an issue that will be present regardless because of network latency, so it was sort of redundant for me to ask. 😅

Yeah, latency is an issue you need to deal with in this case. Fast paced games typically use their own protocol (rather than HTTP) over UDP instead of TCP to keep network overhead as low as possible. They typically aren't browser based either.

 

6 hours ago, DefinitelyRus said:

My intention with this was to have Python do 99% of the data processing while the front-end is literally just a pretty face and nothing else. But yeah, I should consider doing this instead. It'll solve the problem I was having too. Thanks so much!

Sure, keep as much processing on the server side as possible. The server is ultimately responsible for making sure data is valid. You should never trust the client, because users can easily manipulate the JS running in the browser or call your API directly. Duplicating some stuff in the browser is mostly for convenience, so the client can e.g. show a hint that input is invalid without having to make a request each time.

Remember to either quote or @mention others, so they are notified of your reply

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×