0% found this document useful (0 votes)
8 views4 pages

Ecinetwireless Backend Code Bulk

This document outlines a Flask application that provides APIs for loading airtime to mobile numbers using the Econet XML-RPC API. It includes validation for MSISDN formats, error handling, and bulk loading functionality from Excel files. The application also logs errors and validates required fields for API requests.

Uploaded by

emeliamakore
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views4 pages

Ecinetwireless Backend Code Bulk

This document outlines a Flask application that provides APIs for loading airtime to mobile numbers using the Econet XML-RPC API. It includes validation for MSISDN formats, error handling, and bulk loading functionality from Excel files. The application also logs errors and validates required fields for API requests.

Uploaded by

emeliamakore
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

from flask import Flask, request, jsonify

import xmlrpc.client
import xmltodict
import os
import logging
import re
import pandas as pd

# Initialize Flask app


app = Flask(__name__)

# Configure logging
logging.basicConfig(level=logging.DEBUG)

# Load environment variables


ECONET_USERNAME = os.environ.get("ECONET_USERNAME")
ECONET_PASSWORD = os.environ.get("ECONET_PASSWORD")
ECONET_API_URL = os.environ.get("ECONET_API_URL",
"https://your_econet_api_url/xmlrpc")

# Validate environment variables


if not ECONET_USERNAME or not ECONET_PASSWORD:
raise ValueError("Econet username and password must be set as environment
variables.")
if not ECONET_API_URL or ECONET_API_URL == "https://your_econet_api_url/xmlrpc":
raise ValueError("ECONET_API_URL must be set to a valid endpoint.")

# Helper function to validate MSISDN format (basic validation)


def validate_msisdn_format(msisdn):
pattern = r"^\+?1?\d{9,15}$" # Adjust pattern as per the MSISDN format
return re.match(pattern, msisdn)

# Common function to handle API request and response validation


def common_api_request(method_name, api_params, required_fields):
"""Handles API request and validates response structure."""
response = call_econet_api(method_name, api_params)
if validate_response(response, required_fields):
return jsonify(response), 200
return jsonify({"error": "Invalid response structure from Econet API"}), 500

def call_econet_api(method_name, params):


"""Calls the Econet XML-RPC API."""
try:
server = xmlrpc.client.ServerProxy(ECONET_API_URL)
api_params = [ECONET_USERNAME, ECONET_PASSWORD]
api_params.append(params)
result = getattr(server, method_name)(*api_params)

if isinstance(result, str):
# Use xmltodict for simplified XML parsing
try:
response_data = xmltodict.parse(result)
return response_data
except Exception as e:
logging.error(f"Failed to parse XML: {e}")
return None
else:
logging.error(f"Unexpected response from Econet API: {result}")
return None
except xmlrpc.client.Fault as e:
logging.error(f"XML-RPC Fault: {e}")
return None
except Exception as e:
logging.error(f"An error occurred: {e}")
return None

def validate_response(response, required_fields):


"""Validates that the response contains the required fields."""
if not response:
return False
for field in required_fields:
if field not in response:
return False
return True

@app.route("/api/airtime/load", methods=["POST"])
def load_airtime():
"""Loads airtime to a specified MSISDN."""
data = request.get_json()
msisdn = data.get("msisdn")
amount = data.get("amount")
reference = data.get("reference")
currency = data.get("currency", 840) # Default to USD (840) if not provided

# Validate required fields


if not msisdn or not amount or not reference:
return jsonify({"error": "Missing msisdn, amount, or reference"}), 400

# Validate MSISDN format


if not validate_msisdn_format(msisdn):
return jsonify({"error": "Invalid MSISDN format"}), 400

# Validate amount and currency


try:
amount = int(amount)
currency = int(currency)
except ValueError:
return jsonify({"error": "Amount and Currency must be valid integers"}),
400

api_params = {
"MSISDN": str(msisdn),
"Amount": amount,
"Reference": str(reference),
"Currency": currency # Defaults to 840 (USD)
}

return common_api_request("load_value", api_params, ["Status", "StatusCode",


"Description"])

@app.route("/api/airtime/bulk/load", methods=["POST"])
def bulk_load_airtime():
"""Handles bulk airtime loading from an Excel file containing multiple
MSISDNs."""
if "file" not in request.files:
return jsonify({"error": "No file part"}), 400
file = request.files["file"]

if file.filename == "":
return jsonify({"error": "No selected file"}), 400

try:
# Read the Excel file using pandas
df = pd.read_excel(file)

# Check if the required column 'MSISDN' exists


if "MSISDN" not in df.columns:
return jsonify({"error": "Excel file must contain 'MSISDN' column"}),
400

# Extract MSISDNs and validate format


msisdns = df["MSISDN"].tolist()
invalid_msisdns = [msisdn for msisdn in msisdns if not
validate_msisdn_format(str(msisdn))]

if invalid_msisdns:
return jsonify({"error": f"Invalid MSISDN formats: {',
'.join(invalid_msisdns)}"}), 400

# Process each MSISDN and load airtime


results = []
amount = request.form.get("amount")
reference = request.form.get("reference")
currency = request.form.get("currency", 840)

for msisdn in msisdns:


api_params = {
"MSISDN": str(msisdn),
"Amount": int(amount),
"Reference": str(reference),
"Currency": int(currency)
}

response = call_econet_api("load_value", api_params)


if validate_response(response, ["Status", "StatusCode",
"Description"]):
results.append({
"msisdn": msisdn,
"status": "success",
"statusCode": response["StatusCode"],
"description": response["Description"]
})
else:
results.append({
"msisdn": msisdn,
"status": "error",
"message": "Failed to load airtime"
})

return jsonify({"results": results}), 200

except Exception as e:
logging.error(f"Error processing bulk airtime load: {e}")
return jsonify({"error": "An error occurred while processing the bulk
load"}), 500
if __name__ == "__main__":
app.run(debug=True)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy