How to import python modules using Brython and Flask app

386 Views Asked by At

I am using Flask for my backend and brython for my client side since I need to use python modules that aren't available for javascript. At the moment, I am having trouble with importing modules from different folders. For instance, suppose I wanted to import test.py in brython. My file directory is as follows:

root
-- app.py

  • templates
    -- index.html
    -- test.py

I have also tried putting test.py into the root directory along with an __init__.py file, but with no luck. The example code is to follow.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <script src="https://cdnjs.cloudflare.com/ajax/libs/brython/3.8.8/brython.js" integrity="sha256-rA89wPrTJJQFWJaZveKW8jpdmC3t5F9rRkPyBjz8G04=" crossorigin="anonymous"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/brython/3.8.8/brython_stdlib.js" integrity="sha256-Gnrw9tIjrsXcZSCh/wos5Jrpn0bNVNFJuNJI9d71TDs=" crossorigin="anonymous"></script>

    <title>{{ title }}</title>
</head>
<body onload="brython()">
    <h3>Testing Brython with Flask</h3>
    <div id="test">
        
    </div>

    <script type="text/python">
        from browser import document
        import test

        value = test.do_math(4,6)
        output = 'my number is '+(str(value))
        document['test'] <= output
    </script>
</body>
</html>

test.py

def do_math(m,n):
    return m+n

app.py

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    title="Home"
    return render_template("index.html", title=title)

if __name__=='__main__':
    app.run(debug=True)
1

There are 1 best solutions below

2
Zichzheng On

You need to do the import in your app.py.

from flask import Flask, render_template
from ./templates/test import do_math


app = Flask(__name__)

@app.route('/')
def home():
    title="Home"
    value = test.do_math(4,6)
    return render_template("index.html", title=title, value = value)

if __name__=='__main__':
    app.run(debug=True)

And in your html file, you can just take that value.