Advertisement:
Read Later
In this tutorial, I will show you how to send files using the requests module in Python to a LAMP server easily. Also, if you want, you can use this method to create an uploading interface, managed on the LAMP server, for the user to upload files to the server without making an HTTP request in Python, as explained below.
To make HTTP requests from Raspberry Pi to a LAMP server in Python, you need to download the requests module as explained here.
$ pip install requests
Also, you can get the response message using this module(1).
response = requests.get('https://api.github.com')
To receive files and save them in a selected folder, you need to get the request variables ($_FILES[]) in PHP.
Python:
Import the requests module.
Create the send_video_to_LAMP_server() function.
Define the file path in the LAMP server, on which the server hosts the PHP code.
Make an HTTP Post Request to the server, including the file information.
Print the response from the server.
Enter the location of the selected file.
And, activate the mentioned function.
PHP:
If the received file name is not empty:
Get properties of the uploaded file - name, tmp_name, sizei and extension.
Enter settings to check whether the uploaded file has appropriate size and extension if needed.
Define the file location and filename to save the uploaded file to the server:
move_uploaded_file();
------------ Python ------------
import requests
def send_video_to_LAMP_server(file):
# Define the file path in the LAMP server to send the file successfully.
url = '...file_pathway.php'
files = {'new_video': open(file, 'rb')}
# Make an HTTP Post Request to the server.
request = requests.post(url, files=files)
# Print the response from the server.
print ("Rasp_Pi => Files Transferred! \r\n")
print(request.text + "\r\n")
# Define the file location in Pi.
location = "/home/pi/test.jpg"
send_video_to_LAMP_server(location)
------------ PHP ------------
<?php
if(!empty($_FILES["new_file"]["name"])){
// Get properties of the uploaded file.
$file_properties = array(
"name" => $_FILES["new_file"]["name"],
"tmp_name" => $_FILES["new_file"]["tmp_name"],
"size" => $_FILES["new_file"]["size"],
"extension" => pathinfo($_FILES["new_file"]["name"], PATHINFO_EXTENSION)
);
// Enter settings here to check the uploaded file size, extension if needed.
// ...
// ...
// Define the file location and filename and save the uploaded file.
$root = $file_properties["name"];
move_uploaded_file($file_properties["tmp_name"], $root);
}
?>
Result:
You can inspect my electronics project in which I used the same method to receive videos and images from Pi to my LAMP server :)
(1) https://realpython.com/python-requests/