简体   繁体   English

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

[英]Using Python Script to post data to web server

I am using Python 2.7.3 and I am trying to post data to my local web server. 我正在使用Python 2.7.3,我正在尝试将数据发布到我的本地Web服务器。 The data I am posting is temperature readings from my raspberry pi. 我发布的数据是来自我的覆盆子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. 我知道网址是正确的,因为如果我使用postman chrome插件,数据会成功发布,我会收到一条返回消息。 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. 在邮递员中,我只能使用表单数据而不是x-www-form-urlencoded,这就是我的python脚本具有内容类型设置的方式。 Can I change it to form-data? 我可以将其更改为表格数据吗?

Python Code: 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()  

And the Error: 而错误:

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

save your time, use this requests lib for httpRequests, 节省您的时间,使用此请求 lib for httpRequests,

simple app 简单的应用

import requests

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM