Python – Variable

In python variable get declared when you assign value to variable first time

x=10;  #x will be integer
y='abcd' #y will be string
print(x)
print(y)

This will declare x as integer and y as string and you can also check data types as coded in below sample.

Find Type of Variable

you can use “type” keyword to find type of variable

Below is sample code and output

In Python variable names are case sensitive

x=10;  #x will be integer
y='abcd' #y will be string
X= 'Ten'

print( 'Value of small x=' ,x)
print('Value  of y=',y)
print('Value  of X=', X)

print( 'Type of small x=' ,type(x))
print('Type of y=',type(y))
print('Type of X=', type(X))

Output of this code will be as below

Value of small x= 10
 Value  of y= abcd
 Value  of X= Ten 
 Type of small x= <class 'int'>
 Type of y= <class 'str'>
 Type of X= <class 'str'>




P8 -Adding Pagination to ViewSets

Lets see how to add pagination to viewset. As will all other things in django, this is super easy

Assuming you have already done the the tutorial P6 – Django – Viewsets it is possible that we might need pagination on some of the rest calls. So we may have a lot of data on the server and sending it all at once back to the client may not be required and may not be the efficient way to handle the data. The client on the other hand might need only a handful of data and would not want all the data which will become difficult to process. So Lets see how do we set up pagination on view sets.

lets take example of rest services which returns “Ads” and it may have thousands of ads. At any point of time the client will need only a handful of them to process. So the client must be able to pass the rest service some parameter identifying the page number it desires.

For our example. We create a pagination.py file and add below content.


from rest_framework.pagination import PageNumberPagination

class PaginationMeta(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'page_size'
    max_page_size = 10000

Here we have set three parameters. One is the “page_size” which means the amount of data the server will send if requested with page number i.e with parameter “page” . The next is “page_size_query_param” which can be used if want a specified number of records to be retrieved and override the page_size. “max_page_size” which is the max page size for our request.

The next step is to set this class in our viewset as below.

from django.shortcuts import render
from .models import Ads
from .serializers import AdsSerializer
from rest_framework import viewsets
from .pagination import PaginationMeta
# Create your views here.


class AdsView(viewsets.ModelViewSet):
    queryset = Ads.objects.all()
    serializer_class = AdsSerializer
    pagination_class = PaginationMeta


Here we set the pagination_class to the PaginationMeta we created. And this is all we will have to do to set up pagination. I am providing other classes required for this example.

from django.db import models

# Create your models here.

class Ads(models.Model):
    category = models.CharField(max_length=50)
    city= models.CharField(max_length=50)
    email = models.CharField(max_length=50)
    brand = models.CharField(max_length=50)
    make = models.CharField(max_length=50)
    capacity = models.CharField(max_length=50)
    desc = models.CharField(max_length=150)
    price = models.FloatField(max_length=20)
from rest_framework import serializers
from .models import Ads


class AdsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Ads
        fields = ['id','category', 'city','email','brand','make','capacity','price','desc']
from rest_framework.routers import DefaultRouter
from . import views
from django.urls import path, include

router = DefaultRouter()
router.register('ads', views.AdsView)



urlpatterns = [
    path('', include(router.urls))
]

Now we have set the url pattern for our views to “/ads” so to access the views so a call to http://localhost:8000/api/ads/ will return the first page as below.

HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "count": 17,
    "next": "http://localhost:8000/api/ads/?page=2",
    "previous": null,
    "results": [
        {
            "id": 1,
            "category": "Cars & MotorCycles",
            "city": "Pune",
            "email": "",
            "brand": "MARUTI",
            "make": "Brezza",
            "capacity": "1.2",
            "price": 123213.0,
            "desc": "dadsadsad"
        },
        {
            "id": 2,
            "category": "Cars & MotorCycles",
            "city": "Pune",
            "email": "",
            "brand": "HYUNDAI",
            "make": "I20",
            "capacity": "1.2",
            "price": 34324234.0,
            "desc": "asdsadsads"
        },
        {
            "id": 3,
            "category": "Cars & MotorCycles",
            "city": "Pune",
            "email": "",
            "brand": "MARUTI",
            "make": "Brezza",
            "capacity": "1.2",
            "price": 122132.0,
            "desc": "sadsadad"
        }
    ]
}

As you can see, it has returned with the first page and also various others attributes to navigate to next page. We can jump to any page we wish by providing the page parameter to the url e.g. http://localhost:8000/api/ads/?page=4

Please let us know if you liked this post and if it helped you. Thank you for spending time reading my post.

View Session information

Lets see how to view session information in django

From our previous tutorial, we now know how to setup authentication. We know how to create an admin user or a normal user. here is the git link if you have not gone through the tutorial already. https://letsblogcontent.wordpress.com/2020/09/18/django-authentication/

We are going to build on from the previous tutorial – https://letsblogcontent.wordpress.com/2020/09/18/django-authentication/

You can start directly from this tutorial, just copy the contents from the git repo “pip install -r requirements.txt”

Step 1 – We will now create an app to view session information. lets call this app “admin-data-viewer”. Execute below command

python manage.py startapp AdminModels

Register the app into the project under the INSTALLED_APPS object

Step 2 – This will create a new app with admin.py inside the app.

from django.contrib import admin
from django.contrib.sessions.models import Session


class SessionAdmin(admin.ModelAdmin):
    def _session_data(self, obj):
        return obj.get_decoded()
    list_display = ['session_key', '_session_data', 'expire_date']

admin.site.register(Session,SessionAdmin)

Step 3 – If you have not created a user, lets create a super user. Execute below command and follow instructions

python manage.py createsuperuser

Step 4 – execute makemigrations and migrate

python manage.py makemigrations
python manage.py migrate

Step 5 – Run the server

python manage.py runserver

Step 6 – Navigate to http://127.0.0.1:8000/admin&#8221; and provide the admin username and password created in step 3 and look for b

Click on sessions to see below information about session

Setup Authentication in Django – In just 10 mins

A quick 10 min tutorial to setup authentication in django.

We are quickly going to see how do we setup authentication in Django. You wont believe how easy it will be, It is a matter of only 10 min.

git url https://github.com/letsblogcontent/Python/tree/master/djangoauthentication

Step 1

Lets begin with creation of the project using command django-admin startproject djangoauth. I will be using pycharm to edit files. You can edit in pycharm or anyother ide or your choice.

Step 2

On the terminal, in our project root directory, execute commands “python manage.py makemigrations” and “python manage.py migrate”


Step 3
Lets create a template directory where we will place our html files. I have created a templates directory in the root of the project. You may create the same structure. Also we need to register this directory in the settings.py file in the templates object. Against the DIRS add the following path. This will register our templates directory with the django project


 'DIRS': [os.path.join(BASE_DIR, 'templates')],

Lets add a home page for our application by adding home.html under the templates directory and add some sample content as below.

Step 4 – Add url mapping to enable authentication and the home page in the urls.py of djangoauth project (/djangoauth/djangoauth) file. The “django.contrib.auth.urls” is where we set up authentication

from django.contrib import admin
from django.urls import path, include
from django.views.generic.base import TemplateView

urlpatterns = [
    path('admin/', admin.site.urls),
]

urlpatterns += [
    path('', include('django.contrib.auth.urls')),
    path('', TemplateView.as_view(template_name='home.html'))
]

Step 5 –
Now lets run and check what is happening on the browser. Run our application by execution “python manage.py runserver”. You should see following code

Step 6
Django provides an admin page where we can add modify users. We will first create a superuser so that we can add more users to log-in. To create a superuser execute command “python maange.py createsuperuser”

To login with this user, On the browser navigate to http://localhost:8000/admin, this will show up the login page. Login with the user created above, you should see the below page

Now create a new user by clicking on add button. you will be presented with below page. fill in the details and click save. On the next page you can just click save.

Step 7 Next up is we need to setup the login page. Django looks for login page under the registration directory of templates. So we create a login.html file as below in templates/registrations directory.



{% block content %}
  <form method="post" action="{% url 'login' %}">
    {% csrf_token %}
    <table>
      <tr>
        <td>{{ form.username.label_tag }}</td>
        <td>{{ form.username }}</td>
      </tr>
      <tr>
        <td>{{ form.password.label_tag }}</td>
        <td>{{ form.password }}</td>
      </tr>
    </table>
    <input type="submit" value="login" />
    <input type="hidden" name="next" value="{{ next }}" />
  </form>

{% endblock %}

Next we update our home.html to show login and logout. Copy the below content to home.html

{% if user.is_authenticated %}
<h1>Welcome to home</h1>
{% else %}
<h1> Login to the application</h1>
 {% endif %}
<a href = "http://localhost:8000/login/">login</a>
{% if user.is_authenticated %}
<a href = "http://localhost:8000/logout/">logout</a>
{% endif %}

Add below variables to settings.py file. Here we are setting the login url and where should it redirect upon login and logout. Save the file and now navigate to http://localhost:8000/

LOGIN_REDIRECT_URL = '/'

LOGIN_URL = '/login'

LOGIN_REDIRECT_URL = '/'

LOGOUT_REDIRECT_URL= '/'

navigate to http://localhost:8000/ to below page

Click on login and enter with the user you created to see below page. And now you can click on logout to check if it works. It should take you back to the login screen.

Django Rest Framework – Part 3

So we have now completed how to add a GET request and how to add a POST request. Lets look at an example on how to add a url parameter to the request and use it to fetch data. It is extremely simple. Let look at the steps

Step1

Update the urls.py file as below to parse the integer field that we will pass from in the rest request. The integer field will be the primary key of the product object that we stored earlier in the tutorials. Notice we have added <int:pk>
as part of the url pattern which indicates django to map any request with integer values after the product to the get_product function in the views.py we defined in the previous step

