CyberKeeda In Social Media
Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Python Script to create new JIRA tickets using JIRA API

 


Python Script with below JIRA operations

  • Fetch JIRA ticket details using JIRA API.
  • Create JIRA ticket using JIRA API


Information to collect before using script.
  • Get your organization JIRA URL handy with you.
    • Can be retrieved from any JIRA ticket URL, respective URL has FQDN that's the JIRA URL dedicated for your organization.
  • Know your JIRA project/space name.
    • Login to any of your JIRA tickets.
    • From top navigation panel, select projects and check the name associated with the project, project name will be single word without any space.
  • Know JIRA field/mandatory fields within your ticket, before you create a ticket via API.
    • Will know how to fetch details about it from our python script, get_jita_details method can be used to get details for field

Script has one class and two methods, will know how and when to use one by one.
  • JiraHandler ( Class )
  • get_jira_details ( Method ) - Can be used to fetch JIRA ticket details.
  • create_jira_cr_ticket( Method ) - Can be used to create new JIRA ticket. 
Note : 
  • For simplicity, i have used basic authentication method to authenticate to JIRA servers, although for some sort of security instead of using plain text password, have encoded it using base64 authentication.
  • You need to ready with the Payload data json file, before you go ahead and create a new JIRA ticket, this file can be of any name but please content is in JSON format.
        payload_data.json
 

Script.

import requests
import json
import base64
from requests.auth import HTTPBasicAuth

# Inorder to encrypt/decrypt your credentials using base64 module as below.
# To encode --> base64.b64encode(bytes("random", "utf-8"))
# To decode --> base64.b64decode("cmFuZG9t").decode("utf-8")

class JiraHandler:
      
    def __init__(self, username):
        print('Loading Instnace variables...')
        self.username = username
        self.securestring = base64.b64decode("replaceItwithYourCredential").decode("utf-8")
        self.url = "https://jira.yourownjiradomain.com/rest/api/2/issue/"

    def get_jira_details(self,jira_ticket):

        try :
            
            auth = HTTPBasicAuth(self.username, self.securestring)
            get_details_url = self.url + jira_ticket

            headers = {
               "Accept": "application/json"
            }
            
            print("retrieveing", jira_ticket, "details...")
            response = requests.request(
               "GET",
               get_details_url,
               headers=headers,
               auth=auth
            )
            print(json.dumps(json.loads(response.text), sort_keys=True, indent=4, separators=(",", ": ")))
            
        except Exception as e:
            return e



    def create_jira_cr_ticket(self, filename):
        get_details_url = self.url

        auth = HTTPBasicAuth(self.username, self.securestring)

        headers = {
           "Accept": "application/json",
           "Content-Type": "application/json"
        }
        try:
            with open(filename, "r") as re_read_file:
                payload = re_read_file.read()
                print("Creating new JIRA...")
                response = requests.request(
                   "POST",
                   get_details_url,
                   data=payload,
                   headers=headers,
                   auth=auth
                )
                print(json.dumps(json.loads(response.text), sort_keys=True, indent=4, separators=(",", ": ")))
        except Exception as filenotfound:
            print("Can't load file..", filenotfound)



         


How to use it, 
  • Load Instance variable by calling class and provide your JIRA username as an input.
# Initiate Class and load instance variable.
d = JiraHandler("your_JIRA_Username")
  • Call method get_jira_details and add JIRA ticket as method input, for example if we want to get details about a specific JIRA ticket CKPROJ-6162, we must call the method as described below.
# Call below method to get JIRA ticket details.
d.get_jira_details("CKPROJ-6162")
  • Before calling method create_jira_cr_ticket, dump json content within a json file, for instance i have created a file named payload_data.json and it looks somehow like below.
    • Thinking how to find it, use method get_jira_details, it will give you an idea for the field used within your project's jira ticket.
{
        "fields": {
           "project":
           {
              "key": "CKPROJ"
           },
           "summary": "My Dummy Ticket created by REST API",
           "description": "Dummy CR for REST API Test",
           "confluence": "Dummy Confluence Page Link",
           "verification_steps": "Verification Plan",
           "issuetype": {
              "name": "Change Request"
               }
           }
        }
Once you are ready with the payload data, save it within a JSON file and call method providing payload_data.json file as an input to it, as an output script will return the JIRA ticket details.
# Call below method to create new JIRA ticket
d.create_jira_cr_ticket("C:\\Users\\cyberkeeda\\payload_data.json")

Hope this script can have help in any sort, for any help comment please.


Read more ...

How to get yesterday's date using Python timedelta

 

How to use datetime module to get yesterday's date.

All of us use Python's date time library for multiple date/time task, there is an additional function named as timedelta that can be used to get previous date as per requested varaible.

Let's go through it :)

Script to extract yesterday date

# Python script to get yesterday date.
from datetime import date, timedelta # Block to get present day data today = date.today() print("Today's date : ", today.strftime('%Y-%m-%d')) # Block to get yesterday data yesterday = today - timedelta(days = 1) print("Yesterday's date : ", yesterday.strftime('%Y-%m-%d'))

Output


Today's date : 2021-06-29
  Yesterday's date : 2021-06-28


Same way, we can change the timedelta to n number of day ( day = n )
Below, we will extract the 4 days old date


Script to extract yesterday date

# Python script to get yesterday date.
from datetime import date, timedelta # Block to get present day data today = date.today() print("Today's date : ", today.strftime('%Y-%m-%d')) # Block to get yesterday data yesterday = today - timedelta(days = 4) print("Yesterday's date : ", yesterday.strftime('%Y-%m-%d'))

Output


Today's date : 2021-06-29
  Yesterday's date : 2021-06-25


Read more ...

How to use, Python's DateTime Module

 


Python's Date Time Module:
    Python's datetime module ships with default python package which you can't skip for sure sooner or later you will come to know about it.
This module will help you to verify multiple checks and algorithms based upon date time filter.

I will keep on updating the post as per my learnings and used in practical scenarios.
Let's go through it :)

Basic Usage of date time
  • Import module and display current date.

Syntax
# Import datetime function from datetime library
from datetime import datetime
datetime.datetime(2021, 6, 7, 2, 43, 32, 276412)

# Create object and store value##
  dt = datetime.now()
# Display date, time without Formatting
print(dt)

Output:

datetime.datetime(2021, 6, 7, 2, 43, 32, 276412)


Filter datetime output as per our requirement.
  • Filter date

Syntax
# dt = datetime.now()
# show_date = dt.date()

# print (show_date)

Output:

datetime.date(2021, 6, 7)

Filter only Day

# dt = datetime.now()
# show_day = dt.day

# print (show_day)

Output:

7

  • Filter Month

Syntax
# dt = datetime.now()
# show_month = dt.month

# print (show_month)

Output:

6

