0

I am using Python for backend and web scraping, and JavaScript for frontend to write a website. My python file is as below.

def fn1(param1, param2, param3):
  .......

def fn2(param1, param2, param3):
  .......

I want to call fn2() specifically within my js file's function and get a returned value. How do I do that?

3 Answers3

1

I think you're missing a few key concepts here.

What you're asking at the moment isn't really possible (To call your backend Python function within your JavaScript file).

What is possible is using REST apis to interact with your Python backend from JavaScript.

You can use python frameworks like Django or Flask to create backend Python APIS.

I suggest you do a bit of reading on REST, as it's the bread and butter for interacting with backends via front end web applications. Here is a good introduction to REST while using the Flask framework.

I think if you work your way through the above, then read about how to interact with API's via JavaScript. This stackoverflow answer here is a great resource on it.

user5513663
  • 11
  • 1
  • 2
  • I do agree implementing REST in the strictest sense _should_ be centred around states and entities. But it sounds like OP is relatively new to programming. I think the simplest way for him to achieve what he wants is to just setup a simple REST API, and return the data as JSON to display in his frontend. – user5513663 Aug 14 '21 at 00:05
  • I don't disagree that RPC wouldn't solve the problem, I just think that for a newer developer RPC isn't the most friendly thing to wrap your head around. For someone newer to the field and considering it's a front end interacting with a backend, I think REST is a simpler and less daunting solution. – user5513663 Aug 14 '21 at 00:12
0

In NodeJS, you can spawn a subprocess. You can write Python code to a file with fs and then run it with commands, eg py foo.py.

In regular JavaScript, you can't run Python unless you somehow manage to write a Python parser/interpreter in JavaScript. Otherwise, you just rely on a backend to run Python code.

acaiberii
  • 48
  • 1
  • 7
-2

As far as I know, you can't really mix languages (css and html don't count as languages for this one). You'd have to re-write parts of your code :/

Nerd
  • 19
  • 2