Pet*_* G. 10 python json httpresponse httprequest server
我正在尝试创建一个简单的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()
Run Code Online (Sandbox Code Playgroud)
testscript.py处理请求的示例,在这种情况下只返回一个JSON对象.
#!/usr/bin/env python
return {'4': 5, '6': 7}
Run Code Online (Sandbox Code Playgroud)
例如,服务器应返回{'4': 5, '6': 7}格式为http://www.domainname.com:8000/testscript的响应.
我的问题是我无法弄清楚如何在两者之间传递变量,我需要帮助才能使其工作.
以下是python中服务器客户端的示例.我正在使用瓶库来处理对服务器和创建服务器的请求.
服务器代码
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)
Run Code Online (Sandbox Code Playgroud)
它启动服务器localhost:8080.您可以传递要运行的文件名.确保该文件位于上述代码的相同路径中,或者相应地更改路径以从不同目录运行.Path对应于文件名,它process在给出任何路径时调用函数.如果找不到文件,则会引发异常内部服务器错误.您也可以从子目录调用脚本.
客户代码
import httplib, subprocess
c = httplib.HTTPConnection('localhost', 8080)
c.request('POST', '/return', '{}')
doc = c.getresponse().read()
print doc
Run Code Online (Sandbox Code Playgroud)
它调用POST请求 localhost:8080/return
return.py
def func():
print {'4': 5, '6': 7}
func()
Run Code Online (Sandbox Code Playgroud)
确保在我们使用时打印输出响应,subprocess.check_output()因为它只捕获打印语句.
使用Popen在subprocess打开的持续连接,而不是check_output传递参数在服务器中正常工作
请查看此文档,了解如何提取POST或GET值
我用这个:
https://gist.github.com/earonesty/ab07b4c0fea2c226e75b3d538cc0dc55
from apiserve import ApiServer, ApiRoute
class MyServer(ApiServer):
@ApiRoute("/popup")
def addbar(req):
return {"boo":req["bar"]+1}
@ApiRoute("/baz")
def justret(req):
if req:
raise ApiError(501,"no data in for baz")
return {"obj":1}
MyServer("127.0.0.1",8000).serve_forever()
Run Code Online (Sandbox Code Playgroud)
该特定的包装器允许您轻松侦听某些框架混淆的端口 0(随机高端口)。它自动处理所有路由的 GET/POST 请求,并将 URI 参数与顶级 JSON 对象参数合并。在大多数情况下这对我来说已经足够了。
它比大多数框架轻得多。要点中的测试用例更好地展示了它是如何工作的。
| 归档时间: |
|
| 查看次数: |
36888 次 |
| 最近记录: |