Wednesday, 22 May 2024

HTML table tutorials

 


Html table


table

    tr    th 

    tr    td


<table>

    <tr>    <th> title     </th>     <th> age </th>    </tr>   ====>table heading columns

    <tr>    <td> title     </td>     <td> age </td>    </tr>   ====>table normal columns

     <tr>    <td> title     </td>     <td> age </td>    </tr>   ====>table normal columns

</table>


this will display like this


title age
aymen 18
zakiya 30

Monday, 7 August 2023

get client IP address from django request

 def get_client_ip(request):

    ip=None
    x_forwarded = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded:
        ip=x_forwarded.split(',')[0]
    elif not ip:
        ip = request.META.get('REMOTE_ADDR')
    else:
        ip = request.META.get('HTTP_X_REAL_IP')
    return ip

Sunday, 15 January 2023

Django rest framework Project tutorials part 5 modelviewset

In this tutorial, we are going study more about modelviewset

class ProfileViewset(viewsets.ModelViewSet):
    queryset =Profile.objects.all()
    serializer_class = ProfileSerilizer
    authentication_classes=[JWTTblUserAuthentication]
    permission_classes=[IsUser]
    allowed_methods = ('PUT','GET')



modelviewset

common policies

queryset 

serializer_class 

authentication_classes

permission_classes

allowed_methods 

rare policies

    renderer_classes 

    parser_classes 

    throttle_classes  

    content_negotiation_class  

    metadata_class 

    versioning_class 


common overriding function for modelviewset


POST

def create(self, request, *args, **kwargs):

GET

def list(self, request, *args, **kwargs):

PUT

def update(self, request, *args, **kwargs):

PATCH

def partial_update(self, request, *args, **kwargs):

DELETE

def destroy(self, request, *args, **kwargs):


def get_queryset(self):



def get_authenticators(self):


def get_permissions(self):


def as_view(cls, **initkwargs):


custom functions from action

from rest_framework.decorators import action

@action(methods=['post'],detail=False,authentication_classes=[JWTTblUserAuthentication])

def change_password(self,request):


detailed explanation:-

get_queryset

queryset =Profile.objects.all()

we can modify queryset from get_queryset overriding function

use case 

1.full record for user_type =staff or admin

2.customer can only manipulate his records

we only need to give the records with current user id matches the table record if user is customer or we can give full record if the user_type is staff or admin


    def get_queryset(self):
        queryset = Profile.objects.all()
        if self.request.user.id and self.request.user.usertype != 'customer':
            return queryset
        if self.request.user.id:
            return queryset.filter(id=self.request.user.id)


get_authenticators

use case

remove authetication if new record is creating else use autheticator from default

authentication_classes=[JWTTblUserAuthentication]

def get_authenticators(self):
        if self.request.method.lower()=='post':
            return []
        return super().get_authenticators()

if we are using method post then we dont need autheticator else we need JWTTblUserAuthentication

authetication

POST means we are using

def create(self, request, *args, **kwargs):


create

default method is POST

def create(self, request, *args, **kwargs):
        return super().create(request, *args, **kwargs)


use cases

1.we can manipulate the data like changing different serializer

    def create(self, request, *args, **kwargs):
        self.serializer_class=ProfileSaveSerilizer
        return super().create(request, *args, **kwargs)

2. checking user 

3. changing response output if user is not customer, 

    def create(self, request, *args, **kwargs):
        self.serializer_class=ProfileSaveSerilizer
        if request.user.user_type=='customer':
            serializer = self.get_serializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            self.perform_create(serializer)
            headers = self.get_success_headers(serializer.data)
            return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
        return Response({},status=404)


destroy

default method is DELETE

def destroy(self, request, *args, **kwargs):

        return super().destroy(request, *args, **kwargs)


use case

we remove permission if user is destroying some others records

def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        if request.user==instance.user:
            self.perform_destroy(instance)
            return Response(status=status.HTTP_204_NO_CONTENT)
        return Response(status=status.HTTP_403_FORBIDDEN)

 

list

default method is GET

def list(self, request, *args, **kwargs):
        return super().list(request, *args, **kwargs)

use case do pagination number to 50 from default

change serilizer_class

filter queryset with record type is apple only

def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        queryset=queryset.filter(type='apple')
        self.pagination_class.page_size=50
        self.serializer_class=ApplelistSerializers
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


retrieve

default method is GET

def retrieve(self, request, *args, **kwargs):
        return super().retrieve(request, *args, **kwargs)

use case

check current user is the owner of the record then show detail of that record change serizlizer to detailed one

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        if instance.user==request.user:
            self.serializer_class=ProfileDetailSerilizer
            serializer = self.get_serializer(instance)
            return Response(serializer.data)
        return Response()


get_permissions

def get_permissions(self):
        return super().get_permissions()

use case

if we need to put permission like create update delete for staff , and all others can only view the records

then we can override function like 

    def get_permissions(self):
        if self.action=='create' or self.action=='partial_update' or self.action=='update' or self.action=='destroy':
            self.permission_classes=[IsStaff]

        return super(ProfileViewset,self).get_permissions()




Jenkin pipeline for angular

 pipeline {

  agent any

    

  tools {nodejs "Node-12.10.0"}

   environment {

       NODE_OPTIONS = '--max-old-space-size=8192'                               //can be used in whole pipeline

   }

    

  stages {

      stage('echo') {

      steps {

        echo env.NODE_OPTIONS

      }

   

    }

        

    stage('Git') {

      steps {


         git branch: 'brnachname', credentialsId: 'xxxxxxxx-ccc7-49e2-a690-xxxxxxxxxxx', url: "git@****************"

        

      }

   

    }

     

    stage('install_npm') {

      steps {

          sh 'npm install firebase@4.8.0'

          sh 'npm install'

         

      }

    }  

    

            


     stage('prod_build') {

      steps {

        sh 'npm run ng build --prod --aot --output-hashing=all'

      }

    }

    stage('delete_projectname') {

      steps {

        sh 'sudo rm -rf /home/deploy/apps/projectname'

      }

    }

    stage('deploy_code_projectname') {

      steps {

        sh 'sudo cp -r ./dist/apps /home/deploy/apps/projectname'

      }

    }

    

  }

}

Saturday, 26 November 2022

Django rest framework Project tutorials part final deploy

environment 

python -m venv projectenv

activate environment

pip install -r requirements.txt

.env files


MySQL

remotely connect 

mysql configuration changes

Services 

/etc/systemd/system/service_name.services

gunicorn  project_name.wsgi


reverse proxy

nginx 

configuration

localhost:8000

1271.0.0.1:8000

http->80

https ->443


8000->80

9000->80/443

443-> ssl certificate 

rverse_proxy:127.0.0.1:8000

listen:80

certificate  /etc/mm,vgvc...

Installing mysql

1.sudo apt update

2.sudo apt install mysql-server

3.sudo systemctl start mysql.service

4.sudo systemctl statusmysql.service

5.CREATE USER 'my_db_user'@'%' IDENTIFIED BY '7882#BB8B$FC!D327C30$8DD0E7E1750B*';

6.CREATE DATABASE my_db_nameCHARACTER SET utf8 COLLATE utf8_general_ci;

7.FLUSH PRIVILEGES;

8.sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

change to 

bind-address            = 0.0.0.0

change password if needed
ALTER USER 'learning_user'@'%' IDENTIFIED BY '73BE53ED2#BB8B$FC!D327C30$8DD0E7E1750B';

install nginx

configuration accordingly
/etc/nginx/sites-available

sudo apt update
sudo apt install nginx


server{

         server_name 109.69.10.29 mydomain.com;
        listen 80;

        location /static {
        root /home/apps/project_name;
        }
        location /media {
        alias /home/apps/project_name/media/;
        }
        access_log /home/apps/project_name/logs/nginx-access.log;
        error_log /home/apps/project_name/logs/nginx-error.log;


        location / {
                 proxy_set_header Host $http_host;
            proxy_pass http://localhost:9000;
                proxy_redirect off;

       }

         location /apis {
                 proxy_set_header Host $http_host;
            proxy_pass http://localhost:9000;
                proxy_redirect off;

       }


}


add this line to nginx.conf inside http{}

if file uploading get this error

413 Request Entity Too Large


nginx/1.22.0 (Ubuntu)
client_max_body_size 500M;
ln -s /etc/nginx/sites-available/project_name.conf /etc/nginx/sites-enabled/
sudo nginx -s relaod
sudo service nginx restart
sudo service nginx status

creating service
/etc/systemd/system/project_name.service

[Unit]
Description=gunicorn daemon
After=network.target

[Service]
Type=notify
# the specific user that our service will run as
# another option for an even more restricted service is
#DynamicUser=yes
User=root
Group=root
# see http://0pointer.net/blog/dynamic-users-with-systemd.html
RuntimeDirectory=gunicorn
WorkingDirectory=/home/apps/project_name
ExecStart=/home/apps/project_name/projectenv/bin/gunicorn project_name.wsgi --bind 0.0.0.0:8000 --timeout 120
ExecReload=/bin/kill -s HUP $MAINPID
KillMode=mixed
TimeoutStopSec=5
PrivateTmp=true

[Install]
WantedBy=multi-user.target

php
 configuration
nano /etc/php/8.1/fpm/pool.d/www.conf

;listen = /run/php/php8.1-fpm.sock
listen = 127.0.0.1:9000
;security.limit_extensions = .php .php3 .php4 .php5 .php7
security.limit_extensions = .php .html

-----------------

php nginx

nginx.conf

---------------

     fastcgi_buffers 8 16k;

    fastcgi_buffer_size 32k;

    fastcgi_connect_timeout 90;

    fastcgi_send_timeout 90;

    fastcgi_read_timeout 90;

-----------------

domain.conf

location / {

        root /home/apps/front;

        try_files $uri $uri/ /index.php;

        #index index.php index.html;

        fastcgi_split_path_info ^(.+\.php)(/.+)$;

        fastcgi_pass  127.0.0.1:9000;

        include fastcgi_params;

        fastcgi_index index.php;

        #fastcgi_param SCRIPT_FILENAME `$document_root/service/public$fastcgi_script_name`;

        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;


}


  # deny access to Apache .htaccess on Nginx with PHP,

  # if Apache and Nginx document roots concur

  location ~ /\.ht {

    deny all;

  }


Thursday, 27 October 2022

Django rest framework Project tutorials part 4

A django Application


Users

Authetication

search

list

select

cart/wishlist

booking/order

payment

notification



Users

email

mobile

password

otp

Authentication

API

register

login

generate_otp

verify_otp

forgot password

change password


Search

name

location

category


list

name

price

rate


order/booking

Payment


django application

model

serializers

views

urls


Model

class Basemodel(models.Model):

    created=datetimstamp

    updated=datetimstamp


class TableName(models.Model,User,Basemodel):

    field_name=Type

    name=models.CharField

    price=models.FloatField

    count=models.PositiveIntegerField

    is_customer=BooleanFiled

    model_name=Relation

    booking=models.Foreinkey    one to many  on_delete=models.SET_NULL ,PROTECT,

                    =models.OntoOne one to one

                    =models.ManyToMany many to many


example

class Student(models.Model)

    name=models.CharField(max_lenght=100)

    age=models.PositiveIntegerField()


class Mark(models.Model):

    subject=models.CharField(max....)

    grade=models.PositiveIntegerField()

Student and Mark

student table

id name age

1 lulu 15

2 sulu 14


mark

id subject grade student

1    maths 10        1

2    arabic    9        1

3     maths   9        2

       arabic  15     2


class Mark(models.Model):

    subject=models.CharField(max....)

    grade=models.PositiveIntegerField()

    student=models.Foreinkey(Student,)


Serializer

from rest_framework import serializers


class StudentSerializer(serializers.ModelSerailzers):

    class Meta:

        model = Student

         exclude=('created','updated') or  fieleds=('name','age') or fields= '__all__'

      


