Home > Article > Web Front-end > javascript calls python method
In the front-end development process, it is often necessary to use back-end languages to implement some complex computing logic or data processing operations. The Python language has powerful data processing capabilities and support for various libraries, so it is widely used in front-end development. This article will introduce you to how to use JavaScript to call Python methods.
1. Prerequisites
Before you start using JavaScript to call Python methods, you need to understand the following points:
2. Build Python backend API
In order to expose Python methods to the front end, we need to develop a Python backend API. Use the flask library to quickly build a Python backend API. The specific steps are as follows:
Enter the following command in the command line:
pip install flask
Create a Python file named app.py in the project root directory and write the following code:
from flask import Flask, jsonify app = Flask(__name__) @app.route("/tasks/<int:task_id>", methods=['GET']) def get_task(task_id): task = { 'id': task_id, 'title': 'Task ' + str(task_id), 'description': 'Task ' + str(task_id) + ' description' } return jsonify({'task': task}) if __name__ == '__main__': app.run(debug=True)
The code defines an API interface named get_task, and the access path of the interface is "/tasks/58da1e685b26c03de4f232811ffb0cf1", and the request method of the interface is defined as GET. In the specific logic of the interface, we return a json object containing task information.
Run the following command in the terminal to start the API service:
python app.py
Visit http:// through a browser or Postman tool, etc. localhost:5000/tasks/1, you can see the returned json object.
{ "task": { "description": "Task 1 description", "id": 1, "title": "Task 1" } }
3. JavaScript calls Python methods
After setting up the Python back-end API service, we can call Python methods through JavaScript.
The Python-shell library enables JavaScript to interact with Python scripts. Enter the following command in the command line:
npm install python-shell
Create a JavaScript file named test.js in the project root directory and write the following code:
var PythonShell = require('python-shell'); PythonShell.run('test.py', function (err, results) { if (err) throw err; console.log('Python脚本的输出为: %j', results); });
In the code, we use the Python-shell library to run a Python script. The test.py file should be in the same directory as the test.js file. In the output of the Python script, we can see the results returned from the Python script.
Create a Python file named test.py in the project root directory and write the following code:
print("Hello, Python!")
Run the following command in the terminal to start the JavaScript script:
node test.js
We can see that the console outputs the output of the Python script: Hello, Python!.
4. JavaScript calls Python back-end API
Through the above steps, we have successfully implemented the operation of JavaScript calling Python methods. But this method simply executes the Python script. How to let JavaScript interact with the Python backend API?
In JavaScript, you can use Ajax to send a request to the Python backend API to obtain the data returned by the Python backend. The following is an example of using jQuery to send an Ajax request:
$(function() { // 获取任务信息 $.ajax({ url: 'http://localhost:5000/tasks/1', cache: false, success: function(data) { console.log(data); } }); });
In the above code, we obtain the task information returned by the Python backend API by accessing http://localhost:5000/tasks/1. We can see that the console outputs the corresponding task information.
The above is how JavaScript calls Python methods. By combining the power of Python and the flexibility of JavaScript, we can achieve more functions and capabilities in front-end development.
The above is the detailed content of javascript calls python method. For more information, please follow other related articles on the PHP Chinese website!