Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating a API between servers with python

I would like to make a python script that runs on two servers I would like to break the work in between the servers by having a way to send information between them. Would creating an API be the best way to establish this task? Is there other ways to achieve this?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is a simple way to make a Threadings server where Clients can Connect, Disconnect, and send information. Hopefully, this could help you.

import threading

class Server:
    def __init__(self, name):
        self.name = name
        self.clients = []
        self.messages = []
        self.lock = threading.Lock()

    def register(self, client):
        with self.lock:
            self.clients.append(client)

    def unregister(self, client):
        with self.lock:
            self.clients.remove(client)

    def send(self, msg):
        with self.lock:
            self.messages.append(msg)

    def get_messages(self):
        with self.lock:
            messages = self.messages[:]
            self.messages = []
            return messages

    def get_clients(self):
        with self.lock:
            return self.clients[:]

class Client:
    def __init__(self, name):
        self.name = name
        self.server = None

    def connect(self, server):
        self.server = server
        self.server.register(self)

    def disconnect(self):
        self.server.unregister(self)
        self.server = None

    def send(self, msg):
        self.server.send(msg)

    def get_messages(self):
        return self.server.get_messages()

    def get_clients(self):
        return self.server.get_clients()

Server1 = Server("Server1")
Client1 = Client("Client1")
Client2 = Client("Client2")

#connect the clients to the servers
Client1.connect(Server1)
Client2.connect(Server1)

#get the clients from the servers
print(Server1.get_clients())

#send messages from the clients
Client1.send("Hello")
Client2.send("Hi")

#get the messages from the servers
print(Server1.get_messages())

#disconnect the clients from the servers
Client1.disconnect()
Client2.disconnect()

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading