1

I would like to write a simple python application, that generates a HTML "website" as frontend. It is not meant to be hosted online or to consist of multiple pages. The user will simply open the frontend in a browser.

There should be only one index.html file like this:

<!DOCTYPE html>
<html lang="en">

<head>
    <link rel="stylesheet" type="text/css" href="my-styles.css">
    ...
</head>

<body>
    {python_body_var}
</body>

Where python_body_var is an object (or string-representation) of the python-internal state.

Is there a simple way to implement this? Could I easily register event handlers for buttons etc.?

The important thing about this is, that any user interaction (clicking elements, inserting text, ...) should be noticed in the backend. And the frontend should actively respond to certain changes in the backend.

3
  • stackoverflow.com/questions/2301163/creating-html-in-python Commented Oct 31, 2018 at 14:39
  • @Corbie you could add a script tag into your page and then use javascript inside the script tag to add event handlers. Commented Oct 31, 2018 at 14:40
  • Javascript cannot directly communicate with python. All the important stuff should happen in the backend. E.g. if the user clicks a button, the python backend shall create an image and display it in a (new) img element. Commented Oct 31, 2018 at 14:43

2 Answers 2

1

This would be your python script

from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def index(): 
    my_string = "hello world"
    return render_template("index.html", body=my_string)

if __name__ == "__main__":
    app.run()

And in a folder called templates have an html document called index.html

<!DOCTYPE html>
<html lang="en">


<body>
    <p>{{body}}</p>
</body>
</html>

run the python script and go to http://localhost:5000/ in your browser and you will see it. your folder structure will look like this

main.py
templates
|____index.html
Sign up to request clarification or add additional context in comments.

Comments

-1

https://anvil.works/ is a dedicated platform where you can build the prototype easily only with python.

1 Comment

This is nice for hobby projects and very large public projects, where the costs are neglectable. For on-site projects this does not work without an expensive enterprise license.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.