Dup Ver Goto 📝

BasicAjax

PT2/lang/python/web/ajax does not exist
To
196 lines, 456 words, 5165 chars Page 'BasicAjax' does not exist.
from http.server import BaseHTTPRequestHandler, HTTPServer

class MyServer(BaseHTTPRequestHandler):
  def do_GET(self):
    self.send_response(200)
    self.send_header("Content-type", "text/html")
    self.end_headers()
    self.wfile.write(bytes("Get something","utf8"))
  def do_POST(self):
    content_len = int(self.headers.get('Content-Length'))
    post_body = self.rfile.read(content_len)
    request = json.loads(post_body.decode())
    return self.doSomethingWith(request)

if __name__ == "__main__":    
  print(f"Starting server")
  webServer = HTTPServer((hostName, serverPort), MyServer)
  print("Server started http://%s:%s" % (hostName, serverPort))

  try:
    webServer.serve_forever()
  except KeyboardInterrupt:
    pass

  webServer.server_close()
  print("Server stopped.")

Example

Warning this is completely insecure, and is only here to serve as an example. This runs the command given to it in the JSON, and returns the output.

#!/usr/bin/env python


from http.server import BaseHTTPRequestHandler, HTTPServer
from subprocess import run, PIPE
import json

aim = """
Simple command execution.
Client POSTS JSON of the form
{
  cmd: [a,b,c]
}
Server replies with
{
  returncode: 0,
  stdout: "",
  stderr: ""
}
"""

hostName = ""
serverPort = 4001
class MyServer(BaseHTTPRequestHandler):
  def do_GET(self):
    self.send_response(200)
    self.send_header("Content-type", "text/html")
    self.end_headers()
    self.wfile.write(bytes("Must POST","utf8"))
  def do_POST(self):
    content_len = int(self.headers.get('Content-Length'))
    post_body = self.rfile.read(content_len)
    request = json.loads(post_body.decode())
    if "cmd" in request:
      return self.handle_cmd(request)
    reply = { "result": "unrecognised", "received": request }
    self.send_response(400)
    self.send_header("Content-type", "application/json")
    self.end_headers()
    self.wfile.write(json.dumps(reply).encode("utf8"))
  def handle_cmd(self,request):
    cmd = request["cmd"]
    try:
      m = run(cmd,stdout=PIPE,stderr=PIPE)
      reply = {
          "cmd": cmd,
          "returncode": m.returncode,
          "stdout": m.stdout.decode(),
          "stderr": m.stderr.decode()
          }
      code = 200
    except Exception as e:
      reply = {
          "cmd": cmd,
          "exception": str(e)
          }
      code = 500
    self.send_response(code)
    self.send_header("Content-type", "application/json")
    self.end_headers()
    self.wfile.write(json.dumps(reply).encode("utf8"))

if __name__ == "__main__":    
  print(f"Starting server")
  webServer = HTTPServer((hostName, serverPort), MyServer)
  print("Server started http://%s:%s" % (hostName, serverPort))

  try:
    webServer.serve_forever()
  except KeyboardInterrupt:
    pass

  webServer.server_close()
  print("Server stopped.")

Example

This is an AJAX wrapper around a simple script, in turn wrapping mpc, allowing me to easily control mpd from the command line.

#!/usr/bin/env python


from http.server import BaseHTTPRequestHandler, HTTPServer
from subprocess import run, PIPE
import json

aim = """
Simple command execution.
Client POSTS JSON of the form
{
  cmd: [a,b,c]
}
Server replies with
{
  returncode: 0,
  stdout: "",
  stderr: "",
  status: ""
}
"""

hostName = ""
serverPort = 4001
class MyServer(BaseHTTPRequestHandler):
  def do_GET(self):
    self.send_response(200)
    self.send_header("Content-type", "text/html")
    self.end_headers()
    self.wfile.write(bytes("Must POST","utf8"))
  def do_POST(self):
    content_len = int(self.headers.get('Content-Length'))
    post_body = self.rfile.read(content_len)
    request = json.loads(post_body.decode())
    if "cmd" in request:
      return self.handle_cmd(request)
    reply = { "result": "unrecognised", "received": request }
    self.send_response(400)
    self.send_header("Content-type", "application/json")
    self.end_headers()
    self.wfile.write(json.dumps(reply).encode("utf8"))
  def handle_cmd(self,request):
    cmd = request["cmd"]
    if "n" in request:
      n = request["n"]
    else:
      n = 0
    try:
      m = run(["mp",str(n),","]+cmd,stdout=PIPE,stderr=PIPE)
      rc = m.returncode
      reply = {
          "cmd": cmd,
          "returncode": m.returncode,
          "stdout": m.stdout.decode(),
          "stderr": m.stderr.decode()
          }
      m = run(["mp",str(n),",","status"],stdout=PIPE,stderr=PIPE)
      reply["status"] = m.stdout.decode()
      code = 200 if rc == 0 else 400
    except Exception as e:
      reply = {
          "cmd": cmd,
          "exception": str(e)
          }
      code = 500
    self.send_response(code)
    self.send_header("Content-type", "application/json")
    self.end_headers()
    self.wfile.write(json.dumps(reply).encode("utf8"))

if __name__ == "__main__":    
  print(f"Starting server")
  webServer = HTTPServer((hostName, serverPort), MyServer)
  print("Server started http://%s:%s" % (hostName, serverPort))

  try:
    webServer.serve_forever()
  except KeyboardInterrupt:
    pass

  webServer.server_close()
  print("Server stopped.")