Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Friday, 12 March 2021

PDF file generation from HTML file in Python

PDF Generation from HTML File in Python






I am sharing my script to generate PDF file from HTML file in Python using PDFKit module.

Install Python PDF-Kit

$ pip install pdfkit

Some Simple Examples:
import pdfkit

pdfkit.from_url('http://testpage.com', 'out.pdf')
pdfkit.from_file('test.html', 'out.pdf')
pdfkit.from_string('Hello!', 'out.pdf')

My Sample Script to generate PDF from HTML page.

 import os

import sys
from flask import Flask,request
import pdfkit
from flask import make_response
import logging.config
app = Flask(__name__)
from decouple import config

# Logger and handlers
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'console': {
            'format': '%(levelname)-1s%(asctime)s [%(name)-12s.%(funcName)s.%(lineno)s%(message)s',
        },
        'file': {
            'format': '%(levelname)-1s%(asctime)s [%(name)-12s.%(funcName)s.%(lineno)s%(message)s',
        },
    },
    'handlers': {
        'console': {
            'level': "DEBUG",
            'class': 'logging.StreamHandler',
            'formatter': 'console',
            'stream': sys.stdout
        },
        'file': {
            'level': "DEBUG",
            'class': 'logging.handlers.RotatingFileHandler',
            'formatter': 'file',
            'filename': 'htmltopdf.log',
        },
    },
    'loggers': {
        '': {
            'handlers': ['file'],
            'level': "DEBUG",
            'propagate': True
        },
    }
}

logging.config.dictConfig(LOGGING)
LOGGER = logging.getLogger(__name__)


@app.route("/")
# Function for html to pdf convertor
def function_html_to_pdf_convertor():
    try:
        logging.debug("calling func")
        html_file = request.args.get('f', default="", type=str)
        if html_file:
            html_file = '{}{}'.format(html_file,'.html')
            filepath = os.path.join(app.static_folder, html_file)
            filename = os.path.splitext(os.path.basename(filepath))[0]
            css = "static/style.css"
            options = {
                'page-size': 'Letter',
                'encoding': "UTF-8",
                'zoom': 1.80,
                'footer-center': 'Page [page]/[topage]',
                'footer-font-size': 8
            }
            if os.path.isfile(filepath):
                #pdf = pdfkit.from_file(filepath, css=css)
                pdf = pdfkit.from_file(filepath, False,options=options, css=css)
                response = make_response(pdf)
                response.headers.set('Content-Disposition', 'attachment', filename=filename + '.pdf')
                response.headers.set('Content-Type', 'application/pdf')
                return response
            else:
                logging.debug("File not found")
                return {
                    "status": 404,
                    "message": 'File not found'
        }
        logging.debug("'Please provide file'")
        return{
            "status": 400,
            "message": 'Please provide file'
        }

    except Exception as e:
        logging.debug("Bad request {}".format(e))
        return {
            "status": 400,
            "error": '{}'.format(e)
        }
# main function
if __name__ == "__main__":
    app.run()

Monday, 8 February 2021

AWS Cognito SSO Integration with Python

AWS Cognito SSO Integration with Python

AWS SSO Cognito OAuth2.0 implementation as per below URL:

https://aws.amazon.com/blogs/mobile/understanding-amazon-cognito-user-pool-oauth-2-0-grants/

First we need to create code, get Client ID and Client Secret. Run below URL:

https://AUTH_DOMAIN/login?client_id=XXXXXXXXXX&response_type=code&scope=email+openid&redirect_uri=http://localhost/test/sso_check

Above URL will return to redirect url with code in query string.

Note: Code is valid for one time transaction only.

Get Access Token using the Code as per below description:



Make below request:





this will return below response:

{
    "id_token": "eyJraWQiOiJJNGs2UXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    "access_token": "eyJraWQiOiJENllqdXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    "refresh_token": "eyJjdHkiOiJKV1QiLCJlbmXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    "expires_in": 3600,
    "token_type": "Bearer"
}


From above response we need to use id_token to get user information:

  • id_token – A valid user pool ID token. Note that an ID token is only provided if the openid scope was requested.
Below is the Python code Github URL to get user information by validating JWT token returned in id_token key.






Below is the response from above Python code:



Saturday, 30 January 2021

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)

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...