How to integrate p5.js with python flask?

by darrion.kuhn , in category: Javascript , 2 months ago

How to integrate p5.js with python flask?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lizzie , 2 months ago

@darrion.kuhn 

To integrate p5.js with Python Flask, you can follow these steps:

  1. Install Flask: If you haven't already, you can install Flask using pip:
1
pip install Flask


  1. Create a Flask app: Create a new Flask app by creating a new Python file, for example app.py, and import Flask:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return "Hello world"

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


  1. Serve the p5.js files: Place your p5.js files in a static folder in your Flask project directory. This folder will serve as the static folder for Flask to serve your static files from. In your HTML template, you can link to the p5.js file like this:
1
<script src="{{ url_for('static', filename='p5.js') }}"></script>


  1. Render p5.js in a Flask route: You can create a route in Flask that will render your p5.js sketch. For example, you can create a new route that renders an HTML file with your p5.js sketch:
1
2
3
4
5
from flask import render_template

@app.route('/sketch')
def sketch():
    return render_template('sketch.html')


  1. Create your p5.js sketch: Create a new HTML file, for example sketch.html, in the templates folder in your Flask project directory. In this file, you can write your p5.js sketch code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>p5.js Sketch</title>
  <script src="{{ url_for('static', filename='p5.js') }}"></script>
</head>
<body>
  <script>
    function setup() {
      createCanvas(400, 400);
      background(220);
    }

    function draw() {
      ellipse(mouseX, mouseY, 20, 20);
    }
  </script>
</body>
</html>


  1. Run the Flask app: Run your Flask app by executing the app.py file:
1
python app.py


You should now be able to access your p5.js sketch by navigating to http://localhost:5000/sketch in your browser.