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 用verilog实现tanh函数和softplus函数
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题