2013-10-02 3 views
-1

정말 죄송합니다. 여기는 전체 파이썬 스크립트입니다.UnicodeEncodeError : 'ascii'

스크립트의 목적은 두 개의 서로 다른 1 선 온도 센서를 읽고 HTTP 게시물을 사용하여 해당 값을 mysql 데이터베이스에 기록하는 것입니다.

#!/usr/bin/python 
# -*- coding: utf-8 -*- 
import requests 
import hashlib 
import time 

#Dont forget to fill in PASSWORD and URL TO saveTemp (twice) in this file 

sensorids = ["28-00000", "28-000004"] 
avgtemperatures = [] 
for sensor in range(len(sensorids)): 
    temperatures = [] 
    for polltime in range(0,3): 
      text = ''; 
      while text.split("\n")[0].find("YES") == -1: 
        # Open the file that we viewed earlier so that python can see what   is in it. Replace the serial number as before. 
        tfile = open("/sys/bus/w1/devices/"+ sensorids[sensor] +"/w1_slave") 
        # Read all of the text in the file. 
        text = tfile.read() 
        # Close the file now that the text has been read. 
        tfile.close() 
        time.sleep(1) 

      # Split the text with new lines (\n) and select the second line. 
      secondline = text.split("\n")[1] 
      # Split the line into words, referring to the spaces, and select the 10th word (counting from 0). 
      temperaturedata = secondline.split(" ")[9] 
      # The first two characters are "t=", so get rid of those and convert the temperature from a string to a number. 
      temperature = float(temperaturedata[2:]) 
      # Put the decimal point in the right place and display it. 
      temperatures.append(temperature/1000 * 9.0/5.0 + 32.0) 

    avgtemperatures.append(sum(temperatures)/float(len(temperatures))) 

print avgtemperatures[0] 
print avgtemperatures[1] 

session = requests.Session() 
# Getting a fresh nonce which we will use in the authentication step. 
nonce = session.get(url='http://127.0.0.1/temp/saveTemp.php?step=nonce').text 

# Hashing the nonce, the password and the temperature values (to provide some integrity). 
response = hashlib.sha256('{}PASSWORD{}{}'.format(nonce.encode('utf8'), *avgtemperatures).hexdigest()) 

# Post data of the two temperature values and the authentication response. 
post_data = {'response':response, 'temp1':avgtemperatures[0], 'temp2': avgtemperatures[1]} 

post_request = session.post(url='http://127.0.0.1/temp/saveTemp.php', data=post_data) 

if post_request.status_code == 200 : 
    print post_request.text 

다음은 새로운 오류입니다.

Traceback (most recent call last): 
File "/var/www/pollSensors.py", line 42, in <module> 
response = hashlib.sha256('{}PASSWORD{}{}'.format(nonce.encode('utf8'), *avgtemperatures).hexdigest()) 
AttributeError: 'str' object has no attribute 'hexdigest' 
+3

그리고'nonce'와'avgtemperatures'는 정확히 무엇입니까? 문제를 재현 할 수있는 것을 제공해주십시오. –

+0

문제는 MySQL과 완전히 별개입니다. –

+0

전체 게시물을 원래 게시물에 추가했습니다. – user2782497

답변

1

nonce은 유니 코드 값입니다. session.get(..).text은 항상 유니 코드입니다.

명시 적으로 인코딩을 제공하지 않고 해당 값을 문자열로 강제 변환하려고합니다. 결과적으로 파이썬은 기본 ASCII 코덱으로 인코딩하려고합니다. 해당 인코딩이 실패합니다.

유니 코드 값을 문자열로 명시 적으로 인코딩하십시오. SHA 256 해시의 경우 UTF-8이 좋습니다.

response = hashlib.sha256(nonce.encode('utf8') + 'PASSWORD' + 
          str(avgtemperatures[0]) + 
          str(avgtemperatures[1])).hexdigest() 
템플릿

또는 사용 문자열 : 당신의-profile.spyder2의 \의 spyder.lock

:
response = hashlib.sha256('{}PASSWORD{}{}'.format(
    nonce.encode('utf8'), *avgtemperatures)).hexdigest() 
+0

나는 변경된 파이썬 스크립트 오류의 맨 아래에 다음 .. #/usr/bin/python을 추가 # - * - 코딩 : UTF-8 - * - 새로운 오류 : 역 추적 (가장 최근 call last) : 파일 "/var/www/pollSensors.py", 줄 42, 응답 = (nonce + 'PASSWORD'+ str (avgtemperatures [0]) + str (avgtemperatures [1])). hexdigest() AttributeError : 'unicode'객체에 'hexdigest'속성이 없습니다. – user2782497

+0

@ user2782497 :'coding' 헤더가 그 원인이 아니 었습니다. 거기에서'hashlib.sha256' 호출을 삭제했습니다. –

+0

업데이트 된 코드와 새 오류를 표시하기 위해 원래 게시물을 업데이트했습니다. 적어도 오류가 변경되었습니다! – user2782497

0

내가 그것을 소수점 대신 ascci의

제거 디렉토리 것을 제외하고는 유사한 문제를 가지고

관련 문제