Avatar

Blogging tips

Avatar

Python, Django and Flask

Avatar

Latest tech posts

Monday, December 9, 2019

Do this before booking movie tickets

This is a small technique that actually takes less than 10 minutes to learn.
How can we book an extra movie seat for free?
Instance: You’re booking tickets for a movie in bookmyshow or paytm or a similar website, and one of the people who’s coming with you is not sure that he/she will be able to make it to the movie. Let’s say you’re booking tickets for 5, and one person may or may not join you. But if he/she joins later, you can watch the movie sitting together if you learn this technique.
When you’re booking tickets, instead of selecting the seats like this

codesimple.info
select your seats like this

codesimple.info
or like this
codesimple.info
The thing is, there is a very good chance that the single-seat will not get booked as generally most people don’t go to the movie alone. So, if your friend is joining you at the last minute, you can select that remaining (hopefully) single-seat and you can watch the movie together without risking your money.
#Blog, # Movie, #Life hacks

Session vs Token-Based Authentication



The authentication system is one that allows a user to access a resource only after supplied credentials are compared with that stored in the database and found to be the same. Authentication can either be Session-based or Token-based.

Difference between Authentication and Authorization


Authentication is about validating your credentials like User Name/User ID and password to verify your identity. The system determines whether you are what you say you are using your credentials. In public and private networks, the system authenticates the user identity via login passwords. Authentication is usually done by a username and password, and sometimes in conjunction with factors of authentication, which refers to the various ways to be authenticated.
Authorization, on the other hand, occurs after your identity is successfully authenticated by the system, which ultimately gives you full permission to access the resources such as information, files, databases, funds, locations, almost anything. In simple terms, authorization determines your ability to access the system and up to what extent.

session-based authentication

Session-based authentication is one in which the user state is stored on the server’s memory. When using a session-based auth system, the server creates and stores the session data in the server memory when the user logs in and then stores the session id in a cookie on the user browser.
The session Id is then sent on subsequent requests to the server and the server compares it with the stored session data and proceeds to process the requested action.





working of session-based authentication

token-based authentication

Token-based authentication is one in which the user state is stored on the client. This has grown to be the preferred mode of authentication for RESTful APIs. In the token-based authentication, the user data is encrypted into a JWT (JSON Web Token) with a secret and then sent back to the client.
The JWT is then stored on the client-side mostly localStorage and sent as a header for every subsequent request. The server receives and validates the JWT before proceeding to send a response to the client.
headers:{
"Authorization": "Bearer ${JWT_TOKEN}"
}





source

When to use?

There really isn’t a preferred method for authentication, both methods can be used interchangeably or together to create a hybrid system. It all boils down to the developer and the use case.
However, it is worth noting that token-based authentication scales better than that of a session because tokens are stored on the client-side while the session makes use of the server memory so it might become an issue when there is a large number of users using the system at once.

#Authentication #token-based-authentication #session-based-authentication

Saturday, December 7, 2019

Dockerize flask app

codesimple.info
Docker is a container management service. The keywords of Docker are develop, ship and run anywhere. The whole idea of Docker is for developers to easily develop applications, ship them into containers that can then be deployed anywhere.
Containers allow a developer to package up an application with all of the parts it needs, such as libraries and other dependencies, and ship it all out as one package.
Imagine you’re trying to deploy the following Python code, contained in index.py. The application is a simple, “Hello World” app that uses Flask, a small HTTP server for Python apps.


To do so, create a text file called Dockerfile in your application’s root and paste in the following code.

Dockerfile


Docker can build images automatically by reading the instructions from a Dockerfile. A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image.





Each instruction creates one layer:
  • FROM creates a layer from the alpine Docker image with python version as 3.7
  • COPY adds files from your Docker client’s current directory.
  • RUN builds your application with make.
  • CMD specifies what command to run within the container.
When you run an image and generate a container, you add a new writable layer (the “container layer”) on top of the underlying layers. All changes made to the running container, such as writing new files, modifying existing files, and deleting files, are written to this thin writable container layer.
Note that FROM directive is pointing to python:alpine3.7. This is telling Docker what base image to use for the container, and implicitly selecting the Python version to use, which in this case is 3.7. Docker Hub has base images for almost all supported versions of Python including 2.7. This example is using Python installed on Alpine Linux, a minimalist Linux distro, which helps keep the images for Docker small. Prefer Alpine unless there’s a compelling reason to use another base image such as Debian Jessie.
Also, note is the RUN directive that is calling PyPi (pip) and pointing to the requirements.txt file. This file contains a list of the dependencies that the application needs to run. Because Flask is a dependency, it is included as such in the requirements.txt with a simple reference. You can also select version libraries if you need specific versions with requirements.txt. The file should also be at the root of the application.
To build the image, run Docker build from a command line or terminal that is in the root directory of the application.
docker build --tag my-python-app .
This will “tag” the image my-python-app and build it. After it is built, you can run the image as a container.
docker run --name python-app -p 5000:5000 my-python-app
This starts the application as a container. The –name parameter names the container and the -p parameter maps the host’s port 5000 to the containers port of 5000. Lastly, my-python-app refers to the image to run. After it starts, you should be able to browse to the container. Depending on how you are running Docker depends on what the IP address of the application will be. Docker for Windows and Docker for Mac will be able to use 127.0.0.1. For other instances, it will be the host IP of a VM or physical machine you are running Docker on.

codesimple.info
Hello world app

Naturally, more complex scenarios will require more attention to details, but the basic flow is the same for most Python apps. Putting it all together will enable containerized Python apps in short order though!
Thanks for this article.
#Docker #Flask #Dockerfile

Thursday, December 5, 2019

Sticky header using HTML and CSS

Image result for html gif"


While creating my blog, I wanted it to have a sticky header at the top so that the readers will always be aware of the blog’s name. I had the simple idea of displaying the blog name and logo side by side at the header. I tried many things such as “float”, “display-inline” etc and couldn’t succeed.


Sticky header


The sticky header will fix the header in the top portion of your webpage when a user scrolls the page. It will allow quick access to the menu from any part of the page.

This can be achieved with simple HTML and CSS. If you need some cool animation effects then JavaScript can also be used.




sticky header codesimple.info



Pros and cons of a sticky header


So, there was an interesting discussion on an online forum on whether sticky headers improve the user experience or not. And here are the most common arguments for the use of sticky header:


Pros:

  • Time-saving

You have probably experienced this before — scrolling endlessly to go back to the menu bar on the very top after realizing that you were browsing the wrong page. With a sticky header, however, users are able to jump to different sections easily as the menu bar always appears on the screen.

  • Good navigation
So, it is the fastest and the most useful way to access to the right information for the end-users. That should make a sticky header good for user navigation. For example, a study showed that they are 22% faster to navigate and many participants preferred a website with fixed headers without knowing the exact reason. This particularly comes in handy on a mobile interface where text tends to be longer.

  • Branding effect
Here’s another minor advantage to add — it also helps you build your brand as your brand logo/name will always be there on the page next to the header.

Cons:

  • Waste of space
But here’s a catch — sticky header tends to eat up some valuable space as it is fixed permanently on the screen. Imagine you already have a beautiful and functioning website, adding a fixed header may seem excessive. It not only reduces the space for text but also cuts off background imagery.

  • Distracting
Also if implemented badly or incorrectly, it could even disrupt how the page is presented. Sticky navigation ‘does not always render effectively on mobile and tablet devices’. Those who are against sticky headers often argue that users visit the website for content, not navigation. Some users may find it disruptive to the ‘natural flow’ of the web page, while others prefer it for navigation reason (and this is when user testing comes in useful).

HTML



I came up with the solution of using tables for this purpose. This way the contents will be side by side and the height of the table row will also, be adjusted according to the height of the largest element in the row.



CSS