Step 2

Now lets move to views.py file in the products app and create a new method to handle the get request for a particular object. Notice how we have passed the pk parameter to this method, this will be the parameter that we will pass in the rest request as the pk of the object that we want to respond with. We will use the serializer created in our previous tutorials to serialize the fetched object and send the response back


Step 3

Now lets look at sample request through ARC chrome plugin. Notice we have sent 4 as the pk of the Product object that we want to retrieve and we have received the response back from the server in json format.

GIT Project link – https://github.com/letsblogcontent/SampleRestProject

Django Rest Framework – Part2

In the previous tutorial we have created a simple rest framework and configured a “GET” request and successfully displayed data from the server through Django Rest framework. Now lets learn quickly how to add a POST request so that we can add new products through a rest call and then view it later.

Step1

Lets first define a new function in the views.py file in the products app and decorate it with POST attribute of the api_view annotation. Lets call this function as add_product. We fetch the data into the serializer instance of ProductSerializer and then check if the object is a valid Product object. This will confirm if we have received correct types in the fields as defined in our Product class. Once it is termed valid by the framework, we save it into the database.

Step 2

Now that we have defined the function we need to call, we need to configure the url that it should map to. So lets go the url.py in the products app and configure “product” to map to our newly defined function.

Step 3

And we are done with our project configuration. Now lets send a rest call to our server with the product object and check if the save was successful. I am using ARC(Advanced Rest Client) to send the rest request, you can use any one you like.

As you can see I have received a successful response back from the server. I have save a new product having name “Samsung X2” Make sure to choose a correct content type and POST method as shown else it will result into an error.

Step 4

Now lets retrieve the data of all the products and see if the data is saved.

Django Rest Framework -Part1

We will quickly go through a simple tutorial to create django rest project. It is extremely easy to configure a rest project work with Djange rest framework. Lets go through the steps. I am using PyCharm but it is not required but it will make development much easier with PyCharm. So lets begin.

Step1

Create a new project in PyCharm. Those not using PyCharm can skip this step. Create a directory otherwise.

Step 2

Install django using command “pip install django==3.1” on the terminal. You should see a successful installation of the django library.

Step 3

Now create a django project using command on terminal “django-admin startproject restproject .” “.” is used to create project in the current directory

Step 4

Now that we have the project ready, we will create a django app. The project consist only the configuration information. The app contains the application code. Execute the command “python manage.py startapp products

Step 5

Lets now create a model to store and retrieve. Lets create a model with name “Product” with fields “name”, “price”, “desc” as per the below screenshot.

Now, execute the command “python manage.py makemigrations” and “python manage.py migrate” . You will see following output. This will create a table in sqlite3 db being used in django.

Step 6

Install the django rest framework executing the command “pip install djangorestframework”

Step 7

Create a new file with name “serializers.py” under the products app as shown in the snapshot below.
The “serializers” are used to transform between various formats between the rest client and the server so that communication can happen seamlessly. Here we create a class ProductSerializer class which extends from the ModelSerializer class. The ModelSerializer class maps the fields between the model and serializer and performs validation based on the model defined under the meta class. We don’t need to think much here, just we need to understand that this is required for transofmation between an object to json/xml or vice versa.

Step 8

Now update the views.py file under the products app as below. Here we create a new function “product_list” which takes request as input parameter. We retrieve all the elements in the products table and then use the ProductSerializer created in the previous step to create a json response. Please see 1,2,3 points in the snapshot. We annotate the function to process “GET” request with api_view

Step 9

Now create a urls.py file in the products app if not present already and map “products” url to “product_list” function we created in the views.py file

Now update the urls.py file in the restproject as below to map urls starting with api to the products app

Step 10

We are done with the rest framework basic setup. To demonstrate its working, lets add some values to the products object/table using the admin functionality provided by django.

First register your “product” object to the admin. For this create a file admin.py file under products app and update with below content.

Lets create a superuser to manage admin functionality provided by django. Execute below commands. Provide details of username and password to create a super user

Now lets run our server with command “python manage.py runserver“. This will run the server at http://localhost/8000

Now navigate to url http://127.0.01:8000/admin. you will see below below screenshot and provide username and password created in the step above. for me it is admin/admin. Provide the details and press login.

Now you should see below screenshot

Now lets add a few products to the list, click on add and fill the details

This should add to the products table. This is really easy and fast way to populate some data. The admin functionality can do a lot of this, but will see more of it in future tutorials.

Step 11

Now we are all set to retrieve the list of the products using django rest framework. Hit the url http://127.0.0.1:8000/api/products to see the products we have created in previous step. You should response in json for the products you have created.


We have just now successfully created a basic setup of django restframework. We will look at some advanced features in the next tutorial. The git link for this project is “https://github.com/letsblogcontent/SampleRestProject


Create your website with WordPress.com
Get started