Can I use WSGI with a URI that has spaces?
I wrote a sm开发者_如何学JAVAall WSGI App:
def foo(environ, start_response):
bar = 'Your request is %s' % environ['PATH_INFO']
status = '200 OK'
response_headers = [('Content-type', 'text/plain'),
('Content-Length', str(len(bar)))]
start_response(status, response_headers)
return [bar]
if __name__ == '__main__':
from wsgiref.simple_server import make_server
server = make_server('localhost', 8000, foo)
print "Running..."
server.serve_forever()
And another script to test:
import urllib2
checkURL = 'http://localhost:8000/foo bar'
print urllib2.urlopen(checkURL).read()
I run script 1 (WSGI App). When run script 2, I has a problem here. WSGI doesn't retrieve request from script 2 (checkURL has a space between foo and bar) and all other request to my WSGI not responding. Now, how do I correct this problem when url request has spaces?
From http://www.ietf.org/rfc/rfc2396.txt
The space character is excluded because significant spaces may disappear and insignificant spaces may be introduced when URI are transcribed or typeset or subjected to the treatment of word- processing programs. Whitespace is also used to delimit URI in many contexts.
space = <US-ASCII coded character 20 hexadecimal>
Bottom line. No, you cannot use a space. It is not a problem with the WSGI server. It is a problem with your URI.
Further, you should not be using the WSGI server stand-alone. You should be using it embedded in Apache via mod_wsgi
. When you do this, Apache will handle the illegal URI requests for you.
Update
Typically a WSGI URI will look something like localhost:8000/foo/bar/baz
or localhost:8000/?foo=bar
and not use spaces, so I suspect that the server is timing out because it doesn't have built-in handling for spaces.
Maybe your question is really "Can I use WSGI with a URI that has spaces?" -- I think the answer is No, as @S.Lott explains that server's front-end should handle this for you; you shouldn't need to worry about spaces in your WSGI app.
Original answer
If replacing spaces is a fix (your reply to my comment seems like it is) , then you can use urllib2.quote()
to replace the spaces in your URL with %20, like this:
checkURL = 'http://localhost:8000/%s' % urllib2.quote('foo bar')
I moved from wsgiref.simple_server to cherrypy and it work well. Client request will time out after about 1s. Thanks jcoon and S.Lott very much!
You should use "%20" in URL's to encode spaces into then -- but don't do that manually: use urllib.quote function, like:
import urllib base = "http://localhost:8000/" path = urllib.quote("foo bar") checkURL = base + path
(there is also the "unquote" function for you to use serverside)
精彩评论