Skip to content

requests

Boris Lovosevic edited this page Jul 31, 2019 · 5 revisions

network module


Class requests


The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web, where hypertext documents include hyperlinks to other resources that the user can easily access, for example by a mouse click or by tapping the screen in a web browser. HTTP was developed to facilitate hypertext and the World Wide Web.

requests module enables trasfering data between K210 MicroPython and the remote http server.

Features

  • GET, HEAD, POST, PUT, PATCH and DELETE methods are supported.
  • Using secured http (SSL/TLS) is supported (with WiFi interface only).
  • Flexible POST method supporting sending multipart data (from MicroPython dictionary) and Base-64 encoded data.
  • Status, headers and response data are provided as a result
  • Receiving response data into file is supported

Methods


All http methods returns the result in the form of 3-item tuple: (status, header, response).
status http operation result code
header string, http response headers
response bytearray, http response body
If response to file was requested, response will be the string "Saved to file '<file_name>', size=<file_size>".


requests.get(url [, file] [,bufsize])

Sends GET request to the server.

url string containing the server address and optional parameters.
file optional, string containing the file name to which to save the response bufsize optional, size of the temporary buffer used during transfer; default: 1536

Returns the result tuple.

requests.head(url)

Sends HEAD request to the server.

url string containing the server address and optional parameters.

Returns the result tuple. Only the status and header are returned.

requests.post(url, params [, args])

