【发布时间】:2019-03-18 17:58:17
【问题描述】:
我编写了以下代码来接受HTTP POST,然后写出一个包含POST 数据的临时文件,然后使用subprocess 和UNIX 的lp 命令将该临时文件发送到打印机。
from http.server import HTTPServer, BaseHTTPRequestHandler
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.end_headers()
self.wfile.write(b'Hello, world!')
def do_POST(self):
content_length = int(self.headers['Content-Length'])
body = self.rfile.read(content_length)
try:
result = json.loads(body, encoding='utf-8')
# Do other stuff with result
p = subprocess.Popen(['/usr/bin/env', 'lp', '-d', printer_queue, temp.name], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
self.send_response(200)
self.end_headers()
response = BytesIO()
response.write(b'POST Received: ')
response.write(body)
self.wfile.write(response.getvalue())
except Exception as err:
tb = traceback.format_exc()
print(tb)
self.send_response(500) # 500 Internal Server Error
self.end_headers()
response = BytesIO()
response.write(b'ERROR: Blah')
self.wfile.write(response.getvalue())
httpd = HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler)
一切都很棒。然后我读到HTTPServer 不应该在生产中使用,一切都不再那么棒了。
那么如何编写可以用作生产服务器的等效代码呢?我有一个 Apache Web 服务器,但我不知道如何将上面的 Python 代码添加到它(最好不要过多地更改上面的代码,因为它有很多)。
【问题讨论】:
-
“生产”对您意味着什么?你认为你的 python 代码足够稳定,可以在生产服务器上运行吗?
-
“稳定”对您意味着什么?代码工作正常。生产意味着需要安全的系统。