3.1.2. Creating Your First Service Using Python¶
This guide will walk you through creating a simple service using Python. We’ll create a basic temperature monitoring service as an example.
3.1.2.1. Prerequisites¶
Python 3.x installed
Basic understanding of Python programming
XML-RPC library (included in Python standard library)
3.1.2.2. Basic Service Structure¶
A basic service consists of:
Required imports
Service functions
XML-RPC server setup
Here’s a minimal template:
import xmlrpc.server
import json
# Service functions
def hello(message):
print(f"Temperature service received: {message}")
return "Temperature service is running"
# Start the server
server = xmlrpc.server.SimpleXMLRPCServer(("localhost", 8020), allow_none=True)
server.register_function(hello)
server.serve_forever()
3.1.2.3. Adding Service Functionality¶
Let’s expand our temperature service with some useful functions:
import xmlrpc.server
import json
import random # For demo purposes
class TemperatureService:
def __init__(self):
self.current_temp = 20.0 # Default temperature
def get_temperature(self):
# Simulate temperature reading
self.current_temp += random.uniform(-0.5, 0.5)
return json.dumps({
"temperature": round(self.current_temp, 2),
"unit": "Celsius"
})
def set_unit(self, unit):
if unit not in ["Celsius", "Fahrenheit"]:
return json.dumps({"error": "Invalid unit"})
return json.dumps({"status": "Unit updated"})
# Create service instance
temp_service = TemperatureService()
# Start the server
server = xmlrpc.server.SimpleXMLRPCServer(("localhost", 8020), allow_none=True)
server.register_function(temp_service.get_temperature)
server.register_function(temp_service.set_unit)
server.serve_forever()
3.1.2.4. Complete Example¶
Here’s a complete example of a simple service:
import xmlrpc.server
import json
import logging
import time
# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class SimpleService:
def __init__(self):
self.name = "SimpleService"
def hello(self, message):
logger.info(f"Received message: {message}")
return json.dumps({
"status": "ok",
"message": f"Hello from {self.name}"
})
def get_status(self):
return json.dumps({
"service": self.name,
"timestamp": time.time(),
"status": "running"
})
def event(self, sender, event_name, parameters):
logger.info(f"Event from {sender}: {event_name}")
return json.dumps({"status": "event_processed"})
def main():
# Create service instance
service = SimpleService()
# Configure server
server = xmlrpc.server.SimpleXMLRPCServer(
("localhost", 8020),
allow_none=True
)
# Register functions
server.register_function(service.hello)
server.register_function(service.get_status)
server.register_function(service.event)
# Start server
logger.info("Starting Simple Service on port 8020")
server.serve_forever()
if __name__ == "__main__":
main()
3.1.2.5. Testing Your Service¶
You can test your service using the Python XML-RPC client:
import xmlrpc.client
# Connect to your service
service = xmlrpc.client.ServerProxy("http://localhost:8020/")
# Test the service
print(service.hello("test"))
print(service.get_status())
3.1.3. Deploying the service in adminembedded¶
3.1.3.1. Creating the Manifest¶
To deploy your service, you’ll need to create a manifest.json file in your project directory. This file describes your service and how it should be executed.
{
"application_id": "",
"application_name": "temperature_service",
"application_version": "1.0",
"application_description": "Simple temperature monitoring service",
"application_commandline": "/bin/python3 temperature_service.py",
"monitoring_status_file_path": "status.json",
"running_user": "user",
"additional_properties": {},
"content_path": "content_path",
"service_name": "temperature",
"service_port": 8020
}
3.1.3.2. Project Structure¶
Your service project should have the following structure:
temperature_service/
├── manifest.json
├── temperature_service.py
└── requirements.txt (if needed)
3.1.3.3. Environment Variables¶
Your service will have access to these environment variables when deployed:
APPLICATION_CONTENT_PATH: Directory where your service can write its stateAPPLICATION_STATUS_PATH: Path to write status updatesAPPLICATION_DEPLOYMENT_PATH: Read-only directory containing your deployed service
You can access these in your Python code:
import os
content_path = os.getenv('APPLICATION_CONTENT_PATH')
status_path = os.getenv('APPLICATION_STATUS_PATH')
deployment_path = os.getenv('APPLICATION_DEPLOYMENT_PATH')
3.1.3.4. Deployment Steps¶
Package your service files into a directory
Ensure your manifest.json is properly configured
Use the admin service to deploy:
import xmlrpc.client
admin = xmlrpc.client.ServerProxy("http://localhost:8001/") # Admin service port
admin.deploy_app("path/to/temperature_service")
admin.activate_app("temperature_service-1.0")
admin.start_app("temperature_service-1.0")