Call a Python function from p5.js.

Introduction

--This article was written as the 21st day article of ISer Advent Calendar 2020.

What is this article

--For anyone who wants to call a Python function from p5.js, here's one way to do it. --Set up a server with flask and run python there. Access using ajax from javascript.

Finished product

-Create a counting app like this page.

――When you access for the first time, it takes a few seconds to start heroku. --When you hit the keyboard, the displayed numbers increase.

![demo.gif](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/145009/f87b64ff-7553-13e5-2ffd-770381a35867.gif)

--Program structure --Receive keyboard input with keyPressed () in sketch.js. --POST to / increment using ajax and pass the value of the variable count to the plusone function of app.py. --The plusone function returns the given number plus one. --Assign the value returned by sketch.js to the count variable. --The draw function is called at regular intervals to display the text according to the value of the count variable. --All the code is on GitHub.

procedure

Write a count app with p5.js

--Write a count app appropriately with p5.js. --Let's write sketch.js as follows.

let count = 0;
function setup() {
    createCanvas(100, 100);
    count = 0;
}
function draw() {
    background(220);
    textSize(60);
    textAlign(CENTER);
    text(count, 50, 70);
}
function keyPressed(){
    count += 1;
}

--Set count to 0 in setup, increment that value by 1 with keyPressed, and draw (called repeatedly at regular intervals) -You can easily test it by using p5.js official editor. --For those who want to know more about p5.js. --The official page is here. --The tutorial is here. --The official reference is here.

Write index.html and open it in your browser

--Let's write index.html as follows.

<html lang="ja">
<head>
  <meta charset="utf-8">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.min.js"></script>
  <script src="../static/sketch.js"></script>
</head>
<body>
</body>
</html>

--Let's make the directory structure as follows.

./
├── static
│   └── sketch.js
└── templates
    └── index.html

--When you open index.html, you can open the counting app in a browser such as Chrome. --Reference -p5.js Official Tutorial

Try launching a local server with flask

flask install

--First, let's install flask.

$ pip3 install Flask

--Reference: Flask installation

Launch a local server

--Let's write app.py as follows.

from flask import Flask, render_template
app = Flask(__name__)

@app.route("/")
def main():
    return render_template("index.html")
  
if __name__ == "__main__":
    app.run(host = "0.0.0.0", port = 8080, debug = True)

--Let's start a local server.

$ python3 app.py 
 * Serving Flask app "app" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
 * Restarting with fsevents reloader
 * Debugger is active!
 * Debugger PIN: 245-513-508

--If you access http://0.0.0.0:8080/ and the count app is displayed, it's OK. --Reference: Flask Quick Start

Try to communicate with Ajax

――From here, let's finally call the Python code from Javascript.

Call ajax in sketch.js

--Try to access / increment with keyPressed.

function keyPressed(){
    var post = $.ajax({
        type: "POST",
        url: "/increment",
        data: {count: count}, // post a json data.
        async: false,
        dataType: "json",
        success: function(response) {
            console.log(response);
            // Receive incremented number.
            count = response.count;
        }, 
        error: function(error) {
            console.log("Error occurred in keyPressed().");
            console.log(error);
        }
    })
}

--Reference -JQuery.ajax Official Reference --Programs of others calling Python using ajax

Create a plusone function in app.py

--Add the following function to app.py.

@app.route("/increment", methods=["POST"])
def plusone():
    req = request.form
    res = {"count": int(req["count"])+1}
    return jsonify(res)

--Reference --Programs of others calling Python using ajax

Add source to html to use ajax

--Add the following line to index.html.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

--Reference -Programs of others calling Python using ajax

Run

$ python3 app.py

Deploy

-This page also uploads on heroku. -Deploy while referring to heroku official reference.

in conclusion

Recommended Posts

Call a Python function from p5.js.
Python-dynamically call a function from a string
[Python] How to call a c function from python (ctypes)
Call a command from Python (Windows version)
Call a Python script from Embedded Python in C ++ / C ++
Call CPLEX from Python (DO cplex)
Create a function in Python
How to call a function
Consider a conversion from a Python recursive function to a non-recursive function
[Python] What is a zip function?
Call C from Python with DragonFFI
Touch a Python object from Elixir
python function ①
[Python] function
Call popcount from Ruby / Python / C #
python / Make a dict from a list.
[Python] Make the function a lambda function
Call python from nim with Nimpy
Call C / C ++ from Python on Mac
python function ②
Call c language from python (python.h)
Call Rust from Python to speed it up! PyO3 Tutorial: Wrapping a Simple Function Part ➀
Call Rust from Python to speed it up! PyO3 Tutorial: Wrapping a Simple Function Part ➁
[Road to Python Intermediate] Call a class instance like a function with __call__
Simple code to call a python program from Javascript on EC2
Call dlm from python to run a time-varying coefficient regression model
Create a Python function decorator with Class
Precautions when pickling a function in python
Send a message from Python to Slack
# 5 [python3] Extract characters from a character string
Create a deb file from a python package
Generate a class from a string in Python
Use Django from a local Python script
Manipulate BigQuery tables from a Python client
python enumerate function
Python> function> Closure
[Python] Generator function
sql from python
MeCab from Python
Python> function> Inner function
Python function decorator
Send a message from Slack to a Python server
Run a Python script from a C # GUI application
Edit Excel from Python to create a PivotTable
Draw a graph of a quadratic function in Python
How to open a web browser from python
To execute a Python enumerate function in JavaScript
How to create a function object from a string
Create a C array from a Python> Excel sheet
Get the caller of a function in Python
A memorandum of calling Python from Common Lisp
Create a New Todoist Task from Python Script
How to generate a Python object from JSON
"Python Kit" that calls a Python script from Swift
Call Python library for text normalization from MATLAB
Create a decision tree from 0 with Python (1. Overview)
Create a datetime object from a string in Python (Python 3.3)
Run a Python file from html using Django
[Go] How to write or call a function
Read line by line from a file with Python
Call Polly from the AWS SDK for Python