Argument Description
url string containing the server address, IP or domain name can be used
params POST request parameters
params can be string (only if multipart=False or dictionary
If multipart is False and params are dictionary, the parameters will be url-encoded
Valid dictionary value that can be sent are: string, int, float or buffer object
If a string dictionary parameter is an existing file name, the file will be sent
file optional, file name to which to save the response to
Default: not used
multipart optional, if set to True sends the multipard data request
Default: False
If multipart is False, data are sent as "Content-Type: application/x-www-form-urlencoded"
If multipart is True, data are sent as "Content-Type: multipart/form-data"
base64 optional, if set to True sends the buffer object parameter from multipart parameters as base64 encoded
Default: False
bufsize optional, size of the temporary buffer used during transfer
Default: 1536

requests.put(url, data)

Sends PUT request to the server.

url string containing the server address.
data string to be sent to the server

Returns the result tuple.

requests.pachh(url, data)

Sends PATCH request to the server.

url string containing the server address.
data string to be sent to the server

Returns the result tuple.

requests.delete(url, data)

Sends DELETE request to the server.

url string containing the server address.
data string to be sent to the server

Returns the result tuple.


requests.certificate(cert)

Load servers' Certificate from file cert if needed for https operations.

requests.debug(True|False)

Enable or disable printing requests log messages.
The desired log level must also be set with machine.loglevel().

requests.bodybuffer([size])

Get (if no argument provided) or set the size of the response buffer.
Range: 4096 ~ 524288
Default: 64 KB
The response buffer is used when the http response is not received into file.


Examples


GET test

import network, os

wifi = network.wifi

wifi.start(tx=7, rx=6, ssid="LoBoInternet", password="1xxxxxxxx2", wait=True)

requests = network.requests

# ========================================
# === Get file from server into buffer ===
# ========================================

>>> res = requests.get('http://loboris.eu/K210/test.txt')
>>> res[0]
200
>>> print(res[1])
Date: Wed, 31 Jul 2019 10:52:18 GMT
Server: Apache/2.4.29 (Ubuntu)
Last-Modified: Wed, 20 Mar 2019 13:08:43 GMT
ETag: "426-5848652314cc0"
Accept-Ranges: bytes
Content-Length: 1062
Vary: Accept-Encoding
Content-Type: text/plain; charset=UTF-8

>>> print(res[2].decode())
===============
Welcome to K210
===============

General Specifications:
-----------------------
 * The K210 includes two 64-bit RISC-V CPU cores, each with a built-in independent FPU.
 * KPU high performance Convolutional Neural Network (CNN) hardware accelerator.
   The primary functions of the K210 are machine vision and hearing,
   which includes the KPU for computing convolutional neural networks and
   an APU for processing microphone array inputs.
 * The K210 features a Fast Fourier Transform (FFT) Accelerator for high performance
   complex FFT calculations. As a result, for most machine learning algorithms,
   the K210 has high-performance processing power.
 * Advanced TSMC 28nm process, temperature range -40°C to 125°C
 * Firmware encryption support
 * Unique programmable IO array maximises design flexibility
 * Low voltage, reduced power consumption compared to other systems
   with the same processing power
 * 3.3V/1.8V dual voltage IO support eliminates need for level shifters

---------
2019 LoBo
---------

# ============================================
# === Get file from server into local file ===
# ============================================

>>> res = requests.get('http://loboris.eu/K210/tiger240.jpg', file='/flash/tiger.jpg')
>>> res[0]
200
>>> print(res[1])
Date: Wed, 31 Jul 2019 10:58:03 GMT
Server: Apache/2.4.29 (Ubuntu)
Last-Modified: Mon, 30 Jan 2017 18:26:45 GMT
ETag: "17d07-54753f5306340"
Accept-Ranges: bytes
Content-Length: 97543
Content-Type: image/jpeg

>>> print(res[2])
Saved to file '/flash/tiger.jpg', size=97543
>>> os.stat('/flash/tiger.jpg')
(32768, 0, 0, 0, 0, 0, 97543, 1562155662, 1562155662, 1562155662)
>>> 

# ===================================
# === Get request with parameters ===
# ===================================

>>> res = requests.get('http://loboris.eu/K210/test.php?user=lobo&par1=12345&par2=26.43')
>>> print(res[2].decode())

============
Method: GET
============

--------------------------
    Number of GET params: 3
--------------------------

===========
Debug info:
===========

-----------
 GET DATA:  
-----------
Array
(
    [user] => lobo
    [par1] => 12345
    [par2] => 26.43
)

=====================================
LoBo test server, 2019/07/31 13:41:46
=====================================

>>> 

POST test

import network, os

wifi = network.wifi

wifi.start(tx=7, rx=6, ssid="LoBoInternet", password="1xxxxxxxx2", baudrate=921600, wait=True)

requests = network.requests

# define some parameters to be used in POST requests
p4=b'\x00\x01\x02\x03\x7d\x7e\xf8\xf9\xfa'
p={"p1" : "Hi, this is a test string", "p2" : 123, "p3" : 5.4321}
p1={"p1" : "Hi, this is a test string", "p2" : 123, "p3" : 5.4321, "p4" : p4}
p2={"p1" : "Hi, this is a test string", "p2" : 123, "p3" : 5.4321, "p4" : p4, "p5": "/flash/boot.py"}

# ===========================
# === Simple post request ===
# ===========================

>>> res=requests.post('http://loboris.eu/K210/test.php', p)
>>> print(res[2].decode())

============
Method: POST
Content-Type: application/x-www-form-urlencoded
============

--------------------------
Number of uploaded files: 0
   Number of POST params: 3
--------------------------

===========
Debug info:
===========

-----------
POST DATA: 
-----------
[p2] => 123
[p3] => 5.43210000
[p1] => Hi, this is a test string

=====================================
LoBo test server, 2019/07/31 13:20:28
=====================================

# ============================================================
# === Post as multipart data, binnary data can be included ===
# ============================================================

>>> res=requests.post('http://loboris.eu/K210/test.php', p1, multipart=True)
>>> print(res[2].decode())

============
Method: POST
Content-Type: multipart/form-data
============

--------------------------
Number of uploaded files: 0
   Number of POST params: 4
--------------------------

===========
Debug info:
===========

-----------
POST DATA: 
-----------
[p1] => Hi, this is a test string
[p4] => hex[000102037d7ef8f9fa]
[p3] => 5.43210000
[p2] => 123

=====================================
LoBo test server, 2019/07/31 13:20:49
=====================================

>>> 

# ==========================================================
# === Post as multipart data, base64 encode binnary data ===
# ==========================================================

>>> res=requests.post('http://loboris.eu/K210/test.php', p1, multipart=True, base64=True)
>>> print(res[2].decode())

============
Method: POST
Content-Type: multipart/form-data
============

--------------------------
Number of uploaded files: 0
   Number of POST params: 4
--------------------------

===========
Debug info:
===========

-----------
POST DATA: 
-----------
[p1] => Hi, this is a test string
[p4] => AAECA31++Pn6 (base64) hex[000102037d7ef8f9fa]
[p3] => 5.43210000
[p2] => 123

=====================================
LoBo test server, 2019/07/31 13:31:20
=====================================

>>> 

# ==============================================================
# === Post as multipart data, binnary data and file included ===
# ==============================================================

>>> res=requests.post('http://loboris.eu/ESP32/test.php', p2, multipart=True)
>>> print(res[2].decode())

============
Method: POST
Content-Type: multipart/form-data
============

--------------------------
Number of uploaded files: 1
   Number of POST params: 4
--------------------------

===========
Debug info:
===========

-----------
POST DATA: 
-----------
[p3] => 5.43210000
[p2] => 123
[p4] => hex[000102037d7ef8f9fa]
[p1] => Hi, this is a test string

-----------
FILE DATA: 
-----------
Array
(
    [file_p5] => Array
        (
            [name] => boot.py
            [type] => application/octet-stream
            [tmp_name] => /tmp/phpybr25a
            [error] => 0
            [size] => 81
        )

)
-----------

=====================================
LoBo test server, 2019/07/31 13:24:02
=====================================

>>>