Python request.post to php server - php

Different variants of this question litter google, but I am not finding a solution specific to my needs. I am trying to send a JSON string from a client running python to a web server that is using PHP. The JSON string contains the results from a select query.
I have found lots of examples and tutorials on how to generate the JSON in python and how to publish data from the server database to a user via the server's page.
What I am not finding is how to actually transfer the JSON from the Python script to the PHP script. I am using the Arduino YUN with Linino, and have tried a request.post() but get a "module not found" error.
A plain english explanation of how the data hand off should take place between the two devices would help greatly! Any suggestions on a good resource that actually shows an example of what I have described would be great too.
Python (Post):
#!/usr/bin/python
import requests
import json
url = 'http://xxx.xxx.x.xxx/reciever.php'
payload = {"device":"gabriel","data_type":"data","zone":1,"sample":4,"count":0,"time_stamp":"00:00"}
headers = {'content-type': 'application/json'}
response = requests.post(url, data=json.dumps(payload), headers=headers)
PHP (Receiver):
<?php
print_r(json_decode($_POST['payload']));
?>
Maybe there is a totally different way that is better for posting a select query from a client to a server? Client will have dynamic IP's and the server will be web based.

Library requests isn't installed in Python by default. You need to get it first via pip or another package manager:
pip install requests
After that, you can use it.
There is also library, that is built in: urllib2. Example:
import urllib
import urllib2
url = 'http://xxx.xxx.x.xxx/reciever.php'
payload = {"device":"gabriel","data_type":"data","zone":1,"sample":4,"count":0,"time_stamp":"00:00"}
headers = {'content-type': 'application/json'}
data = urllib.urlencode(payload)
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)
the_page = response.read()

Related

How can I stream a GET request line-by-line?

I would like to send a GET request to a server that is streamed almost in 'realtime' using Chunk Transfer Encoding that I can completley modify line-by-line.
For example:
SendChunks = SomeHTTPLibrary.SendData;
SendChunks(Example.org, "5\r\n")
SendChunks(Example.org, "Hello\r\n")
SendChunks(Example.org, "7\r\n")
SendChunks(Example.org, "Goodbye\r\n")
SendChunks(Example.org, "0\r\n")
Where I am right now, I don't even care about listening for a response. It doesn't need to be in C++, I'm comfortable with Python, Javascript, PHP or anything similar.
Firstly, you shouldn't be sending a request body along with a GET request. I think technically you can, but if the server does anything with it then it's non-compliant. See https://stackoverflow.com/a/983458/241294.
From you question it looks as though you already know that you need chunked transfer encoding. Here is a crude example of how you can achieve this in python, but with a POST request instead of a GET request (code hacked from here):
import httplib
conn = httplib.HTTPConnection('Example.org')
conn.connect()
conn.putrequest('POST', '/post')
conn.putheader('Transfer-Encoding', 'chunked')
conn.endheaders()
conn.send("5\r\n")
conn.send("hello\r\n")
conn.send("7\r\n")
conn.send("Goodbye\r\n")
conn.send("0\r\n")
resp = conn.getresponse()
print(resp.status, resp.reason, resp.read())
conn.close()
For a nicer example with a python chunking function see How to force http.client to send chunked-encoding HTTP body in python?.

Sending and receiving data to PHP from Python

I am working on a project that requires a python client to execute functions and send data to a PHP server. To clarify, the python program is on a client computer, the PHP script is hosted on a webserver (24hosting). I need the python script to be able to get data from an SQL server hosted on the same site as the PHP server. I have already written code to get the SQL table data using PHP, I just need a way to get that data into python.
I am hoping the process will look like this:
Data in SQL Table
Get data using PHP
Use python on remote computer to recieve data from PHP
Any advice on how to go about this will be greatly appreciated!
Take a look at the requests api library in Python. You can use this library to let your python client make web based calls to our php code hosted in a web-server.
You can pass data from PHP to Python via JSON like this.
PHP script myscript.php reads a database table into a PHP array which is then encoded as JSON:
$fields = array('pkey', 'name', 'occupation');
$result = $conn->query($sql);
$row_data = array();
while ($row = $result->fetch_assoc()) {
$row_data[] = $row;
}
$rowfields = array('cols' => $fields, 'rows' => $row_data);
$json_data = json_encode($rowfields);
echo $json_data;
Then on a local computer running python:
import json
import urllib2
url = r'http://www.mysite/myscript.php'
response = urllib2.urlopen(url)
remote_data = json.load(response)
In this example, remote_data is a python dictionary with our server data.
You probably want to send the data from the PHP webserver in some easy-to-parse format such as JSON. Python has good parsing libraries for JSON, and for sending/receiving HTTP requests. The later is not part of the standard library, but can be downloaded using pip or similar.

Dropbox api - php - display image file in website

This might sound trivial for some of you, but I need to be sure...
I simply need to use dropbox for 2 things :
upload image files via php from my web server with the possibility of creating folder (as I would do on a normal web server) or sync folders from my web server to dropbox via rsync;
display these image files in a web page
I have downloaded the api sdk, then run into the 64bit exception error, then invalid redirect-uri...
So I would really appreciate if someone can reply to my 2 questions above and point me to a good example to just do that.
I solved it in another way. Rather than displaying the raw-file I use the API to generate Direct Download Link. This will give me a weblink that I then modify by adding a "raw=1" and subsitute the "dl=0" with "dl=1". This new link than then be used as the source for a normal html image.
As per above suggestions
import dropbox
import json
import httplib, urllib, base64
access_token='your token'
client = dropbox.client.DropboxClient(access_token)
url = client.share('test.jpg',short_url=False)
imageurl = url['url'].replace("dl=0","raw=1")
body = {
"url":imageurl
}
print json.dumps(body)
headers = {
# Request headers
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': '00759a20e705487a91e4db51b80bdfa7',
}
params = urllib.urlencode({
})
try:
conn = httplib.HTTPSConnection('api.projectoxford.ai')
conn.request("POST", "/emotion/v1.0/recognize?%s" % params,json.dumps(body), headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))

Send variable from php to python

Here is my problem, I need to send a variable to a python script from php which isn't really that hard but I just found out that they are not on the same server. The php file is on server A and can be accessed at server-a.com and the python is on a different server that can be accessed at server-b.com.
This is my current code for the php and python which works when they are on the same server:
PHP:
// Call to the python script test.py with the JSON data
$result = shell_exec('python test.py ' . escapeshellarg(json_encode($data)));
// get data back from python, decode it and display it
$resultData = json_decode($result, true);
//var_dump($resultData);
echo $result;
?>
Python:
import sys, json
# Load the data that PHP testv2.php sent us
try:
data = json.loads(sys.argv[1])
except:
print "ERROR"
sys.exit(1)
# Generate some data to send to PHP
result = {'status': 'Yes!'}
# Send it to PHP
print json.dumps(data)
Since you are on different servers you probably want to communicate via HTTP.
If your code is really THAT simple like shown in your example and will never become more complex, consider invoking Python via CGI.
For anything else (or if you simply prefer doing it properly) consider using WSGI and a framework such as Flask which allows you to define multiple endpoints using an url routing system.

Python: how to make HTTP request internally/localhost

I want to send some parameters from a python script on my server to a php script on my server using HTTP. Suggestions?
This is pretty easy using urllib:
import urllib
myurl = 'http://localhost/script.php?var1=foo&var2=bar'
# GET is the default action
response = urllib.urlopen(myurl)
# Output from the GET assuming response code was 200
data = response.read()

Categories