【问题标题】:UnicodeEncodeError: 'ascii'UnicodeEncodeError: 'ascii'
【发布时间】:2013-10-02 21:39:11
【问题描述】:

对不起,我真的是新手。这是完整的 python 脚本。

脚本的目的是读取两个不同的 1 线温度传感器,然后使用 HTTP post 将这些值写入 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'

【问题讨论】:

  • nonceavgtemperatures 到底是什么?请给我们一些可以重现您的问题的东西。
  • 您的问题完全与 MySQL 无关。
  • 我在原帖中添加了完整的脚本。
  • nonce 是 unicode;你用过session.get(...).text

标签: python unicode character encode


【解决方案1】:

nonce 是一个 unicode 值; session.get(..).text 始终是 unicode。

您试图在不明确提供编码的情况下将该值强制转换为字符串。因此,Python 尝试使用默认的 ASCII 编解码器为您编码。该编码失败。

改为将您的 Unicode 值显式编码为字符串。对于 SHA 256 哈希,UTF-8 可能没问题。

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

或使用字符串模板:

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

【讨论】:

  • 我在 python 脚本的顶部添加了以下内容,错误发生了变化.. #!/usr/bin/python # -- coding: utf-8 - - 新错误:回溯(最后一次调用):文件“/var/www/pollSensors.py”,第 42 行,在 响应 =(nonce + 'PASSWORD' + str(avgtemperatures[0]) + str( avgtemperatures[1])).hexdigest() AttributeError: 'unicode' object has no attribute 'hexdigest'
  • @user2782497:coding 标头不是造成这种情况的原因,也不可能是这种情况。您在那里删除了hashlib.sha256 调用。
  • 我更新了原始帖子以显示更新的代码和新的错误..至少错误正在改变!
  • @user2782497:我的错误,response = 行上缺少右括号。
  • 感谢 Martijn.. 修复了语法错误.. 新错误在原帖中。
【解决方案2】:

我遇到了类似的问题,只是它是十进制而不是 ascci

删除目录:your-profile.spyder2\spyder.lock

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-13
    • 2013-05-17
    • 2015-12-03
    • 2015-12-01
    • 2018-08-14
    • 1970-01-01
    • 2014-05-09
    • 1970-01-01
    相关资源
    最近更新 更多