In this example we will be using the Python library Requests in JavaScript.
Note: Using this example in the real world is not a good idea. Just use a JavaScript HTTP library (superagent, request) instead.
The following python versions are supported: 2.6, 2.7, 3.3, 3.4, 3.5, 3.6.
Python 2 is required to build regardless of your target python version.
sudo apt-get install python python3 python3-dev
Download the installer from python.org
brew install python3
If you have multiple python versions on your system, you may want to set a target python version when you install. This can be done by passing something like --python_version=3.3
to npm install
.
npm install @require-x/python # Uses python 3 if installed, falling back to python 2.
npm install @require-x/python --python_version=2
npm install @require-x/python --python_version=3.3
pip install requests
pip3 install requests
Lets start coding.
First we need to import the library.
const py = require('@require-x/python');
Then we need to import requests.
const requests = py.require('requests');
Then we can make a new request.
const r = requests.post('http://httpbin.org/post', py.kwargs({ data: JSON.stringify(["Hello, world!"]) }));
Lets break this down.
We are calling the method requests.post
with a url as the first argument and then passing kwargs through py.kwargs()
.
The method returns a py.Object
object which can be manipulated in several ways.
To get an attribute, you can use o.attr_name
(the same as you do in Python).
// Get the status code. This is equal to "r.status_code" in Python.
console.log(r.status_code); // Prints: 200
To get a value from a dict, you can use o.$key
, this is equal to o["key"]
in Python.
// Get the content-type header received from the server. This is equal to "r.headers["content-type"]" in Python
console.log(r.headers['$content-type']); // Prints: application/json,
To get a value from a list or tuple, you can use o[key]
(the same as you do in Python).
// Get the first value of the JSON array we sent that the server sent back in it's response. This is equal to "r.json().json[0]` in Python.
console.log(r.json().$json[0]) // Prints: Hello, world!
const py = require('@require-x/python'); // Import the library
const requests = py.require('requests'); // Import requests
const r = requests.post('http://httpbin.org/post', py.kwargs({ data: JSON.stringify(["Hello, world!"]) })); // Make a request
console.log(r.status_code); // Log the status code
console.log(r.headers['$content-type']); // Log the content type
console.log(r.json().$json[0]); // Log the first value of the JSON array we sent that the server sent back in it's response