mod_wsgi with python 3.4 get an error sequence of byte string values expected, value of type list found

折月煮酒 提交于 2020-01-15 20:15:28

问题


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()

How convert cursor.fetchall to bytes?


回答1:


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".

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]

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.



来源:https://stackoverflow.com/questions/31937508/mod-wsgi-with-python-3-4-get-an-error-sequence-of-byte-string-values-expected-v

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!