2009-04-22 31 views
1

我想從簡單的表單捕獲POST數據。如何使用WSGIREF捕獲POST

這是我第一次玩WSGIREF,我似乎無法找到正確的方法來做到這一點。

This is the form: 
<form action="test" method="POST"> 
<input type="text" name="name"> 
<input type="submit"></form> 

而這顯然是缺少正確的信息捕捉後的功能:

從服務器
def app(environ, start_response): 
    """starts the response for the webserver""" 
    path = environ[ 'PATH_INFO'] 
    method = environ['REQUEST_METHOD'] 
    if method == 'POST': 
     if path.startswith('/test'): 
      start_response('200 OK',[('Content-type', 'text/html')]) 
      return "POST info would go here %s" % post_info 
    else: 
     start_response('200 OK', [('Content-type', 'text/html')]) 
     return form() 
+0

發生了什麼,而不是正確的行爲? 我只是用一個快速的`paster server`運行這個應用程序,一切似乎都應該如此。 – hao 2009-04-22 04:31:56

回答

3

你應該閱讀的響應。

nosklo's answer到一個類似的問題:「PEP 333表示you must read environ['wsgi.input']」。

測試的代碼(改編自this answer):
       警告:該代碼僅用於示範的目的。
       警告:儘量避免硬編碼路徑或文件名。

def app(environ, start_response): 
    path = environ['PATH_INFO'] 
    method = environ['REQUEST_METHOD'] 
    if method == 'POST': 
     if path.startswith('/test'): 
      try: 
       request_body_size = int(environ['CONTENT_LENGTH']) 
       request_body = environ['wsgi.input'].read(request_body_size) 
      except (TypeError, ValueError): 
       request_body = "0" 
      try: 
       response_body = str(request_body) 
      except: 
       response_body = "error" 
      status = '200 OK' 
      headers = [('Content-type', 'text/plain')] 
      start_response(status, headers) 
      return [response_body] 
    else: 
     response_body = open('test.html').read() 
     status = '200 OK' 
     headers = [('Content-type', 'text/html'), 
        ('Content-Length', str(len(response_body)))] 
     start_response(status, headers) 
     return [response_body] 
+0

謝謝,這正是我需要的!然而,一個修改是將[5:]添加到response_body以避免'size ='部分。 – alfredodeza 2009-04-22 16:32:00