使用python 3.4的mod_wsgi获得预期的字节字符串值的错误序列,找到类型列表的值 [英] mod_wsgi with python 3.4 get an error sequence of byte string values expected, value of type list found

查看:162
本文介绍了使用python 3.4的mod_wsgi获得预期的字节字符串值的错误序列,找到类型列表的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Im trying to return to the client mysql data and i get mod_wsgi (pid=2304): Exception occurred processing WSGI script TypeError: sequence of byte string values expected, value of type list found\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()

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

How convert cursor.fetchall to bytes?

推荐答案

如果您正在阅读modwsgi,则它会提供一小段代码来检查mod_wsgi是否在您的服务器上正常工作.但是,我发现在将Python 3.4和Django 1.9.2与Apache和mod_wsgi结合使用以安装Python 3模块时,代码失败.我会不断收到"TypeError:预期的字节字符串值序列,找到类型str的值".

If you are following the modwsgi readthedocs it provides a small snippet to check if mod_wsgi is working on your server. However, I found that the code fails when using Python 3.4 and Django 1.9.2 with Apache and mod_wsgi for Python 3 module installed. I would keep getting "TypeError: sequence of byte string values expected, value of type str found".

答案是显式地在字符串的前面加上"b",使它们成为字节字符串,而不是默认的unicode.所以解决方法是说:

The answer was to explicitly put 'b' in front of my strings to make them byte strings instead of default unicode. So the fix was to say:

output = b'Hello World!'

在返回时,请确保您以列表形式返回,例如:

And when returning and the bottom make sure you are returning as a list, e.g.:

return [output]

这让我难过几个小时,直到我终于不得不阅读PEP 3333( https://www.python.org/dev/peps/pep-3333/#a-note-on-string-types ),然后阅读字符串注释"部分.

This stumped me for hours until I finally had to read PEP 3333 (https://www.python.org/dev/peps/pep-3333/#a-note-on-string-types) and read the "Note on Strings" section.

这篇关于使用python 3.4的mod_wsgi获得预期的字节字符串值的错误序列,找到类型列表的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