我编写了以下代码以接受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代码(最好不要更改上述代码太多,因为它有很多)。
我找到了一种将您的代码与nginx服务器连接的方法。首先,使用您的功能添加一些代码添加创建套接字,然后编写Nginx Conf File。它将起作用
步骤1:
在您的功能中添加main()函数
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())
def main():
try:
server = HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler)
print ('Starting BaseServer.')
server.serve_forever ()
except KeyboardInterrupt:
print ('Interrupt recieved; closing server socket')
server.socket.close()
if __name__ == '__main__':
main()
步骤2:
nginx.conf文件应该像这个
server {
location / {
root /data/www;
}
location / {
proxy_pass http://localhost:8000;
}
}
如果面对下面的任何问题评论