使用python 3.4的mod_wsgi获得预期的字节字符串值的错误序列,找到类型列表的值

Ort*_*iel 2 mod-wsgi python-3.x

我试图返回到客户端 mysql 数据,我得到 mod_wsgi (pid=2304): 异常发生处理 WSGI 脚本 TypeError: 期望的字节字符串值序列,找到类型列表的值\r

    def application(environ, start_response):

    result = ChildClass().getValue()
    status = '200 OK'
    output =  result

    response_headers = [('Content-type', 'text/plain'),
                        ('Content-Length', str(len(output)))]
    start_response(status, response_headers)

    print(output)
    return [output]

class ChildClass(): # define child class
   print('ppp')
   def __init__(self):
      print("Calling child constructor")

   def childMethod(self):
      print('Calling child method')
      #Parentclass().parentMethod()

   def getValue(self):
    # Open database connection
    db = mysql.connector.connect(user='root', password='55118',host='127.0.0.1',database='test')
    cursor = db.cursor()
    query = ("SELECT * from employees2")
    cursor.execute(query)
    #for (first_name) in cursor:
    return  cursor.fetchall()
Run Code Online (Sandbox Code Playgroud)

如何将 cursor.fetchall 转换为字节?

cra*_*jun 5

如果您正在关注 modwsgi readthedocs,它会提供一个小片段来检查 mod_wsgi 是否在您的服务器上运行。但是,我发现在安装了 Python 3 模块的 Python 3.4 和 Django 1.9.2 与 Apache 和 mod_wsgi 一起使用时,代码会失败。我会不断收到“类型错误:预期的字节字符串值序列,找到 str 类型的值”。

答案是明确地将 'b' 放在我的字符串前面,使它们成为字节字符串而不是默认的 unicode。所以修复是说:

output = b'Hello World!'
Run Code Online (Sandbox Code Playgroud)

当返回和底部时,请确保您以列表的形式返回,例如:

return [output]
Run Code Online (Sandbox Code Playgroud)

这让我难住了几个小时,直到我最终不得不阅读 PEP 3333 ( https://www.python.org/dev/peps/pep-3333/#a-note-on-string-types ) 并阅读“关于字符串的说明“ 部分。