【发布时间】:2016-02-13 06:28:22
【问题描述】:
我正在尝试创建一个简单的 Python 服务器来测试我的前端。它应该能够处理 GET 和 POST 请求。数据应始终为 JSON 格式,直到它们被转换为 HTTP 请求/响应。应调用具有相应名称的脚本来处理每个请求。
server.py
#!/usr/bin/env python
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import SocketServer
import json
import urlparse
import subprocess
class S(BaseHTTPRequestHandler):
def _set_headers(self):
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
def do_GET(self):
self._set_headers()
parsed_path = urlparse.urlparse(self.path)
request_id = parsed_path.path
response = subprocess.check_output(["python", request_id])
self.wfile.write(json.dumps(response))
def do_POST(self):
self._set_headers()
parsed_path = urlparse.urlparse(self.path)
request_id = parsed_path.path
response = subprocess.check_output(["python", request_id])
self.wfile.write(json.dumps(response))
def do_HEAD(self):
self._set_headers()
def run(server_class=HTTPServer, handler_class=S, port=8000):
server_address = ('', port)
httpd = server_class(server_address, handler_class)
print 'Starting httpd...'
httpd.serve_forever()
if __name__ == "__main__":
from sys import argv
if len(argv) == 2:
run(port=int(argv[1]))
else:
run()
testscript.py 处理请求的示例,在这种情况下它只返回一个 JSON 对象。
#!/usr/bin/env python
return {'4': 5, '6': 7}
例如,服务器应返回 {'4': 5, '6': 7} 以获取格式为 http://www.domainname.com:8000/testscript 的响应。
我的问题是我不知道如何在两者之间传递变量,我需要帮助才能让它工作。
【问题讨论】:
-
你想在哪里传递变量?到服务器或类中的定义之间
-
本题主要返回python脚本之间的变量。但理想情况下,我想在 Httprequest -> server -> handler script -> server -> http response 之间传递 json
-
看看这个相关的帖子,它提供了一个工作 HTTP 服务器,为 Python2.7 提供 POST 支持stackoverflow.com/questions/31371166/…
标签: python json server httprequest httpresponse