How to open localhost server in Python



In this tutorial, I want to guide you how to open a localhost server in Python. This scenario would be useful, if you want to connect other Web Framework such as PHP, Ruby on rails, Node js … to Python and let Python handle specific problem like as OpenCV, Tensorflow, Numpy … The Web Framework will request to Python Server to process something and response the result.

First you need to create config.json, this file helps you to navigate all setting in Python easily.

{
  "server": "localhost",
  "pythonPort": 3030
}

Notice: Above fiels are just my default settings, you can change whatever you want.

Now you need to create a python file called “serverProcessing.py”. And add these code.

import json
import urlparse
from ServiceSegment.Segmentation import Kmean       # example, I imported the Kmean library to handle this process.
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

# Server process

with open('./config.json') as data_file:    
    config = json.load(data_file)

host = config["server"]
port = int(config["pythonPort"])

class MyHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        try:

            parsed = urlparse.urlparse(self.path)
            # sample url query path.
            folderPath = urlparse.parse_qs(parsed.query)['path'][0]
            framePath = urlparse.parse_qs(parsed.query)['frame'][0]
            kMean = int(urlparse.parse_qs(parsed.query)['knumber'][0])

            print "Folder path: " + folderPath
            print "Frame path: " + framePath
            print "Number of images: " + str(numImg)
            print "K mean Number: " + str(kMean)

            process = Kmean(folderPath, folderPath, framePath, width, kMean, "jpg")  # this is my Class K mean
            process.segment();                

            self.send_response(200)
            self.end_headers()
            self.wfile.write("Process is completed");

        except IOError:
            self.send_error(404,'File Not Found: %s' % self.path)


    # do something related to HTTP POST process. You can ignore this if you needn't.
    def do_POST(self):
        global rootnode
        try:

        except :
            pass

def mainServer():
    try:
        server = HTTPServer(('', port), MyHandler)
        serverInfo = 'started httpserver ' + host + ':' + str(port) + '...'
        print serverInfo
        server.serve_forever()
    except KeyboardInterrupt:
        print '^C received, shutting down server'
        server.socket.close()


if __name__ == '__main__' :
    mainServer()

You can see, I’ve imported the example K mean library, then in do_GET function you can see:

process = Kmean(folderPath, folderPath, framePath, width, kMean, "jpg")
process.segment();

The “process” variable will use Kmean class to segment the image.

The url to request to the server will be like “http://localhost:3030/?path=example&frame=example&kmean=example

That’s done. Whenever Python receive requests, it will handle segment image function.

Now it’s time to run your file.

python serverProcessing.py

You will see the server is waiting the request.

If you have any questions, feel free to put your questions here. I will answer as soon as possible.

One thought on “How to open localhost server in Python

Leave a Reply

Your email address will not be published. Required fields are marked *