How to develop a background function in Python ?

This is an example of executing a function in the background. I was searching for an option to run a function in background along with the normal execution flow.

The main execution will continue in the same flow without waiting for the background function to complete and the function set for background execution will continue its execution in the background.

You can modify this code based on your requirement. Just replace the logic inside function under the @background¬†annotation. Hope this tip helps ūüôā


How to containerize a python flask application ?

Containerization is one of the fast growing and powerful technologies in software Industry. With this technology, user can build, ship and deploy the applications (standalone and distributed) seamlessly. Here are the simple steps to containerize a python flask application.

Step 1:
Develop your flask application. Here for demonstration I am using a very simple flask application. You can use yours and proceed with the remaining steps. If you are new to this technology, I would recommend you to start with this simple program. As usual with all the tutorials, here also I am using a “Hello World” program. Since we are discussing about Docker, we can call it as “Hello Docker”. I will demonstrate the containerization of an advanced application in my next post.

import json
from flask import Flask

app = Flask(__name__)

@app.route("/requestme", methods = ["GET"])
def hello():
    response = {"message":"Hello Docker.!!"}
    return json.dumps(response)

if __name__ == '__main__':"", port=9090, debug=True)

Step 2:
Ensure the project is properly packaged and the dependencies are mentioned in the requirements.txt. A properly packaged project is easy to manage. All the dependent packages are required in the code execution environment. The dependencies will be installed based on the requirements.txt. So prepare the dependency list properly and add it in the requirements.txt file. Since our program is a simple one module application, there is nothing to package much. Here I am keeping the python file and the requirements.txt in a folder named myproject (Not using any package structure)


Step 3:
Create the Dockerfile. The file should be with the name “Dockerfile“. Here I have used python 2 base image. If you use python:3, then python 3 will be the base image. So based on your requirement, you can select the base image.

FROM python:2
ADD myproject /
WORKDIR /myproject
RUN pip install -r requirements.txt
CMD [ "python", "" ]

Ensure you create the Dockerfile without any extension. Docker may not recognize the file with .txt extension.

Step 4:
Build an image using the Dockerfile. Ensure we keep the python project and the Dockerfile in proper locations.
Run the following command from the location where the Dockerfile is kept. The syntax of the command is given below

docker build -t [imagename]:[tag] [location]

The framed command is given below. Here I am executing the build command from the same location as that of the Dockerfile and the project, so I am using ‘dot’ as the location. If the Docker file is located in a different location, you can specify it using the option -f or using –file.

docker build -t myflaskapp:latest .

Step 5:
Run a container from the image

docker run -d -p 9090:9090 --name myfirstapp myflask:latest

Step 6:
Verify the application
List the running containers

docker ps | grep myfirstapp

Now your application is containerized.


Step 7:
Save the docker image locally. The following command will save the docker image as a tar file. You can take this file to any other environment and use it.

docker save myflaskapp > myflaskapp.tar

Save the docker image to Dockerhub also.

In this way you can ship and run your application anywhere.

Common dependencies to install PyCrypto package in CentOS/RHEL

The installation of pycrypto package may fail with errors like

“error: no acceptable C compiler found in $PATH”

“RuntimeError: autoconf error”

“fatal error: Python.h: No such file or directory”

” #include “Python.h”
compilation terminated.
error: command ‘gcc’ failed with exit status 1″

The solution for this issue is to install the following dependent packages.

yum install gcc

yum install gcc-c++

yum install python-devel

pip install pycrypto

Python code to list all the running EC2 instances across all regions in an AWS account

This code snippet will help you to get the list of all running EC2 instances across all regions in an AWS account. I have used python boto3 package for developing the code. This code will dynamically pick up all the aws ec2 regions. So the code will work perfectly without any modification even if a new region gets added to the AWS.

Note: Only the basic api calls just to list the instance details¬†are mentioned in this program . Proper coding convention is not followed . ūüôā

Changing the python version in pyspark

pyspark will pick one version of python from the multiple versions of python installed in the machine. In my case, I have python 3, 2.7 and 2.6 installed in my machine and pyspark was picking python 3 by default. If we have to change the python version used by pyspark, set the following environment variable and run pyspark.

export PYSPARK_PYTHON=python2.6

similarly we can configure any version of python with pyspark. Ensure that python2.6 or whatever you are specifying is available

Programmatic way to reboot EC2 instances

Sometimes we might have to reboot EC2 instances. If the requirement is to restart EC2 instances regularly, we can achieve it by writing a small piece of code. I also came across a similar requirement and a portion of the code I used is given below.


How to hide or obfuscate python source code ?

Sometimes we may have the requirement to provide applications without source code. In Java it is very easy and people are widely using also. If we want to hide our source code in python what we will do ??

I checked for several solutions for obfuscating the source code . One is using pyminifier. This is  a good tool. This will rename the methods and variables. So that the obfuscated code will look more complicated. But still if you spend some time, we can read it.

Another best way to hide the source code completely is by using the built-in compiler in the python itself. This will generate a byte code and we can use that for execution.

python -OO -m py_compile  <your>

This will generate a .pyo file. Rename the .pyo file to .py extension. You can use this for execution. This will work just like the actual code.

NB : If your program imports modules obfuscated like this, then you have to rename them with a .pyc suffix instead