dtwvr26066 2015-08-05 05:40
浏览 68
已采纳

Python request.post到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.

  • 写回答

1条回答 默认 最新

  • dongnuo6310 2015-08-05 06:57
    关注

    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()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办