Saturday 30 January 2021

Python Flask REST API Tutorial

Python Flask REST API Tutorial

I am sharing my Python code to create simple REST API. I have used Python's lightweight framework Flask is used to create simple REST API. Flask Restful is an extension of Flask. This code may helpful for some beginner Python developer. 


from flask import Flask
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

class HelloWorld(Resource):
    def get(self):
        return {'hello': 'world'}

api.add_resource(HelloWorld, '/')

if __name__ == '__main__':
    app.run(debug=True)

Print CSV Content in Python Tutorial

Print CSV Content in Python Tutorial

As CSV is most common file to import and export data on web applications. So we may need to use this feature in almost our most of the apps. So I am sharing my small Python code to print CSV data into an array. May this code is helpful for someone.

We need CSV module of Python for this code to run. We used CSV module `reader` function to read CSV content in Python.

import csv

results = []
with open('test.csv', newline='') as csvfile:
    reader = csv.reader(csvfile, delimiter=' ', quotechar='|')
    for row in reader:
        results.append(row)
print("CSV data: ", results)



More details on CSV module of Python, please follow below URL:

https://docs.python.org/3/library/csv.html

Python Basics

Python Basics 

 Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming.

Python is an interpreted language, which can save you considerable time during program development because no compilation and linking is necessary.

Python is extensible: with C/C++/Java code, and easily embeddable in applications.

Some Python modules are also useful as scripts.

Python source files are treated as encoded in UTF-8.

Start the interpreter and wait for the primary prompt, >>>.

The interpreter acts as a simple calculator. The operators +, -, * and / work just like in most other languages.

Python can also manipulate strings.  They can be enclosed in single quotes (‘) or double quotes (“). 

Simple print command in Python.

print("Hello world")

Math Commands acts like a calculator.

>>> 2 + 2
4

>>> 17 / 3  # classic division returns a float
5.666666666666667

>>> 5 * 3 + 2  # result * divisor + remainder
17

>>> width = 20
>>> height = 5 * 9
>>> width * height
900

If Statement in Python: Below example is asking to input integer value. isdigit() function is checking if provided value in of type int.
Try Except statements are used for catching any exception. It protects any exception if we don't enter any
input.

try:
    x = int(input("Please enter number: "))
    if x.isdigit():
        if x <= 0:
            x = 0
            print('Printing 0 value')
        elif x < 10:
            print('Printing ' + str(x))
        else:
            print('Value is very big')
except:
    print("Please enter valid input")


For Loop Below example printing hexa code of colors by their name in Python.

Install colour package of Python
pip install colour
Ref: https://pypi.org/project/colour/
Converts and manipulates common color representation (RGB, HSL, web, …)
from colour import Color
colors = ['red', 'green', 'white', 'blue']
for c in colors:
    n = Color(c)
    print(c, n.hex)


Fibonacci Series in Python as follows:
# Fibonacci series:
# the sum of two elements defines the next
a, b = 0, 1
while a < 10:
    print(a)
    a, b = b, a+b

For loop in Python:

a = 0 b = [] for a in range(0, 10): b.append(4 + ((a - 1) * 3)) s = ',' . join(str(c) for c in b) print(s) // print array elements in string


Function in Python:
def parrot(a, b, c):
print(a,b,c)

d = {"a": "this", "b": " is my ", "c": "test"}
parrot(**d)

Saturday 9 January 2021

AWS X-ray Send Traces Lumen

AWS X-ray Test Script in PHP Framework Lumen


I have tested sending traces to AWS X-Ray through API Gateway through Lumen.

I have used below PHP package:

https://packagist.org/packages/pkerrigan/xray

<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Support\Response;
use Pkerrigan\Xray\Trace;
use Pkerrigan\Xray\Submission\DaemonSegmentSubmitter;
use Pkerrigan\Xray\Segment;

class TestController extends Controller
{
    /**
     * construct
     */
    public function __construct(Response $response) {
        $this->response = $response;
    }

    /**
     * test xray
     */
    public function xray() {    
      try {  
        if(env('ENABLE_XRAY')) {

              //echo "----Tracing Start 14 ----";

              Trace::getInstance()
                ->setTraceHeader($_SERVER['HTTP_X_AMZN_TRACE_ID'] ?? null)
                ->setName('api-1')
                ->setUrl("[API-1-URL]")
                ->setMethod('GET')
                ->begin();

              Trace::getInstance()
                ->setTraceHeader($_SERVER['HTTP_X_AMZN_TRACE_ID'] ?? null)
                ->setName('api-2')
                ->setUrl("[API-2-URL]")
                ->setMethod('GET')
                ->begin();
                
              Trace::getInstance()
                ->setTraceHeader($_SERVER['HTTP_X_AMZN_TRACE_ID'] ?? null)
                ->setName('api-3')
                ->setUrl("[API-3-URL]")
                ->setMethod('GET')
                ->begin();    
                  
              Trace::getInstance()
              ->getCurrentSegment()
              ->end()
              ->setResponseCode(http_response_code())
              ->submit(new DaemonSegmentSubmitter());
              return $this->response->success(array('xray-res' => 'success'));
          } else {
            return $this->response->success(array('xray-res' => 'no-set'));
          }
        } catch(Exception $e) {
          return $this->response->success(array('xray-res' => $e->getMessage()));
        }
    }
}

Create .ICS file using PHP code

Recently worked on creating a .ics file in PHP after a very long time, code so thought to share with everybody. Please find below the comple...