2

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)
relyt
  • 21
  • 3

1 Answers1

0

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.

Zichzheng
  • 1,090
  • 7
  • 25
  • Is there anyway to import the module from the html file? Although this certainly works for my very simple example, this doesn't work with the actual code that I have (and cannot share unfortunately). I have a progress bar whose width is modified according to the amount of columns that I iterate through in a csv file. I am unsure of what the logic would be to pass this through render_template – relyt Oct 16 '21 at 03:31
  • This answer certainly does not answer the question! – mteam88 May 11 '22 at 21:04