0

Gunicorn behinx 是 Ubuntu 12.04 上的 nginx 代理。

我在用于发送 html 字符串的裸机 gunicorn 服务器中具有以下功能:

def send_html(start_response, replystr):
    try:
        status = '200 OK'
        response_headers = [('Content-type', 'text/html; charset=UTF-8'),
                            ('Content-Length', str(len(replystr)))]
        start_response(status, response_headers)
        return iter([replystr])
    except:
        log.info(traceback.print_exc())
        send_error(start_response, '501')
        return []

如果我执行send_html(start_response, 'Hello world')它就可以了。但是,当我尝试发送包含新闻文章内容的相当大的字符串时,似乎每次都会收到以下错误:

Traceback (most recent call last):
  File "build/bdist.linux-x86_64/egg/gevent/pywsgi.py", line 504, in handle_one_response
    self.run_application()
  File "build/bdist.linux-x86_64/egg/gevent/pywsgi.py", line 491, in run_application
    self.process_result()
  File "build/bdist.linux-x86_64/egg/gevent/pywsgi.py", line 482, in process_result
    self.write(data)
  File "build/bdist.linux-x86_64/egg/gevent/pywsgi.py", line 375, in write
    self._write_with_headers(data)
  File "build/bdist.linux-x86_64/egg/gevent/pywsgi.py", line 394, in _write_with_headers
    towrite.extend(data)
TypeError: an integer or string of size 1 is required

gevent pywsgi 源代码告诉我towrite是一个字节数组:

    def _write_with_headers(self, data):
        towrite = bytearray()
        self.headers_sent = True
        self.finalize_headers()

        towrite.extend('%s %s\r\n' % (self.request_version, self.status))
        for header in self.response_headers:
            towrite.extend('%s: %s\r\n' % header)

        towrite.extend('\r\n')
        if data:
            if self.response_use_chunked:
                ## Write the chunked encoding
                towrite.extend("%x\r\n%s\r\n" % (len(data), data))
            else:
                towrite.extend(data)
        self._sendall(towrite)

文章内容与字节数组或其他内容不匹配吗?

4

2 回答 2

0

我修改了 send_html 函数以适应我的目的,在发送之前将replystr 转换为字节数组。不确定这个解决方案的可持续性如何,但它已经工作了一段时间。

def send_html(start_response, replystr):
    try:
        status = '200 OK'
        #coerce the string to a bytearray
        replystr = bytearray(replystr, 'UTF-8') 
        response_headers = [('Content-type', 'text/html; charset=UTF-8'),
                            ('Content-Length', str(len(replystr)))]
        start_response(status, response_headers)
        return iter([replystr])
    except:
        log.info(traceback.print_exc())
        send_error(start_response, '501')
        return []
于 2013-10-25T19:32:45.270 回答
0

做 towrite.extend(str("%x\r\n%s\r\n" % (len(data), data))) 将解决问题。

“扩展”的原因将不接受 unicode。

于 2015-08-12T10:16:47.630 回答