Page MenuHomec4science

server.py
No OneTemporary

File Metadata

Created
Thu, May 2, 17:44

server.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" This program can be used to send xml data as json over http.
"""
# Copyright (C) University of Basel 2020 {{{1
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/> 1}}}
import getopt
from http.server import BaseHTTPRequestHandler, HTTPServer, SimpleHTTPRequestHandler
import http.client
import simplejson as json
from os.path import exists, isfile, isdir, dirname, basename
import cgi
import sys
from interactive_editor import ResponseOrganizer
sys.path.append('svgscripts')
from convert_wordPositions import JSONConverter
from datatypes.page import Page
__author__ = "Christian Steiner"
__maintainer__ = __author__
__copyright__ = 'University of Basel'
__email__ = "christian.steiner@unibas.ch"
__status__ = "Development"
__license__ = "GPL v3"
__version__ = "0.0.1"
UNITTESTING = False
class Server(BaseHTTPRequestHandler):
CONTENT_TYPE = 'Content-Type'
CONTENT_LENGTH = 'Content-Length'
CONFIG_FILE = '.local_variables'
XML = 'xml'
SVG = 'svg'
MANUSCRIPT = 'manuscript'
@classmethod
def get_local_file_dictionary(cls) ->dict:
"""Return a dictionary about local files with keys: XML, SVG, MANUSCRIPT.
"""
local_file_dictionary = {}
if isfile(cls.CONFIG_FILE):
with open(cls.CONFIG_FILE, 'r') as reader:
for raw_line in reader.readlines():
line = raw_line.replace('\n', '')
line_content = line.split('=')
if len(line_content) == 2\
and isfile(line_content[1]):
local_file_dictionary.update({line_content[0]: line_content[1]})
return local_file_dictionary
def _set_headers(self, response_code):
self.send_response(response_code)
self.send_header('Content-type', 'application/json')
#self.send_header('Access-Control-Allow-Credentials', 'true')
self.send_header("Cache-Control", "no-cache")
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
self.send_header("Access-Control-Allow-Headers", "X-Requested-With")
self.send_header("Access-Control-Allow-Headers", "Content-Type")
self.end_headers()
def do_HEAD(self):
self._set_headers(200)
def do_OPTIONS(self):
"""Process OPTIONS.
"""
self.send_response(200, "ok")
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
self.send_header("Access-Control-Allow-Headers", "X-Requested-With")
self.send_header("Access-Control-Allow-Headers", "Content-Type")
self.end_headers()
def do_GET(self):
"""Process GET.
"""
self._set_headers(200)
local_file_dictionary = Server.get_local_file_dictionary()
if self.XML in local_file_dictionary.keys():
response_organizer = ResponseOrganizer()
json_dict = response_organizer.create_json_dict(local_file_dictionary[self.XML])
self.wfile.write(str.encode(json.dumps(json_dict)))
def _parse_header(self, key) ->str:
"""Return content of header for key.
"""
headers = [ header for header in self.headers._headers if key in header ]
if len(headers) > 0:
return headers[0][1]
return ''
def do_POST(self):
"""Process POST.
"""
ctype = self._parse_header(self.CONTENT_TYPE)
if ctype != 'application/json':
length = int(self._parse_header(self.CONTENT_LENGTH))
self._send_error()
return
# read the message and convert it into a python dictionary
length = int(self._parse_header(self.CONTENT_LENGTH))
response = json.loads(self.rfile.read(length))
response_organizer = ResponseOrganizer()
json_dict = response_organizer.handle_response(response)
self._set_headers(200)
self.wfile.write(str.encode(json.dumps(json_dict)))
def _send_error(self):
"""Send error msg.
"""
self._set_headers(400)
self.end_headers()
def run(port=8008):
server_address = ('', port)
httpd = HTTPServer(server_address, Server)
print(f'Starting httpd on port {port}...')
httpd.serve_forever()
def usage():
"""prints information on how to use the script
"""
print(main.__doc__)
def main(argv):
"""This program can be used to send xml data as json over http.
fixes/server.py OPTIONS
OPTIONS:
-h|--help: show help
:return: exit code (int)
"""
try:
opts, args = getopt.getopt(argv, "h", ["help"])
except getopt.GetoptError:
usage()
return 2
for opt, arg in opts:
if opt in ('-h', '--help') or not args:
usage()
return 0
run()
return exit_code
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))

Event Timeline