使用 JSON 处理 GET 和 POST 请求的简单 Python 服务器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33662842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple Python server to process GET and POST requests with JSON
提问by Peter G.
I'm trying to create a simple Python server in order to test my frontend. It should be able to handle GET and POST requests. The data should be always in JSON format until they are translated to HTTP request/response. A script with corresponding name should be called to handle each request.
我正在尝试创建一个简单的 Python 服务器来测试我的前端。它应该能够处理 GET 和 POST 请求。数据应始终为 JSON 格式,直到它们被转换为 HTTP 请求/响应。应调用具有相应名称的脚本来处理每个请求。
server.py
服务器.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()
Example of testscript.py
for handling requests, which in this case just returns a JSON object.
testscript.py
处理请求的示例,在本例中仅返回一个 JSON 对象。
#!/usr/bin/env python
return {'4': 5, '6': 7}
The server should for example return {'4': 5, '6': 7}
for a response in format http://www.domainname.com:8000/testscript.
例如,服务器应该以http://www.domainname.com:8000/testscript{'4': 5, '6': 7}
格式返回响应。
My problem is that I can't figure out how to pass variables in between and I need help to make it work.
我的问题是我不知道如何在两者之间传递变量,我需要帮助才能使它工作。
采纳答案by Harwee
Here is an example of server client in python. I am using bottlelibrary to handle requests to server and create server.
这是python中的服务器客户端示例。我正在使用Bottle库来处理对服务器的请求并创建服务器。
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.
它在 上启动服务器localhost:8080
。您可以传递要运行的文件名。确保该文件位于相同的路径中以使上述代码工作或适当更改路径以从不同目录运行。路径对应于文件名,process
当给出任何路径时它会调用函数。如果找不到文件,则会引发异常内部服务器错误。您也可以从子目录调用脚本。
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
它调用一个 POST 请求到 localhost:8080/return
return.py
返回.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.
确保像我们使用的subprocess.check_output()
那样打印输出响应,因为它只捕获打印语句。
Use Popen
in subprocess
to open a continuous connection instead of check_output
to pass arguments to function in server
使用Popen
insubprocess
打开一个连续的连接,而不是check_output
将参数传递给服务器中的函数
Check this documentationon how to extract POST or GET values
查看有关如何提取 POST 或 GET 值的文档
回答by Erik Aronesty
I use this:
我用这个:
https://gist.github.com/earonesty/ab07b4c0fea2c226e75b3d538cc0dc55
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()
That particular wrapper allows you to easily listen on port 0 (random high port) which some frameworks obfuscate. It automatically handles GET/POST requests for all routes, and it merges in URI arguments with the top level JSON object arguments. Which is good enough for me in most cases.
该特定包装器允许您轻松侦听某些框架混淆的端口 0(随机高端口)。它自动处理所有路由的 GET/POST 请求,并将 URI 参数与顶级 JSON 对象参数合并。在大多数情况下,这对我来说已经足够了。
It's a lot lighter weight than most frameworks. Test cases in the gist show better how it works.
它的重量比大多数框架轻得多。要点中的测试用例更好地展示了它是如何工作的。