The CSS part looks like this. 



Finally, the sticky header of my blog looks like this.



sticky header codesimple.info

Tuesday, November 26, 2019

pip in python - installing, uninstalling and upgrading packages

pip is the package installer for python. Pip is one of the most famous and widely used package management systems to install and manage software packages written in Python and found in the Python Package Index (PyPI).
Most distributions of Python come with pip preinstalled. Python 2.7.9 and later (on the python2 series), and Python 3.4 and later include pip (pip3 for Python 3) by default. Additionally, you’ll need to make sure you have pip available. You can check this by running:
pip --version
If pip is not present, we can install it manually. To install pip, securely download get-pip.py
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
Then run the following:
python get-pip.py

What is a package?

A package contains all the files you need for a module. Modules are Python code libraries you can include in your project. The term “package” in this context is being used as a synonym for a distribution (i.e. a bundle of software to be installed), not to refer to the kind of package that you import in your Python source code (i.e. a container of modules).
pip provides various functionalities such as installing and uninstalling packages, the listing of packages, creating a requirements file, etc.

Installing packages using pip

Downloading a package is very easy. Open the command-line interface and tell PIP to download the package you want.

Installing a package

Any package can be installed from the python packaging index by the following command.
pip install SomePackage
This will install the latest version of a module and its dependencies from the Python Packaging Index.

Installing a package of a specific version

similarly, we can also install any packages of a specific version by specifying the version along with the above command. It’s also possible to specify an exact or minimum version directly on the command line.
pip install SomePackage==1.0.4

To install a greater, lesser or intermediate version

we can specify the minimum version to download by,
pip install SomePackage>=1.0.4
This will install the package whose version will be greater than or equal to 1.0.4
We can also specify an intermediate version to download by,
pip install SomeProject>=1,<2 span="">
The installed package’s version will be greater than or equal to one and less than two in this case.

Installing a compatible version

To install a version that is compatible with the current version, we can use
pip install SomeProject~=1.4.2

Upgrading the packages

Normally, if a suitable module is already installed, attempting to install it again will have no effect. Upgrading existing modules must be requested explicitly.
Modules can be upgraded by
pip install --upgrade SomePackage
or
pip install -U SomePackage

Uninstalling packages

Uninstalling packages is similar to installing them. we can directly specify the package name and uninstall them like
pip uninstall SomeProject
the example
$ pip uninstall simplejson
Uninstalling simplejson:
  /home/me/env/lib/python2.7/site-packages/simplejson
  /home/me/env/lib/python2.7/site-packages/simplejson-2.2.1-py2.7.egg-info
Proceed (y/n)? y
  Successfully uninstalled simplejson

Installing via Git

It’s quite common to want to pip install a version of a package that hasn’t been released to PyPI, but is available on its Git repository host, such as GitHub. If the package is pure Python or has a relatively simple build process integrated with setup.py, it can be installed from source.
Pip can speak git to do this through its VCS Support. For example, to install Django’s most recent commit at time of writing, we can run:
pip install git+https://github.com/django/django.git@45dfb3641aa4d9828a7c5448d11aa67c7cbd7966

Installing to the User Site

To install packages that are isolated to the current user, use the --user flag:
pip install --user SomeProject
For more information see the User Installs section from the pip docs.
Note that the --user flag has no effect when inside a virtual environment - all installation commands will affect the virtual environment.

Local project installs

pip supports installing local project in both regular mode and editable mode. You can install local projects by specifying the project path to pip:
$ pip install path/to/SomeProject
During regular installation, pip will copy the entire project directory to a temporary location and install from there. The exception is that pip will exclude .tox and .nox directories present in the top level of the project from being copied.

Installing packages from a requirements file

Requirements files give you a way to create an environment: a set of packages that work together. While developing a project we will install the packages one by one. If we want somebody else to run our application on their system, installing the packages one by one is not possible. “requirements” file come in handy here.

So what are requirements files? They are very simple: lists of packages to install.

