python - 使用 Python 脚本将数据发布到 Web 服务器

标签 python python-2.7 http post

我使用的是 Python 2.7.3,我正在尝试将数据发布到我的本地 Web 服务器。我发布的数据是我的树莓派的温度读数。我知道 url 是正确的,因为如果我使用 postman chrome 插件,数据会成功发布并且我会收到一条返回消息。在 postman 中,我只能使用表单数据,而不是 x-www-form-urlencoded,这是我的 python 脚本设置内容类型的方式。我可以将其更改为表单数据吗?

Python 代码:

import os
import glob
import time
import threading
import urllib
import urllib2

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'

def read_temp_raw():
    f = open(device_file, 'r')
    lines = f.readlines()
    f.close()
    return lines

def read_temp():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = float(temp_string) / 1000.0
        temp_f = temp_c * 9.0 / 5.0 + 32.0
    temperature = {'tempf':temp_f, 'tempc':temp_c}
        return temperature

def post():
    threading.Timer(1800.0, post).start()
    temperature = read_temp()
    data = temperature
    data['room'] = 'Server Room'
    print(data)

    data=urllib.urlencode(data)
    path='http://client.pathtophppage'    #the url you want to POST to
    req=urllib2.Request(path, data)
    req.add_header("Content-type", "application/x-www-form-urlencoded")
    page=urllib2.urlopen(req).read()


post()  

错误:

pi@raspberrypi ~/Documents $ python Temperature.py 
{'tempc': 22.0, 'tempf': 71.6, 'room': 'Server Room'}
Traceback (most recent call last):
  File "Temperature.py", line 49, in <module>
    post()  
  File "Temperature.py", line 45, in post
    page=urllib2.urlopen(req).read()
  File "/usr/lib/python2.7/urllib2.py", line 127, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 407, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 520, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.7/urllib2.py", line 439, in error
    result = self._call_chain(*args)
  File "/usr/lib/python2.7/urllib2.py", line 379, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 626, in http_error_302
    return self.parent.open(new, timeout=req.timeout)
  File "/usr/lib/python2.7/urllib2.py", line 407, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 520, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.7/urllib2.py", line 445, in error
    return self._call_chain(*args)
  File "/usr/lib/python2.7/urllib2.py", line 379, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 528, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 500: Internal Server Error

最佳答案

节省您的时间,使用这个 requests httpRequests 的库,

简单的应用

import requests

url = 'http://url.com'
query = {'field': value}
res = requests.post(url, data=query)
print(res.text)

关于python - 使用 Python 脚本将数据发布到 Web 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30459762/

相关文章:

python - Tkinter 类方法和访问类成员

python - "ValueError: setting an array element with a sequence"- 尝试将列表输入 feed_dict 中的占位符时

python - 如何在数据存储到数据库之前对其进行测试?

python-2.7 - 决定 pip 和 easy_install 使用哪个 python 版本

http - StreamSets HTTP 客户端

php - 从 php 发送 HTTP 状态代码的区别

python - 覆盖设置和包默认值

python - 无法将 .xlsx 导入 Python : No such file or directory

jquery - 如何实现选择,以便在用户单击提交按钮时我可以访问我的代码中的选定值

http - 安装 SuiteCRM 时出现 403 错误