Home > OS >  Creating a API between servers with python
Creating a API between servers with python

Time:05-03

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?

CodePudding user response:

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()

  • Related