class StudentSerializer(serializers.ModelSerailzers):

    class Meta:

        model = Student

         exclude=('created','updated') or  fieleds=('name','age') or fields= '__all__'


    def to_internal_value(self, data):

            #input data manipulation

            return data


   def to_representation(self, instance);

        data= super()

        #output data manipulation

        return data

    def validate(self, attrs):

    def create(

    def update(


views

from rest_framework import viewsets


class StudentViewset(viewsets.ModelViewSet):

    queryset.Student.objects.all()

    serializer_class=StudentSerializer


    urls

    from rest_framwork.routers import SimpleRouter

    #main_url/function_name/

    http://localhost:8000/student/


    student is function name mapped to viewset function or class


    obj=SimpleRouter()

    obj.register(r'student',StudentViewset)

    urlpatterns=obj.urls



class StudentViewset(viewsets.ModelViewSet):

    queryset.Student.objects.all()

    serializer_class=StudentSerializer

    authetication_class=

    permission_class


inbuild methods with model viewset

    def create()  ===>POST

    def update()    ==>PUT,PATCH

    def retrieve()    ==>GET

    def list() ===>GET

    def destroy() ==>DELETE

   

 @action(methods=['post'],detail=True)

   def custom_function()

    eg 

        @action(methods=['POST'],detail=False,authentication_classes=[],permission_classes=[])

def login(self,request):

                pass


    

urls

    from rest_framwork.routers import SimpleRouter

    #main_url/function_name/

    http://localhost:8000/student/


    student is function name mapped to viewset function or class

student ===>StudentViewset

    router=SimpleRouter()

    router.register(r'student',StudentViewset)

    urlpatterns=router.urls



ModelViewSet

class ModelViewSet(mixins.CreateModelMixin,==>POST create

                   mixins.RetrieveModelMixin, ==>GET, retrieve

                   mixins.UpdateModelMixin, ==>PUT,PATCH update

                   mixins.DestroyModelMixin,==>DELETE destroy

                   mixins.ListModelMixin, =====>GET, list

                   GenericViewSet)


class ProfileViewset(viewsets.ModelViewSet)

create

update

list retrieve

delete



class ProfileViewsets(mixins.CreateModelMixin,GenericViewSet)

    def create() ===>POST


Admin


admin.site.register(Student)


or we can customize with adminModel


example to disable delete option from admin


class StudentModel(admin.ModelAdmin):

def get_actions(self, request):

actions = super(StudentModel, self).get_actions(request)

if 'delete_selected' in actions:

del actions['delete_selected']

return actions

def delete_model(self, request, obj):

return 0

def message_user(self, request, message, level = 30, extra_tags, fail_silently) :

message='delete not allowed'#you can give whatever messeage you want

return super().message_user(request, message, 40, extra_tags, fail_silently)

so then we can resgist Student model like 

admin.site.register(Student,StudentModel)

to get more about this overiding functions alt+click on admin.ModelAdmin


Saturday, 15 October 2022

Django tutorial part 2

step 1

 create an environment

open 'cmd ' from address bar











python -m venv myenv -> enter

step 2

activate by 


PS E:\project> .\myenv\Scripts\activate


step 3

Install django library


step 4

Install djangorestframework


step 5

Show installed libraries in current environment


step 6 

listing installed libraries in current environment


step 7

After installing django we can see a django-admin.exe file is created in myenv ->Scripts-
>

step 8

listing django admiṇ command

django-admin


Step 9

create project using django admin


step 10

create app 



step 11

open vs code



step 12

project file structure












step 13

register app 

add myapp in INSTALLED_APPS list variable 


INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
]


step 14

create urls.py in myapp











STEP 15

Create a funtion home in views.py of myapp

from django.http import HttpResponse

def home(request):
    return HttpResponse("HELLO WORLD")


step 16

myproject-> urls.py

from django.contrib import admin
from django.urls import path,include

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

step 17

create routing for home

from django.urls import path
from myapp.views import home
urlpatterns = [
    path('index',home)
]

step 18

runserver

(myenv) PS E:\project> python manage.py runserver

Watching for file changes with StatReloader

Performing system checks...


System check identified no issues (0 silenced).


You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, 

sessions.

Run 'python manage.py migrate' to apply them.

October 16, 2022 - 12:03:14

Django version 4.1.2, using settings 'myproject.settings'

Starting development server at http://127.0.0.1:8000/    

Quit the server with CTRL-BREAK.


step 19

goto browser and type url

http://127.0.0.1:8000/index