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

标签 python json server httprequest httpresponse

我正在尝试创建一个简单的 Python 服务器来测试我的前端。它应该能够处理 GET 和 POST 请求。在将数据转换为 HTTP 请求/响应之前,数据应始终采用 JSON 格式。应调用具有相应名称的脚本来处理每个请求。

服务器.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 中的服务器客户端示例。我正在使用 bottle处理对服务器的请求和创建服务器的库。

服务器代码

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)

它在 localhost:8080 上启动服务器。您可以传递要运行的文件名。确保该文件位于同一路径中,以便上述代码正常工作或适当更改路径以从不同目录运行。路径对应文件名,给定任何路径都会调用process函数。如果找不到文件,则会引发异常内部服务器错误。您也可以从子目录调用脚本。

客户端代码

import httplib, subprocess

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

它调用一个 POST 请求到 localhost:8080/return

返回.py

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

确保您在我们使用 subprocess.check_output() 时打印您的输出响应,因为它只捕获打印语句。

subprocess 中使用 Popen 打开连续连接,而不是使用 check_output 将参数传递给服务器中的函数

检查这个documentation关于如何提取 POST 或 GET 值

关于python - 使用 JSON 处理 GET 和 POST 请求的简单 Python 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33662842/

相关文章:

python - numpy python中的"AttributeError: '矩阵' object has no attribute '等历'"

python - 在 Bokeh 中隐藏注释

jquery - 使用 JQuery 将 JSON 对象解析为数组

json - 在 jointjs-Rappid 中向 basic.Image 类型的模板形状添加标签

css - 如何在 Oxygen 中使用 XSLT 从单个 XML 文件拆分为 3 个 JSON

java - 如何禁用 SSL session 缓存服务器端 java?

python pandas 在最后一个非 NaN 值处停止 fillna

c# - 我希望生成一个具体名词列表......带有图片和相关句子

c# - FBRemoteEvent 使应用程序崩溃

mysql - Web服务器和api服务器-配置和代码上传