使用WSGI将用户重定向到URL(无框架)

时间:2015-02-05 06:06:15

标签: python python-2.7 redirect wsgi wsgiref

我正在尝试使用python的WSGI开发一个小型Web应用程序。例如,如果用户选择Google,他们将被重定向到google.com,如果他们选择Facebook,则会将其重定向到facebook.com等。

from wsgiref.simple_server import make_server
from cgi import parse_qs, escape

main_html = """
<html>
<head><title> Welcome to redirection test page </title> </head>
<body>
    <form method="get" action='/visit'>
        <input type=radio name='site' value=google> Google
        <input type=radio name='site' value=facebook> Facebook
        <input type=submit value=submit>
    </form>
</body>
</html>
"""


def main(environ, start_response):

    response_body = main_html
    print type(response_body)   
    status = '200 OK'

    response_headers = [
                        ('Content-Type','text/html'),
                        ('Content-Length', str(len(response_body)))
                       ]


    start_response(status, response_headers)
    return [response_body]


def visit(environ, start_response):
    qs = parse_qs(environ['QUERY_STRING'])
    dest = qs.ge('site')[0]
    if dest == 'google':
        start_response('301 Moved Permanently', [('Location','http://google.com')])
    else:
        start_response('301 Moved Permanently', [('Location','http://facebook.com')])

    return [1]


def app(environ, start_response):
    if environ['PATH_INFO'] == '/':
        return main(environ, start_response)
    elif environ['PATH_INFO'] == '/visit':
        return visit(environ, start_response)

httpd =  make_server('192.168.48.128',8052, app)
print 'Serving on port 8052'
httpd.serve_forever()

但是,当我运行此代码时,我收到以下错误:

Traceback (most recent call last):
  File "/usr/lib/python2.7/wsgiref/handlers.py", line 86, in run
    self.finish_response()
  File "/usr/lib/python2.7/wsgiref/handlers.py", line 131, in finish_response
    self.close()
  File "/usr/lib/python2.7/wsgiref/simple_server.py", line 33, in close
    self.status.split(' ',1)[0], self.bytes_sent
AttributeError: 'NoneType' object has no attribute 'split'

2 个答案:

答案 0 :(得分:7)

你有两个问题,都在visit()内。第一个是拼写错误,第二个是未能遵守WSGI specification

def visit(environ, start_response):
    qs = parse_qs(environ['QUERY_STRING'])
    dest = qs.ge('site')[0]
    if dest == 'google':
        start_response('301 Moved Permanently', [('Location','http://google.com')])
    else:
        start_response('301 Moved Permanently', [('Location','http://facebook.com')])

    return [1]

查看第dest = qs.ge('site')[0]行。 qs只是一个字典,没有方法ge,只有get。此外,cgi.parse_qs is deprecated - 改为使用urlparse.parse_qs()。修复会给我们带来一个新错误(我的地址是127.0.0.1,因为我刚从localhost运行它):

127.0.0.1 - - [05/Feb/2015 16:45:17] "GET /visit?site=facebook HTTP/1.1" 302 0 
Traceback (most recent call last):
  File "C:\Python27\lib\wsgiref\handlers.py", line 86, in run
    self.finish_response()
  File "C:\Python27\lib\wsgiref\handlers.py", line 128, in finish_response
    self.write(data)
  File "C:\Python27\lib\wsgiref\handlers.py", line 204, in write
    assert type(data) is StringType, "write() argument must be string"
AssertionError: write() argument must be string

这告诉我们某些东西应该是一个字符串,但不是。再次回顾visit(),在返回线上,揭示了问题。您将返回[1]而不是['1']。修复该错误使一切正常。您会发现PEP 333

中记录了此行为
  

start_response callable必须返回一个write(body_data)callable,它接受一个位置参数:一个字符串,作为HTTP响应体的一部分写入。

最后,根据this answer,您可能应该使用'302 Found'状态而非'301 Moved Permanently'进行重定向,但无论如何都可以。

用此替换该功能应解决您的问题:

def visit(environ, start_response):
    qs = parse_qs(environ['QUERY_STRING'])
    dest = qs.get('site')[0]
    if dest == 'google':
        start_response('302 Found', [('Location','http://google.com')])
    else:
        start_response('302 Found', [('Location','http://facebook.com')])

    return ['1']

答案 1 :(得分:0)

响应主体必须是字节,而不是字符串。因此,您应该返回[b“ 1”]而不是[1]或[“ 1”]。