Python's Articles

Python is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991. Python's design philosophy emphasizes code readability with its notable use of significant whitespace.

Create REST API using Django Rest Framework
There are multiple ways to indite an API in Django, but I don't optate you confound them. I will show you the two best ways to implement APIs, which will cover virtually all the scenarios. Both ways are homogeneous to each other. They are: APIView ModelViewSet APIView is more generic, while ModelViewSet is categorical to a Model's CRUD operations (i.e. ModelViewSet is utilized to perform List, Engender, Read, Update, Expunge (CRUD ) operations only.) Whereas with APIView, you can implement not only CRUD operations but additionally other Non-CRUD functionalities like authenticate, logout, engender invoice, download invoice, change fields of multiple models, etc. You must be cerebrating, "with APIView we can implement so much, why to learn ModelViewSet?" Well, you will decipher the reason very anon after implementing them both. Let's commence with APIView first. Prerequisite Create a Django project and application using the following steps. # Install django in your system from command prompt pip install django # Create Project django-admin startproject DemoProject # Create Application inside the Project cd DemoProject django-admin startapp DemoApplication # Add DemoApplication in > INSTALL_APPS list INSTALLED_APPS = [ ... 'DemoApplication', ] Install Django Rest Framework # Install django rest framework from command prompt install djangorestframework # Add rest_framework application in > INSTALLED_APPS list INSTALLED_APPS = [ ... 'rest_framework', ] Now, we are ready with the Django Rest Framework setup. Let's create our first API using APIView. APIView With APIView, we can implement Get, Post, Delete, Patch, Put methods. Let's create a Book data model and implement CRUD functionality on it. Edit the file -  DemoProject > DemoApplication > and create a model. (Django will create a new SQL table in Database.) class Book(models.Model): id=models.IntegerField(primary_key=True) title=models.CharField(max_length=200) author=models.CharField(max_length=200) Edit the file - DemoProject > DemoApplication > from rest_framework.views import APIView from rest_framework.response import Response from .models import * from .serializers import * from rest_framework import viewsets # Create your views here. class BookApiView(APIView): def get(self,request): allBooks=Book.objects.all().values() return Response({"Message":"List of Books", "Book List":allBooks}) def post(self,request): Book.objects.create(["id"], title=["title"], author=["author"] ) book=Book.objects.all().filter(["id"]).values() return Response({"Message":"New Book Added!", "Book":book}) Edit the file - DemoProject > from django.contrib import admin from django.urls import path from django.conf.urls import url from ApiApplication import views urlpatterns = [ path('admin/',, url("book/",views.BookApiView.as_view()), #new ] Now, Migrate and run the project. python makemigrations python migrate python runserver Open from your browser. Voila! Your first API has created.  Now Imagine, We have 10 data models (tables in database) and we have to create 10 such APIS and also implement CRUD functionality for the same. Isn't that a redundant task?  To avoid repetitive code, Django has ModelViewSet where you can save 1000 of such lines. ModelViewSet Edit the file -  DemoProject > DemoApplication > and create a new data model. class Student(models.Model): id=models.IntegerField(primary_key=True) first_name=models.CharField(max_length=20) last_name=models.CharField(max_length=20,null=True,blank=True) dob=models.DateField(null=True,blank=True) Create a new file  -  DemoProject > DemoApplication > from rest_framework import serializers from .models import * class StudentSerializer(serializers.ModelSerializer): class Meta: model=Student fields = "__all__" Edit the file -  DemoProject > DemoApplication > class StudentViewSet(viewsets.ModelViewSet): queryset = Student.objects.all() serializer_class=StudentSerializer Edit the file - DemoProject > from django.conf.urls import url from ApiApplication import views from rest_framework import routers from django.urls import include router = routers.DefaultRouter() router.register('student',views.StudentViewSet) urlpatterns = [ path('admin/',, path('',include(router.urls)) ] Now run the server and open from your browser. i hope you like this article.
GET and POST requests using Python requests module
Requests is open-source library to send http requests in Python. Though there is Python's built-in library, urllib2 but it lacks many capacities you need. Requests provide simple and easy way to create HTTP or API requests. With requests, you can send most common HTTP requests, add headers and data, create authenticate requests etc. In this article, we will install Python's requests module and create different requests with example. So let's start! Install requests module First install the requests library with Python pip package. pip install requests Once requests library is installed, you can import and use it. Create request First import the requests library in the begining. import requests Here is the simple Get request. response_data = requests.get('') response_data variable stores all the response information from the request. You can also make Post request with data. response_data ='', data = {'key': 'value' }) This way you can send all type of request. response_data = requests.put('', data = {'key': 'value'}) response_data = requests.delete('') response_data = requests.options('') Sometimes you may want to send get request with query string. This is how you can send get request with query string. data = {'key': 'value', 'new_key': 'new_value'} response_data = requests.get('', params = data) If you want to pass header with request, then pass like this. headers = {'Content-Type': 'Application/Json'} response_data = requests.get('', headers = headers) If route is protected with authentication, then you can also add auth. response_data ='', data = {'key': 'value' }, auth = ('username', 'password')) You can set time to stop request for wait. response_data = requests.get('', timeout = 5) Of course, you can also pass image in request payload. url = '' file = {'file': open('document.pdf', 'rb')} response_data =, files=file) response_data.text Getting response After creating request you want to handle response data and response header. Here is how to get and handle data. We can check the response status code with status_code. response_data = requests.get('') http_status_code = response_data.status_code You can also check response header. response_header = response_data,headers This will return all headers in dictionary format. {     'content-encoding': 'gzip',     'transfer-encoding': 'chunked',     'connection': 'close',     'server': 'nginx/1.0.4',     'x-runtime': '148ms',     'etag': '"e1ca502697e5c9317743dc078f67693f"',     'content-type': 'application/json' } You can also get specific header: content_header = response_header.headers['Content-Type'] 'application/json' content_header = response_header.headers.get('content-type') 'application/json' If a response contains some Cookies, you can get cookies this way. response_data = requests.get('') response_data.cookies['example_cookie_name'] You have just learned to make basic HTTP requests. In the next article, we will discuss in details.
How to Create virtual environment in Python3
Python virtual environment is tool that keeps every package in solated from system. This tool is required when you are working on different project on same machine. This will help to install same package with different version for different package. In this article, we will install and create virtual environment for Python 3. We will use PIP to install the package. So let's start by installing virtual environment. First open the Terminal and run the below command. pip3 install virtualenv or install using apt command for Debian based distribution system. sudo apt-get install python3-venv You have installed virtual environment package. Now we need to create virtual environment for every project. For that, go to the project directory in Terminal and run the command. python3 -m venv new-env This will create new-env directory with python files. This directory will install all packages when you activate environment. To use this environment, you need to activate it. To activate environment, run the below command. source new-env/bin/activate When you run this command, environment name will be prefixed in the new line. Output: (new-env) root@laravelcode-lenovo-g30-50:/var/www/python Now all your python package will install and remove package in this environment. Once you done with environment package, you can deactivate the environment with deactivate command. deactivate Conclusion So in this article, we have learned how to install and create Python environment. This way you can create as many environment as you want. Thank you for giving time in reading the article.
Install Python 3.8 in Ubuntu
Python is flexible and powerful open-source programming language. Python is popular language for its short syntax, data analysis, machine learning and artificial purpose. In this tutorial, we will go through installing Python 3.8 in Ubuntu. However Python2 comes preinstalled in Ubuntu, but we will install latest version of Python 3.8 which is latest stable version of Python. Prerequisite You need to be logged as non-root user with sudo privilege to install packages in system. There are many ways you can install Python package. Here are some simple ways you can install Python easily. 1. Install Python via PPA You can simply add the third-party PPA repository to your Ubuntu software repository. This is the easy way to install Python package. This way you can also get update the package with apt package manager. First open the Terminal software by using shortcut key CTRL+ALT+T or go to menu and open the Terminal. Update the software repository index with below command: sudo apt-get update Install the common dependencies required for Python sudo apt-get install software-properties-common Now run the below command to add the third party deadsnakes PPA to your Ubuntu repository. sudo add-apt-repository ppa:deadsnakes/ppa Update the software repository index again and install the Python: sudo apt-get update sudo apt-get install python3.8 That's it. The latest Python is now installed. You can check the version by running the below command. python3 --version 2. Installing from source code Some hardcore users only want to install latest version of packages by building from the source code. In this way, you download the source code and build. Open the Terminal and run the below commands as instructs. First update the repository index and install the other required packages that will need to build the Python. sudo apt-get update sudo apt-get install build-essential zlib1g-dev libncurses5-dev libgdbm-dev libnss3-dev libssl-dev libreadline-dev libffi-dev wget After you install the above packages, first go to ~/Downloads directory and download the source code from the Python official site. You can direct download the source code or from the wget command. cd ~/Downloads wget Now extract the source code sudo tar xzf Python-3.8.3rc1.tgz Go to the source code directory cd  Python-3.8.3rc1 And build the package and install ./configure --enable-optimizations sudo make sudo make install This way Python 3.8 will be installed to your Ubuntu system. In this article, you have learned to install the latest version of Python by PPA as well as manually from the source code. I hope you had liked this article.
Image Blur Detection in Python using OpenCV and imutils Package
imutils is Python basic image processing functional package to do image translation, rotation, resizing, skeletonization, or blur amount detection. imutils also check to find functions if you already have NumPy, SciPy, Matplotlib, and OpenCV installed. In this article, we will check the image blur amount. This is used to verify image quality. We will use PIP to install the package. The next step is to install OpenCV package that will process the image. Run the below command to install it. pip3 install opencv-python We will also need Numpy package to work with array data. Install Numpy with following command. pip3 install numpy Now install imutils with below command: pip3 install imutils Now we have installed all packages that we required. Create file and add the below code. from imutils import paths import argparse import cv2 import sys def variance_of_laplacian(image):     return cv2.Laplacian(image, cv2.CV_64F).var() # image path imagePath = sys.argv['image']     image = cv2.imread(imagePath) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) fm = variance_of_laplacian(gray) text = "Not Blur" # check image quality if fm < 100:     text = "Blur image"     print text Explanation variance_of_laplacian() function takes one argument of image and returns 3X3 laplacian variance. We will pass imagePath with argument. The default blur threshold value we set is 100. You can set it according to image you want to test. If the value will be lower than 100, we will print image as Blur. Now run Python file in Terminal using python command python --image test.jpg This will print variable text whether the image is blur or not. Thank you giving time to read the article.
Python MySQL Database Connection using MySQL Connector module
Python is fast when working and analysing large size of database. To work with MySQL in Python, first you need to install MySQL Driver for Python. In this article we will use mysql-connector driver to work with Python3. pip is the package installer for Python. You can use pip to install packages from the Python Package Index. We recommend you use pip to install Python packages. To install MySQL driver, run the below command in Terminal. python3 -m pip install mysql-connector-python Now in python file, first import mysql connector. import mysql.connector Now create a connection to the database. mysql_database = mysql.connector.connect(     host = 'localhost',     user = 'root',     password = 'root',     database = 'database',     autocommit = True ) mysql_cursor = mysql_database.cursor() That's it. Your MySQL database is connected with Python. Now you can run MySQL query in Python. query = "SELECT * FROM users WHERE country = 'US'" mysql_cursor.execute(query) users = mysql_cursor.fetchall() for x in users:     print(x) Same way you can use all MySQL query in Python. If the query changes anything in the table you need to commit() the query to make changes in database or you can add autocommit = True in your connection code. query = "INSERT INTO users (first_name, last_name, address) VALUES ('John', 'Doe', 'Freemount Street')" mysql_cursor.execute(query) mysql_database.commit() Here is file with full code: #!/usr/bin/python import mysql.connector # connect with database mysql_database = mysql.connector.connect(     host = 'localhost',     user = 'root',     password = 'root',     database = 'neo',     autocommit = True ) # run query query = "INSERT INTO users (first_name, last_name, address) VALUES ('John', 'Doe', 'Freemount Street')" mysql_cursor.execute(query) mysql_database.commit() # close connection with database mysql_database.close() I hope this will help you in your day-to-day work. In next article, we will see on how to connect MongoDB with Python.
How To Install Pip3 On Ubuntu 20.04
PIP is python package manager that installs and manages Python packages from pypi. Python3 is already installed in Ubuntu 20.04 version. In this article, we will install pip package. So let's start. FIrst of all, open Terminal and run the below command tp update the Ubuntu repository list. sudo apt-get update Now, run the following command to install pip: sudo apt-get install python3-pip The PIP is now installed in your machine. You can find pip version with below command. pip3 --version To view all installed package through PIP, run the command: pip3 list To install new package through PIP, run the pip3 install command with package name. pip3 install package-name To remove package from Python3, run uninstall command: pip3 uninstall package-name To upgrade python package, run the command: pip3 install --upgrade package-name For more details about PIP, visit official website. Thank you for giving time to read the article. I hope you liked the article and it will help on your way.
How to connect with MongoDB Database in Python
In this article we will see how to connect MongoDB database with Python. MongoDB is open-source and json based NoSQL database management system. MongoDB store all data in collection with key and value. To connect MongoDB database with Python, you will need to install MongoDB driver to access MongoDB database. We will install PyMongo driver with PIP command. It is easy and recommend you install python packages with PIP. To install PyMongo driver, run the below command in Terminal. python3 -m pip install pymongo Now you can use PyMongo package for interacting with MongoDB database. Create database import pymongo client = pymongo.MongoClient("localhost", 27017) db = client.testdb To get all list of system database: print(client.list_database_names()) To check if database already exist dbname = client.list_database_names() if "mydatabase" in dbname:     print("The database exists.") Create and insert collection Collection is same as table in MySQL. Here’s a basic example for creating collection. db.my_collection Collection(Database(MongoClient('localhost', 27017), u'test'), u'my_collection') db.my_collection.insert_one({"name": "laravelcode"}).inserted_id # 5b1910482ddb101b7042fcd7 To insert multiple collection, you may use insert_many() method: import pymongo client = pymongo.MongoClient("localhost", 27017) mydb = client["my_database"] myrec = mydb["users"] mylist = [     { "name": "HacktheStuff"},     { "name": "Laravelcode"},     { "name": "ITSolution_stuff"} ] x = myrec.insert_many(mylist) # print list of the _id values of the inserted documents: print(x.inserted_ids) MongoDB Query To search records in MongoDB, find() method is used. This will filter the search results. import pymongo client = pymongo.MongoClient("localhost", 27017) mydb = client["my_database"] myrec = mydb["users"] myquery = {"name": "Laravelcode"} results = myrec.find(myquery) for x in results:     print(x) If you only want to get first result, use find_one() method instead of find()method. import pymongo client = pymongo.MongoClient("localhost", 27017) mydb = client["my_database"] myrec = mydb["users"] myquery = {"name": "Laravelcode"} results = myrec.find_one(myquery) print(results) sort() method will sort the result into specific collection. The second parameter in sort() method will sort by ascending(1) or descending(-1) order. import pymongo client = pymongo.MongoClient("localhost", 27017) mydb = client["my_database"] myrec = mydb["users"] myquery = {"name": "Laravelcode"} results = myrec.find(myquery).sort("name", -1) for x in results:     print(x) limit() method will return limited number of rows. import pymongo client = pymongo.MongoClient("localhost", 27017) mydb = client["my_database"] myrec = mydb["users"] myquery = {"name": "Laravelcode"} results = myrec.find(myquery).limit(2) for x in results:     print(x) Update records To update records, you can update records using update_one() or update_many() method. Update only first result using update_one() method. import pymongo client = pymongo.MongoClient("localhost", 27017) mydb = client["my_database"] myrec = mydb["users"] myquery = {"name": "Laravelcode"} newquery = {"$set": { "name": "Laravel-News" }} myrec.update_one(myquery, newquery) Update all searched records using update_many() method. import pymongo client = pymongo.MongoClient("localhost", 27017) mydb = client["my_database"] myrec = mydb["users"] myquery = {"name": {"$regex": "^Laravel"}} newquery = {"$set": { "name": "Laravel-News" }} myrec.update_many(myquery, newquery) Delete records In the same way, you can delete records using delete_one() or delete_many() method. import pymongo client = pymongo.MongoClient("localhost", 27017) mydb = client["my_database"] myrec = mydb["users"] myquery = {"name": "Laravelcode"} myrec.delete_one(myquery) Drop collection To drop whole collection, use drop() method. import pymongo client = pymongo.MongoClient("localhost", 27017) mydb = client["my_database"] myrec = mydb["users"] myrec.drop() This will return true if collection dropped successfully. If there is no collection, it will return false. This way, you can connect and work with MongoDB Database in Python.