Python Libraries | Python for DevOps | Part 3

Python Libraries | Python for DevOps | Part 3

·

4 min read

Python is a versatile programming language with an extensive collection of libraries that make it easier to develop various applications, from web development to data analysis, and more. In this blog post, we will introduce some popular Python libraries that can be useful for different types of projects.

There are some third-party libraries like NumPy, Pandas, matplotlib, Scikit-learn, Flask, Django, etc.

To know more about Python Data Types and Data Structures, I have written a blog: Python DataTypes & DataStructures.

Python In-Built Libraries

Python has a wide range of built-in libraries that provide developers with a variety of functionalities to help solve complex programming problems. Some of them are os, sys, datetime, re, math, random, json, yaml, etc.

A good DevOps engineer should know which library needs to be used for a particular action. Because as a DevOps Engineer, you should be able to parse files, be it Txt, json, yaml, etc.

JSON File

JSON stands for "JavaScript Object Notation", but it's not limited to just JavaScript and can be used in many programming languages. A JSON file is a file format used for storing and exchanging data.

JSON files are composed of key-value pairs, where the keys are strings and the values can be strings, numbers, arrays, objects, booleans, or null.

Usage: JSON is often used to transfer data between web applications and servers as it is lightweight, easy to read and write, and can be parsed by most programming languages.

Extension: .json

Example of a JSON file:

{
  "name": "Sneha K S",
  "age": 23,
  "email": "sneha.ks@gmail.com",
}

YAML File

YAML stands for "YAML Ain't Markup Language" which uses indentation to represent data hierarchies and is designed to be easy to read and write by humans.

Like JSON, YAML is a key-value-based format, but it has a more relaxed syntax and can handle more complex data structures, including lists and nested objects.

Usage: YAML file is used for configuration files and data exchange between different programming languages.

Extension: .yaml or .yml

Example of a YAML File:

name: Sneha K S
age: 23
email: sneha.ks@gmail.com

Tasks

Task 1: Create a Dictionary in Python and write it to a JSON File.

Create a Dictionary named "person" and import the json library.

person = {
    "name": "Sneha",
    "age": 23,
    "email": "sneha.ks@gmail.com",
    "address": {
        "street": "1",
        "city": "Bangalore",
        "state": "Karnataka",
        "zip": "560098"
    },
    "interests": ["DevOps", "Cricket", "Bikes"]
}
import json

with open('person.json','w') as f:
    json.dump(person,f)

json.dump() is a function provided by the built-in json module in Python that is used to write a Python object to a JSON file.

After running this code, a new file named "person.json" will be created in the same directory as the Python script, containing the contents of the person dictionary in JSON format.

Task 2: Read a json file services.json kept in the Day 15 Task of 90 Days of DevOps Github repo and print the service names of every cloud service provider.

First, we import the JSON module. Then we read the data into the services.json file.

We then use json.loads()to parse the JSON string and convert it to a Python object called data. We can then access the value of the "services" key by calling data["services"] and storing it in the variable list.

The code for the above task is:

import json
>>> services = {
...     "services": {
...       "debug": "on",
...       "aws": {
...         "name": "EC2",
...         "type": "pay per hour",
...         "instances": 500,
...         "count": 500
...       },
...       "azure": {
...         "name": "VM",
...         "type": "pay per hour",
...         "instances": 500,
...         "count": 500
...       },
...       "gcp": {
...         "name": "Compute Engine",
...         "type": "pay per hour",
...         "instances": 500,
...         "count": 500
...       }
...     }
...   }
>>> json_obj = json.dumps(services)
>>> with open("services.json","w") as f:
...     json.dump(services, f)
...
>>> file = open("services.json","r")
>>> data = json.loads(file.read())
>>> list = data['services']
>>> print("\naws :", list['aws'].get('name'))

aws : EC2
>>> print("azure :", list['aws'].get('name'))
azure : EC2
>>> print("gcp :", list['aws'].get('name'))
gcp : EC2
>>>

Task 3: Read the YAML file using Python, file services.yaml and read the contents to convert yaml to json.

The YAML file is opened using the open() function and load its contents using the yaml.safe_load() function. The json.dumps() function is used to convert the YAML data to a JSON string, which is then printed on the console.

>>> import yaml
>>> import json
>>> with open("services.yaml", "r") as F:
...     yaml_contents = yaml.safe_load(F)
>>> json.contents = json.dumps(yaml_contents)
>>> print(json.contents)


Well, this was it for this blog. Until then, keep reading my blogs and connect with me on LinkedIn and let's have a conversation.

To help me improve my blog and correct my mistakes, I am available on LinkedIn as Sneha K S. Do reach me and I am open to suggestions and corrections.

#Day15 #90DaysofDevops

Did you find this article valuable?

Support Sneha K S by becoming a sponsor. Any amount is appreciated!