This is how a requirements file looks like.

we can install all the requirements one by one by running the following command.
pip install -r requirements.txt

This will install all the packages one by one like this.




pip in python


Creating requirements file

We can also create our own requirements file for the packages that we installed in our application by running this following command.
pip freeze > requirements.txt
This creates a requirements.txt file with all the packages that we installed along with their versions.

List packages

Use the list command to list all the packages installed on your system:
pip list



pip list
pip list

Find Packages

By default, pip only finds stable versions. To find pre-release and development versions, in addition to stable versions, we can
$ pip install --pre SomePackage
Find more packages at https://pypi.org/.

Monday, November 4, 2019

CRUD operations using Flask and SQLAlchemy



 

CRUD operations using Flask and SQLAlchemy


Every database-related application has to deal with CRUD operations. It is used to store and retrieve data from the database. The CRUD operations are,
  1. Create
  2. Insert
  3. Update
  4. Delete
SQLAlchemy provides us a method to perform the CRUD operations. We can see this with the help of the book table. The book model looks like this.


    Inserting the records

     

    New records can be inserted by following these three steps. They are
    • Create the python object
    • Add it to the session
    • Commit the session

     

    Example

     

    Data can be inserted into the book model by the following commands.


    Deleting the records


    Deleting the records is very similar to adding the records. Instead of using the session.add(), we will use session.delete(), and commit the changes.


    Querying the database


    Flask-SQLAlchemy provides a query attribute on model class. Querying refers to the action of retrieving data from the database. For example, we may need only the people living in a particular city or from a particular age group. For these purposes querying comes in handy.

    Get all the values of a model


    The "all()" method by the query attribute helps us in retrieving all the records of a table.

    CRUD operations using Flask and SQLAlchemy
    Flask SQLAlchemy all() method

     Get the values of a record using primary key


    Let us say the table books have two entries with id 1 and 2, where id is the primary key field.


    CRUD operations using Flask and SQLAlchemy
    Flask SQLAlchemy get by primary key


    The contents of the record with the primary key 1 can be accessed by using the following query.

    To get the first value from a list of values


    The "first()" method by the query attribute helps us to get the first value from the list of available values.

    CRUD operations using Flask and SQLAlchemy
    Flask SQLAlchemy first() method

    Filter records


    The query attribute provides the "filter_by()" method. The field and the value is provided as the argument to the filter_by() method.


    CRUD operations using Flask and SQLAlchemy
    Flask SQLAlchemy filter_by first method



    This query will get the first instance of all the books named "Twilight".
    CRUD operations using Flask and SQLAlchemy
    Flask SQLAlchemy filter all method
    This will return all the instances of the books named "Twilight".


    Limiting query results


    The query results can be limited by using the limit() method. It takes an integer as an argument. This integer is the number of results that we want our query to return instead of returning them all.

    CRUD operations using Flask and SQLAlchemy
    Flask SQLAlchemy limit method

    This will limit the search result to 5 records only.


    Ordering the query results


    In SQLAlchemy the query results can be ordered by using the order_by method provided by the query attribute. The field based on which the search results are to be ordered is passed to the order_by method as an argument.

    CRUD operations using Flask and SQLAlchemy
    Flask SQLAlchemy order_by method

    Order by desc


    First we need to import the desc module from the SQLAlchemy  for this purpose.

    CRUD operations using flask and SQLAlchemy
    flask SQLAlchemy order by desc

    In the first example, the result is sorted in descending order based on the name of the author who wrote the book.

    Before it was like this. "Robin Sharma, Stephanie Meyer".
    Now it is like this. "Stephanie Meyer, Robin Sharma".


    Updating the records


    Updating a record is also a three step process. The three steps are,
    • Get the object
    • Assign a new value to the object's field
    • commit the changes
    CRUD operations using Flask and SQLAlchemy
    update record SQLAlchemy

        After running this command, the name of the book will be changed from "Twilight" to "Harry Potter".