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

问题描述:

我正在使用Python 2.7.3,我正在尝试将数据发布到我的本地Web服务器。我发布的数据是来自我的覆盆子pi的温度读数。我知道网址是正确的,因为如果我使用postman chrome插件,数据会成功发布,我会收到一条返回消息。邮递员我只能使用表格数据而不是x-www-form-urlencoded这是我的python脚本具有内容类型设置的方式。我可以将其更改为表格数据吗?

I am using Python 2.7.3 and I am trying to post data to my local web server. The data I am posting is temperature readings from my raspberry pi. I know the url is right because if I use the postman chrome plugin the data is successfully posted and I get a return message. In postman I can only use form-data though and NOT x-www-form-urlencoded which is how my python script has the content type setup. Can I change it to form-data?

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


节省您的时间,使用此请求 lib for httpRequests,

save your time, use this requests lib for httpRequests,

简单应用

import requests

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