added 3 urls /user-data, /meta-data, and /finished for Serving Static Content

master
coolguy-cell 2 years ago
parent 00eec0c309
commit 46b499d45f
No known key found for this signature in database
GPG Key ID: CD3A42E1D470AD70
  1. 9
      config.ini
  2. 1
      data/localhost/metadata_extra/meta_data_extra.txt
  3. 2
      data/localhost/user-data/sample_file.txt
  4. 75
      main.py

@ -0,0 +1,9 @@
[server]
server_host = 127.0.0.1
server_port = 8081
[app]
user_data = sample_file.txt
meta_data = meta_data_extra.txt

@ -0,0 +1,2 @@
This is a sample static file to be served
from cherrypy server at user-data url.

@ -0,0 +1,75 @@
import os
import sys
import cherrypy
from cherrypy.lib.static import serve_file
import json
import socket
import configparser
PATH = os.path.dirname(os.path.abspath(__file__))
config = configparser.ConfigParser()
config.read("config.ini")
user_data_filename = config["app"].get("user_data", "sample_file.txt")
meta_data_filename = config["app"].get("meta_data", "meta_data_extra.txt")
class MainApp:
@cherrypy.expose
def user_data(self):
hostname = socket.gethostbyaddr(str(cherrypy.request.remote.ip))[0]
filename = user_data_filename
filepath = os.path.join(PATH, "data", hostname, "user-data", filename)
return serve_file(filepath, "application/x-download", "attachment")
@cherrypy.expose
@cherrypy.tools.json_out()
def meta_data(self):
host_info = socket.gethostbyaddr(str(cherrypy.request.remote.ip))
hostname = host_info[0]
data = {"instance-id": hostname.split(".")[0], "local-hostname": hostname}
folder = os.path.join(PATH, "data", hostname, "metadata_extra")
if os.path.exists(folder):
with open(os.path.join(folder, meta_data_filename), "r") as f:
lines = f.readlines()
for line in lines:
ls = list(map(lambda k: k.strip(), line.split(":")))
data[ls[0]] = ls[1]
return data
@cherrypy.expose
def finished(self, data):
hostname = socket.gethostbyaddr(str(cherrypy.request.remote.ip))[0]
folder = os.path.join(PATH, "data", hostname, "metadata_extra")
if not os.path.exists(folder):
os.makedirs(folder)
with open(os.path.join(folder, meta_data_filename), "w") as f:
f.write(data)
ROOT = MainApp()
if __name__ == "__main__":
cherrypy.server.socket_host = config["server"].get("server_host", "127.0.0.1")
cherrypy.server.socket_port = config["server"].getint("server_port", 8081)
ENGINE = cherrypy.engine
cherrypy.tree.mount(ROOT)
if hasattr(ENGINE, "signal_handler"):
ENGINE.signal_handler.subscribe()
if hasattr(ENGINE, "console_control_handler"):
ENGINE.console_control_handler.subscribe()
try:
ENGINE.start()
except Exception:
sys.exit(1)
else:
ENGINE.block()
Loading…
Cancel
Save