0

wsgiref我有以下在运行服务器时调用的请求文件:

import cgi, os
import cgitb; cgitb.enable() 
import pdb, time


STATUS_TEXT = \
  {
  200: 'OK',
  400: 'Bad Request',
  401: 'Unauthorized',
  403: 'Forbidden',
  404: 'Not Found',
  409: 'Conflict'
  }

class AmyTest( object ):

  def __init__( self, env, start_response ):
    """
rootDir_  is used to have the path just in case you need to refer to
    files in the directory where your script lives
environ_  is how most things are passed
startReponse_  is WSGI interface for communicating results
"""
    self.rootDir_ = os.environ.get( 'ROOT_DIR', ',' )
    self.environ_ = env
    self.startResponse_ = start_response

  def doTest( self ):

    method = self.environ_.get( 'REQUEST_METHOD', 'get' ).lower()
    if method == 'post':
      params = cgi.FieldStorage(
      fp = self.environ_[ 'wsgi.input' ],
          environ = self.environ_, keep_blank_values = True
      )
    else:
      params = cgi.FieldStorage(
          environ = self.environ_, keep_blank_values = True
      )

    vehicle_type = params.getfirst( 'vehicletype' )
    power_train_type = params.getfirst( 'powertraintype' )
    engine_displacement = params.getfirst( 'enginedisplacement' )
    engine_power = params.getfirst( 'enginepower' )
    curb_weight = params.getfirst( 'curbweight' )
    gv_weight = params.getfirst( 'gvweight' )
    frontal_area = params.getfirst( 'frontalarea' )
    coefficient_adrag = params.getfirst( 'coad' )
    rr_coefficient = params.getfirst( 'rrco' )
    sat_options = params.getfirst( 'satoptions' )

# This is the response HTML we are generating.
    fmt = """
<h2>Results</h2>
<table>
  <tr><td>Vehicle Type:</td><td>%s</td></tr>
  <tr><td>Power Train Type:</td><td>%s</td></tr>
  <tr><td>Engine Displacement (L):</td><td>%s</td></tr>
  <tr><td>Engine Power (hp):</td><td>%s</td></tr>
  <tr><td>Curb Weight (lbs):</td><td>%s</td></tr>
  <tr><td>Gross Vehicle Weight Rating (lbs):</td><td>%s</td></tr>
  <tr><td>Frontal Area (m^2):</td><td>%s</td></tr>
  <tr><td>Coefficient of Aerodynamic Drag:</td><td>%s</td></tr>
  <tr><td>Rolling Resistance Coefficient:</td><td>%s</td></tr>
  <tr><td>Selected Advanced Technology Options:</td><td>%s</td></tr>
</table>
"""
    content = fmt % ( vehicle_type, power_train_type, engine_displacement, engine_power, curb_weight, gv_weight, frontal_area, coefficient_adrag, rr_coefficient, sat_options)

    headers = \
      [
#        ( 'Content-disposition',
#          'inline; filename="%s.kmz"' % excat_in[ 'name' ] )
      ]

    result = \
      {
      'body': content,
      'code': 200,
      'headers': headers,
      'type': 'text/html'
      }
    time.sleep(5)
    return result


  def process( self ):
    result = self.doTest()
    return self.sendResponse( **result )

  def sendResponse( self, **kwargs ):
    """
@param  body
@param  code
@param  headers
@param  type
"""
    code = kwargs.get( 'code', 200 )
    status = '%d %s' % ( code, STATUS_TEXT[ code ] )

    body = kwargs.get( 'body', '' )
    mime_type = kwargs.get( 'type', 'text/plain' )
    headers = \
      [
        ( 'Content-Length', str( len( body ) ) ),
        ( 'Content-Type', mime_type )
      ]
    headers_in = kwargs.get( 'headers' )
    if headers_in != None and len( headers_in ) > 0:
      headers += headers_in

    self.startResponse_( status, headers )
    return [body]


  @staticmethod
  def processRequest( env, start_response ):
    server = AmyTest( env, start_response )
    return  server.process()

在 Python 2 上一切正常,但是当我尝试在 Python 3 上运行时,我得到关于write() argument must be bytes instanceNoneType object is not subscriptable. 来自控制台的错误是:

Traceback (most recent call last):
  File "/Users/gavin/miniconda3/lib/python3.6/wsgiref/handlers.py", line 138, in run
    self.finish_response()
  File "/Users/gavin/miniconda3/lib/python3.6/wsgiref/handlers.py", line 180, in finish_response
    self.write(data)
  File "/Users/gavin/miniconda3/lib/python3.6/wsgiref/handlers.py", line 266, in write
    "write() argument must be a bytes instance"
AssertionError: write() argument must be a bytes instance

Traceback (most recent call last):
  File "/Users/gavin/miniconda3/lib/python3.6/wsgiref/handlers.py", line 141, in run
    self.handle_error()
  File "/Users/gavin/miniconda3/lib/python3.6/wsgiref/handlers.py", line 368, in handle_error
    self.finish_response()
  File "/Users/gavin/miniconda3/lib/python3.6/wsgiref/handlers.py", line 180, in finish_response
    self.write(data)
  File "/Users/gavin/miniconda3/lib/python3.6/wsgiref/handlers.py", line 274, in write
    self.send_headers()
  File "/Users/gavin/miniconda3/lib/python3.6/wsgiref/handlers.py", line 331, in send_headers
    if not self.origin_server or self.client_is_modern():
  File "/Users/gavin/miniconda3/lib/python3.6/wsgiref/handlers.py", line 344, in client_is_modern
    return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9'
TypeError: 'NoneType' object is not subscriptable

任何有关如何在 Python 3 中实现此功能的建议都会非常有帮助。

4

1 回答 1

0

如果是字符串,则write()可以通过调用来修复期望字节的函数。该函数将字符串转换为字节,并将字节转换为字符串。your_arg.encode()your_argencode()decode()

编码/解码函数在 python 3 中不可用,将字节转换为字符串,反之亦然,在 python 2 中的处理方式不同。

另一个错误说不可下标意味着它不支持下标表示法。例如foo[i]。所以你得到那个错误的地方,那个对象不支持[]下标。

于 2017-06-22T02:05:14.660 回答