Use datetime strftime to format date/time as per our need

    Below are some identifier to use while formatting.
    • %a  : Day of week (Short )
      • Mon, Tue, Wed, ... Sat, Sun
    • %A : Day of week (Full )
      • Monday, Tuesday, Wednesday .. Saturday, Sunday
    • %m : Month  ( Two digit number )
      • 01,02,03,04 .... 10,11,12
    • %y : Year ( Short, Two digit number )
      • 19,20,21
    • %Y : Year ( Full)
      • 2019,2020,2021
    • %d : Date ( Two digit number )
      • 01,02,03,04, 22,23,30,31

    Use Strftime as per our need.
    • With or Without Variables


    Syntax
    # dt = datetime.now()
    # show_val1 = dt.strftime('%m%d%y')
    # show_val2 = dt.strftime('%m%d%Y')
    # show_val3 = dt.strftime('%Y%m%d')
    # show_val4 = dt.strftime('%a %m %y')
    # show_val5 = dt.strftime('%A-%m-%Y')
    # show_val6 = dt.strftime('%I %p %S')
    # show_val7 = dt.strftime('%-j')
    # show_val8 = dt.strftime('myprefix-%m%d%y-mysuffix')

    # print (show_val1)
    # print (show_val2)
    # print (show_val3)
    # print (show_val4)
    # print (show_val5)
    # print (show_val6)
    # print (show_val7)

    Output:

    060721
    06072021
    20210607
    Mon 06 21
    Monday-06-2021
    02 AM 32
    158
    myprefix-060721-mysuffix


    There is lot of content with respect to datetime module, will keep this post updated ;)
    Read more ...

    Python : Selenium and Chromedriver to take webpage screenshot and send it via email.




    Browser Automation using Python


    Within this post, we will cover.

    • Use of selenium and chromedriver to take screenshot of most recent webpage status.
    • Will leverage the basic preinstalled libraries to send email.
    • Will know, how we can send an image as a part of email body not as an attachment.
    • Will use the headless mode option of chromdriver, that's is the entire operation will run in background no GUI chrome events will be observed.

    We will start with the use case:

    • if you have a requirement to check the current status of a webpage multiple times within a day/hour.
    • If you have multiple of webpages to look into periodically without opening any of it, check status of directly from your inbox only.
    We will use a python script here and perform the below operations sequentially.
    1. Take screenshot of webpage using Python selenium library and google chrome webdriver and save it in our folder by name screenshot.png
    2. Use Python base library email and use it's multipart function to draft image as an email body.
    3. Use Python base library to send email using SMTP server.
    Steps:
    • Download mandatory requirements.
      • Install selenium library from PIP
    C:\Users\cyberkeeda> pip install selenium
    First confirm which chrome browser you have on your system, for this open Chrome Browser --> Click on 3 dots at the top right corner of chrome --> Help
    --> About Chrome Chrome --> You will get google chrome version.
    • Create an new directory and place your above chrome webdriver into it.
    • Note your organizations SMTP server URL/IP.
    • Create a new Python file and paste the below script lines within it.
    • Paste and save your python script and replace the below lines with yours.
      • driverPath  : Replace it with the path you have kept your downloaded chromedriver 
      • chrome_options.add_argument('window-size=1920,1080')  : Replace it with resolution what you want for the screenshot.
        • 720p = 1280 x 720 - is usually known as HD or "HD Ready" resolution
        • 1080p = 1920 x 1080 - is usually known as FHD or "Full HD" resolution
        • 1440p = 2560 x 1440 - is commonly known as QHD or Quad HD resolution
      • driver.get('https://www.mohfw.gov.in/'): Replace it your URL.
      • sendFrom : Replace it your sender's email address.
      • sentTo: Replace it your recipient email address. ( You can use same email for sendFrom and sendTo)
      • smtp = smtplib.SMTP('smtp.cyberkeeda.com') : Replace it your own smtp server or IP.


    import smtplib
    from email.mime.text import MIMEText
    from email.mime.image import MIMEImage
    from email.mime.multipart import MIMEMultipart
    from selenium.webdriver.chrome.options import Options
    from selenium import webdriver
    from time import sleep

    def grab_screenshot():

        # Path for your downloaded chromedriver.
        driverPath = '\\Users\\cyberkeeda\\BrowserAutomation\\chromedriver'

        # To activate GUI Mode Uncomment te below two lines
        # And comment the below four lines staring from chrome_options to driver

        #driver = webdriver.Chrome(executable_path=driverPath)
        #driver = webdriver.Chrome(driverPath)
        
        chrome_options = Options()
        chrome_options.add_argument("headless")
        chrome_options.add_argument("--start-maximized")
        chrome_options.add_argument('window-size=1920,1080')
        driver = webdriver.Chrome(options=chrome_options, executable_path=driverPath)

        driver.get('https://www.mohfw.gov.in/')
        sleep(15)
        driver.get_screenshot_as_file("screenshot.png")
        driver.close()
        driver.quit()

    def emailScreenShot():

        grab_screenshot()

        html_string = """ 
                        '<b>Covid-19 Cases </b> <br> 
                        Do and Don't Link :https://www.mohfw.gov.in/pdf/socialdistancingEnglish.pdf <br>
                        <img src="cid:image1"><br>Regards <br> Automation
                      """

        sendFrom = 'Covid Update <dontreply-covid@cyberkeeda.com>'
        sendTo = 'admin@cyberkeeda.com'
        # Create the root message and fill in the from, to, and subject headers
        msgRoot = MIMEMultipart('related')
        msgRoot['Subject'] = 'Covid-19 Cases Status'
        msgRoot['From'] = strFrom
        msgRoot['To'] = strTo

        # Encapsulate the plain and HTML versions of the message body in an
        # 'alternative' part, so message agents can decide which they want to display.
        msgAlternative = MIMEMultipart('alternative')
        msgRoot.attach(msgAlternative)

        msgText = MIMEText('This is the alternative plain text message.')
        msgAlternative.attach(msgText)

        # We reference the image in the IMG SRC attribute by the ID we give it below
        msgText = MIMEText(html_string, 'html')
        msgAlternative.attach(msgText)

        # This example assumes the image is in the current directory
        fp = open('screenshot.png''rb')
        msgImage = MIMEImage(fp.read())
        fp.close()

        # Define the image's ID as referenced above
        msgImage.add_header('Content-ID''<image1>')
        msgRoot.attach(msgImage)

        # Send the email (this example assumes SMTP authentication is required)
        try:
            smtp = smtplib.SMTP('smtp.cyberkeeda.com')
            smtp.sendmail(sendFrom, sendTo, msgRoot.as_string())
            smtp.quit()
        except:
            print("SMTP Error")

    emailScreenShot()



    Hope this blog post helps you to meet your requirement, in case of any support using above script do comment.
     

    Read more ...

    Python : How to extract desired cell values from a table created by module PrettyTable


    PrettyTable

    It is simple Python library designed to make it quick and easy to represent tabular data in visually appealing ASCII tables. It was inspired by the ASCII tables used in the PostgreSQL shell psql. PrettyTable allows for selection of which columns are to be printed, independent alignment of columns (left or right justified or centred) and printing of “sub-tables” by specifying a row range.

    Official Document : Link

    There could be many uses cases while using it, here in this blog post we will cover how we can extract our desired cell values from preetyTable.

    So we will start by 
    • Importing module
    • Creating object
    • Add Feilds
    • Add Data
    from prettytable import PrettyTable           # importing module

    tabular_table = PrettyTable()                 # creating object
    tabular_fields = ["Name""Age""Gender"]    # Define Field List

    tabular_table.field_names = tabular_fields    # Add Fields to table

    tabular_table.add_row(["Tokyo""33""M"])   # Add Data
    tabular_table.add_row(["Narobi""74""M"])
    tabular_table.add_row(["Denver""21""F"])

    print(tabular_table)

    Output.
    +--------+-----+--------+
    |  Name  | Age | Gender |
    +--------+-----+--------+
    | Tokyo  |  33 |   M    |
    | Narobi |  74 |   M    |
    | Denver |  21 |   F    |
    +--------+-----+--------+


    Use Case 1.

    • Extract cell values for a specific field only from prettyTable
    Below For loop will help to do so.


    for row in tabular_table:
         print (row.get_string(fields=["Name"]))


    Output.
    +-------+
    |  Name |
    +-------+
    | Tokyo |
    +-------+
    +--------+
    |  Name  |
    +--------+
    | Narobi |
    +--------+
    +--------+
    |  Name  |
    +--------+
    | Denver |
    +--------+


    Use Case 2.

    • Extract cell values without header or border from prettyTable

    for row in tabular_table:
         row.border = False
         row.header = False
         print (row.get_string(fields=["Name"]).strip())

    Output.
    Tokyo
    Narobi
    Denver
    Read more ...

    How to Upload your Django bundled package to PyPI using twine

    Within our last django post, i have demonstrated how we can bundle/package our app into tar.gz format and how we can install it locally.


    In case you are not aware, go through the post link.
    Within this blog post, we will know cover, how we can upload our django app bundled package into PYPI.
    • Once you have successfully created an account, let's install an additional python package named as twine, open command prompt/terminal and run the below command.
    # pip install twine
    • Toggle down to your bundled home directory where you have your bundled tar.gz package under dist folder and run the following command.
    # twine check dist/*
    Note : PyPI uses your README.rst for to make it's README, descrptions and all other sections under your python package as a part of documentation.
    Most of the errors comes while reading your README.rst file from twine as it fails to meet the requirement the formatting required to upload on twine.

    In case it gives error, fix the error and try making new bundled package and do run "twine check" to verify if it has been fixed or not.

    In order to recreate bundled package, delete old directories (dist and egg-info) and rerun previous command to rebundle it.

    # python setup.py sdist
    One all errors are fixed, we are ready to upload it on PyPi website, use the below command to upload your package.
    # twine upload dist/*
    It will ask for your credentials, use the same newly created PYPI account credentials to upload it under your username.
    Upon successful upload, we can check our PyPi account, package will be uploaded with formatted description mentioned within our README.rst file.

    Our django-filesnow screenshot looks like below screenshot.


    Read more ...
    Designed By Jackuna