Open Laboratory for Technocrats

Grab the developer role, learn concepts & prepare with senior software engineers to get solutions for problems in a software job. Coding and Programming Solutions crafted for you.

Python - Auto generate requirements.txt



WHY

We need to track the dependencies that are being used in the application. Its an way to keep track of the modules that are being used with versions.


FORMAT

The requirement file will have the data in this format
requests==1.1.9
Flask==0.9.0

METHODS


PIPREQS

URL:
 https://github.com/bndr/pipreqs
Installation:
pip install pipreqs
Example:
pipreqs /home/project/location
Contents of requirements.txt

wheel==0.23.0
Yarg==0.1.9
docopt==0.6.2


FREEZE


  • It's good to use this when using virtual env for your project.
  • It saves the packages that are installed with pip install in your environment
  • It saves all packages in the environment including those that you don't use in your current project. (if you don't have virtualenv)

How to install dependencies from requirements.txt file

pip install -r <path_to_requirements.txt>


Keep Learning




Python Anonymous/Lambda Function



In Python anonymous functions are also called as Lambda functions.

Python Anonymous function is a function which is without a name.

We define functions in python is using the keyword def. Now if we define the anonymous function or lambda function we are not going to use the def keyboard. We will use the lambda keyword.

So the initial difference that we can easily detect is that lambda is the keyboard which will be used to define anonymous/lambda function.

Remember the school days of programming you might have used an inline function. Let's refresh it in contrast to python language.

Lambda Function is having a syntax as:
lambda argument: expression

  • Arguments can be multiple but the expression can be a single
  • It returns the result value to the caller.

We can use this wherever we need to use function objects required.

Example:

# Program to show the use of lambda functions
double = lambda x: x * 5
# Output: 5
print(double(1))

We can use lambda/anonymous function wherever we require the nameless function for a shorter period of time or which is not going to be reusable.

Please let us know about the article in comments or contact us.

Convert Image to Base64 Encoding - Python

Images are the important part of web applications.
Which are heavily used in some major application and ,some of the best applications are made on the base of the images.
Lets learn how to change the image from an URL to be converted to base64 encoded string which can be used directly to the img tag under html.
Lets see the code in python to do the same.
import base64
import requests
url = "http://images.freeimages.com/images/previews/118/bicycle-sign-3-1442216.jpg"
response = requests.get(url)
convertedData = ("data:" + response.headers['Content-Type'] + ";" + "base64," +str(base64.b64encode(response.content).decode("utf-8")))
Now you have the string inside variable called converted data, which holds base64 encoded string for the image mentioned in the url variable.
print convertedData

Check website is up and running - Python

Lets see how we can check if the website is up and working or its down in python.

Python provides minimal code to check this kind of requests and its fast.

Here is the code:
import urllib
import sys
try:
    httpcode =  urllib.urlopen("http://www.google.com").getcode()
    if httpcode == 200:
        print "Site is up and running"
    else:
        print "Site is not up"
except:
print "Oops!  Exception occured for this site: ", sys.exc_info()[0]
Explanation will be updated soon

Python Youtube Search Script













If you want to build a python script to get the result from the youtube based on the search query here is the script which you can run from a terminal and use in ubuntu.

For this, you will need the developer key for which you have to create an account but if you have a google account that's great then we are just a few clicks away from our developer key.

Before going into that just install this package click here

Just go to google developer projects page by clicking here and add a project for which you want to get the keys.

Then click on the project and go to Credentials on the left tab panel and then click create new key button.

It will ask you for which type of key, it will describe also that which type of key you are going to use on which kind.

So basically select the Browser key and you will be asked for the domains specification if you needed to restrict.

Lastly, press create.

You will have the keys on the project page which various other details will be along with it. So API KEY is the main key that we are going to use in our script.

After getting the key go through the process to install some pre-requirements from here and then here is the script which you can run from the terminal as python filename.py


#!/usr/bin/python

from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.tools import argparser


# Set DEVELOPER_KEY to the API key value from the APIs & auth > Registered apps
# tab of
#   https://cloud.google.com/console
# Please ensure that you have enabled the YouTube Data API for your project.
DEVELOPER_KEY = "PLACE DEVELOPER KEY HERE"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"

def youtube_search(options):
  youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
    developerKey=DEVELOPER_KEY)

  # Call the search.list method to retrieve results matching the specified
  # query term.
  search_response = youtube.search().list(
    q=options.q,
    part="id,snippet",
    maxResults= options.max_results
  ).execute()

  videos = []
  channels = []
  playlists = []

  # Add each result to the appropriate list, and then display the lists of
  # matching videos, channels, and playlists.
  for search_result in search_response.get("items", []):
    if search_result["id"]["kind"] == "youtube#video":
      videos.append("%s (%s)" % (search_result["snippet"]["title"],
                                 search_result["id"]["videoId"]))
    elif search_result["id"]["kind"] == "youtube#channel":
      channels.append("%s (%s)" % (search_result["snippet"]["title"],
                                   search_result["id"]["channelId"]))
    elif search_result["id"]["kind"] == "youtube#playlist":
      playlists.append("%s (%s)" % (search_result["snippet"]["title"],
                                    search_result["id"]["playlistId"]))

  print "Videos:\n", "\n".join(videos), "\n"
  print "Channels:\n", "\n".join(channels), "\n"
  print "Playlists:\n", "\n".join(playlists), "\n"


if __name__ == "__main__":
  argparser.add_argument("--q", help="Search term", default="Google")
  argparser.add_argument("--max-results", help="Max results", default=25)
  args = argparser.parse_args()

  try:
    youtube_search(args)
  except HttpError, e:
    print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)
Make sure you have replaced the DEVELOPER KEY with your key.

Thanks to developers.google.com

Now you can run this from your terminal to get the videos, channels and playlist from the search query.

Make sure that you should pass the argument from the terminal as python filename.py --pythonTutorialSearch so that it can search on your query else there is a by default case which is embedded.

Thanks :)

Top #3 Articles

Most Read