Search code examples
javascriptpythonhtmlcross-language

Python in HTML Code


I have a Python file, called function.py, which contains this code:

def double(x):
    return x * 2

I also have this HTML code:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <script>
  alert(double(4));
  </script>
</body>
</html>

Is there a way for me to load the Python file in HTML of JavaScript, or is that impossible?


Solution

  • No. You cannot execute python directly in your web page. The web page is in the browser and the browser does not know how to execute python.

    So, the python needs to run on the server. You have a couple options for how you can access the python on the server from your web page:

    1. You can use a template system that allows you to insert python generated results in the web page BEFORE it is sent to the browser so when it gets to the browser, your python code has already been run and the results were placed into the web page for your page Javascript to access in the browser.

    2. You can make an Ajax call with Javascript from your web page to your server and you can code your python server to respond to that Ajax call and return results. The Javascript in the web page can then do whatever it wants to with the results of the Ajax call.