Python:从localhost调用另一个localhost服务器

时间:2015-04-07 16:42:14

标签: python wsgiref

def jsonCatch(environ,start_response):
     results = requests.get("http://localhost:8055/jsonResponse") 
     start_response('200 OK', [('Content-Type', 'application/json')])
     return results.json()

from wsgiref.simple_server import make_server
httpd = make_server('', 8050, application)
print('Serving on port 8050...')
httpd.serve_forever()

在端口8055上提供服务

def jsonResponse(environ,start_response):
    responseData={}
    responseData['name']="alex"
    responseData['age']="12"
    start_response('200 OK',[('Content-Type', 'application/json')])    
    return json.dumps(responseData)


[ERROR]

Traceback (most recent call last):
File       "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/wsgiref/handlers.py", line 86, in run
self.finish_response()
File   "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/wsgiref/handlers.py", line 128, in finish_response
self.write(data)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/wsgiref/handlers.py", line 204, in write
assert type(data) is StringType,"write() argument must be string"
AssertionError: write() argument must be string
127.0.0.1 - - [07/Apr/2015 09:50:04] "GET /jsonCatch HTTP/1.1" 500 59
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 52274)
Traceback (most recent call last):
 File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 295, in _handle_request_noblock
self.process_request(request, client_address)
 File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 321, in process_request
self.finish_request(request, client_address)
 File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 334, in finish_request
self.RequestHandlerClass(request, client_address, self)
 File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 649, in __init__
self.handle()
 File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/wsgiref/simple_server.py", line 124, in handle
handler.run(self.server.get_app())
 File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/wsgiref/handlers.py", line 92, in run
self.close()
 File "/System/Library/Frameworks/Python.framework/Versions/2.7/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'

编辑:将https更改为http并在服务器上更改

我正在尝试访问一个返回json响应的localhost服务器,并由另一个localhost服务器使用。有人能告诉我一个例子吗?

2 个答案:

答案 0 :(得分:1)

我已将上述代码更改为

n=json.loads(results.text)
start_response('200 OK', [('Content-Type', 'text/plain')])
return n['name'].encode('utf-8')

它返回给我“alex”

答案 1 :(得分:0)

尝试在此行使用http://代替https://results = requests.get("https://localhost:8055/jsonResponse")