使用JSON处理GET和POST请求的简单Python服务器

时间:2015-11-12 01:15:10

标签: python json server httprequest httpresponse

我试图创建一个简单的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的响应。

我的问题是,我无法弄清楚如何在两者之间传递变量,我需要帮助才能使其发挥作用。

1 个答案:

答案 0 :(得分:9)

Here is an example of server client in python. I am using bottle library to handle requests to server and create server.

Server Code

import subprocess
from bottle import run, post, request, response, get, route

@route('/<path>',method = 'POST')
def process(path):
    return subprocess.check_output(['python',path+'.py'],shell=True)

run(host='localhost', port=8080, debug=True)

It starts server on localhost:8080. You can pass file name you want to run run. Make sure that file is in the same path for above code to work or change path appropriately to run from different directory. Path corresponds to file name and it invokes process function when any path is given. If it cannot find file it raises exception Internal server error. You can call scripts from subdirectories too.

Client Code

import httplib, subprocess

c = httplib.HTTPConnection('localhost', 8080)
c.request('POST', '/return', '{}')
doc = c.getresponse().read()
print doc

It invokes a POST request to localhost:8080/return

return.py

def func():
    print {'4': 5, '6': 7}
func()

Make sure you print your output response as we are using subprocess.check_output() as it catches only print statements.

Use Popen in subprocess to open a continuous connection instead of check_output to pass arguments to function in server

Check this documentation on how to extract POST or GET values

相关问题