1

I've a problem with a python web server based on HTTPServer:

INTRODUCTION: I've a system of cameras: 2 in each computer. Each computer has his python web server which manage the cameras settings. The camera settings are stored in a xml file. Then I've another computer with a software (in python) which manage the data from the cameras. Also this software has a settings file in xml and a web server in python

PROBLEM: I did an interface in html/jquery which send requests to the servers. The problem is when I send an Ajax request to the server situated in the "cameras computer" for the xml file from a page situated in another server.

This is the AJAX Request:

$.ajax({
        type: "GET",
        url: "http://"+ipCompleto+":8081/"+$(this).attr("port")+"/default.xml",
        dataType: "xml",
        success: function(xml){

            bordoBlob = $(xml).find('dimBordoBlob').text();
            blobSize = $(xml).find('blobSize').text();
            hMin = $(xml).find('intval1').text();
            hMax = $(xml).find('intval2').text();
            $("#inputHMax").val(hMax);
            $("#titoloHMax").text(hMax);
            $("#inputHMin").val(hMin);
            $("#titoloHMin").text(hMin);
            $("#minBlobSizeValue").val(blobSize);
            $("#minBlobSizeTitle").text(blobSize);
            $("#blobBorderSizeValue").val(blobSize);
            $("#blobBorderSizeTitle").text(blobSize);   
        },
        error: function() {
            alert("An error occurred while processing XML file.");
        }       
    });

This is the server:

#!/usr/bin/env python
from http.server import BaseHTTPRequestHandler, HTTPServer
from xml.dom import minidom
import os
import time
from stat import *
class MyHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        self.data_string = self.rfile.read(int(self.headers['Content-Length']))
        self.send_response(200)
        self.end_headers()
        valore = str(self.data_string)[2:-1]
        response = ["",""]
        response[0],response[1] = processData(valore)
        if response[0] == 1:
            sep = ""
            message = ""
            for res in response[1]:
                message += res
            response = sep.join(message)
            self.wfile.write(bytes(message, "utf-8"))

    def do_GET(self):
        # Send response status code
        self.send_response(200)
        self.send_header('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0')
        # Send headers
        if self.path.endswith("html"):
            self.send_header('Content-type', 'text/html')
            self.end_headers()
        elif self.path.endswith("css"):
            self.send_header('Content-type', 'text/css')
            self.end_headers()
        elif self.path.endswith("xml"):
            self.send_header('Content-type', 'text/xml')
            self.end_headers()
        elif self.path.endswith("js"):
            self.send_header('Content-type', 'application/javascript')
            self.end_headers()
        if not self.path.endswith("jpeg") and not self.path.endswith("jpg") and not self.path.endswith("png") and not self.path.endswith("gif"):
            with open(self.path[1:], 'r') as myfile:
                data = myfile.read()
            # Write content as utf-8 data
            self.wfile.write(bytes(data, "utf8"))
        if self.path.endswith("jpeg"):
            f = open(self.path[1:], 'rb')
            self.send_response(200)
            self.send_header('Content-type', 'image/jpeg')
            self.send_header('Cache-Control', 'no-store')
            self.end_headers()
            self.wfile.write(f.read())
            f.close()
        elif self.path.endswith("png"):
            f = open(self.path[1:], 'rb')
            self.send_response(200)
            self.send_header('Content-type', 'image/png')
            self.end_headers()
            self.wfile.write(f.read())
            f.close()
        elif self.path.endswith("gif"):
            f = open(self.path[1:], 'rb')
            self.send_response(200)
            self.send_header('Content-type', 'image/gif')
            self.end_headers()
            self.wfile.write(f.read())
            f.close()
        elif self.path.endswith("jpg"):
            f = open(self.path[1:], 'rb')
            self.send_response(200)
            self.send_header('Content-type', 'image/jpeg')
            self.end_headers()
            self.wfile.write(f.read())
            f.close()
        return

def run():
    print('starting server...')

    # Server settings
    # Choose port 8080, for port 80, which is normally used for a http server, you need root access
    server_address = ('192.168.2.245', 8081)
    httpd = HTTPServer(server_address, MyHandler)
    print('running server...')
    httpd.serve_forever()


def processData(data):
    XMLlist = []
    data = data.split(":")
    field = data[0].split(">")
    print(data,field,data[2])
    try:
        exists = field[2]
    except:
        exists = False
    if data[0] == "XMLlist":
        path = os.path.realpath(__file__)
        path = os.path.dirname(path)
        path = path+"/"+data[2]
        for filename in os.listdir(path):
            if filename.endswith('.xml'):
                XMLlist.append(filename[:-3])
        return 1,XMLlist
    elif exists != False:
        file = open(data[2]+data[3], 'r')
        tree = minidom.parse(file)
        camera = tree.getElementsByTagName(field[0])
        for element in camera:
            if element.getAttribute('id') == str(field[1]):
                print(data[1], field[0], field[1], field[2])
                element.getElementsByTagName(field[2])[0].childNodes[0].replaceWholeText(data[1])
        file = open(data[2]+data[3], 'w')
        tree.writexml(file)
        file.close()
        return 0, 0
    else:
        print(data)
        file = open(data[2]+data[3], 'r')
        tree = minidom.parse(file)
        tree.getElementsByTagName(data[0])[0].childNodes[0].replaceWholeText(data[1])
        file = open(data[2]+data[3], 'w')
        tree.writexml(file)
        file.close()
        return 0, 1
run()

Thank you for the answers and sorry for my bad english!

1

1 Answer 1

2

The Access-Control-Allow-Origin response header indicates whether the response can be shared with resources with the given origin.

You need to add this header to your response :

Access-Control-Allow-Origin: *

Unfortunately, SimpleHTTPServer is really that simple that it does not allow any customization, especially not of the headers it sends. You can however create a simple HTTP server yourself, using most of SimpleHTTPServerRequestHandler, and just add that desired header. or subclass SimpleHTTPServer.SimpleHTTPRequestHandler and changeing the behavior of end_headers()

import SimpleHTTPServer

class MyHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def end_headers(self):
        self.send_my_headers()

        SimpleHTTPServer.SimpleHTTPRequestHandler.end_headers(self)

    def send_my_headers(self):
        self.send_header("Access-Control-Allow-Origin", "*")

if __name__ == '__main__':
    SimpleHTTPServer.test(HandlerClass=MyHTTPRequestHandler)

Thank this answer for the code & This guy answer has all what you need to understand cros

Sign up to request clarification or add additional context in comments.

1 Comment

thank you very much. I'll try to follow the answers! I'll let you know...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.