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









































Django rest framework Project tutorials part 3

psc project

psc_project

-pscproject

--settiṇgs.py

--urls.py

-questionapp

--models.py

--urls.py

--serializers.py

--views.py

-userapp

--models.py

--urls.py

--serializers.py

--views.py

-manage.py

  settings.py

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

  urls.py

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

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

Question app

-models.py

-serilizers.py

-urls.py

-views.py

-models.py

from django.db import models

# Create your models here.
class Question(models.Model):
    question=models.CharField(max_length=255)
    ans1=models.CharField(max_length=255)
    ans2=models.CharField(max_length=255)
    ans3=models.CharField(max_length=255,blank=True,null=True)
    ans4=models.CharField(max_length=255,blank=True,null=True)
    ans5=models.CharField(max_length=255,blank=True,null=True)
    ans6=models.CharField(max_length=255,blank=True,null=True)
    original_ans=models.PositiveIntegerField(default=0)
    grade=models.FloatField
    class Meta:
        db_table='questions'

serilizers.py

from questionapp.models import Question
from rest_framework import serializers

class QuestionSerilizer(serializers.ModelSerializer):

    class Meta:
        model =Question
        fields = '__all__'
class QuestionDetailSerilizer(serializers.ModelSerializer):
   
    class Meta:
        model =Question
        fields = ('id','question')

views.py

from questionapp.models import Question
from rest_framework.response import Response
from rest_framework import viewsets
from questionapp.serilizers import QuestionDetailSerilizer, QuestionSerilizer

class QuestionViewset(viewsets.ModelViewSet):
    queryset =Question.objects.all()
    serializer_class = QuestionSerilizer
   
    def list(self, request, *args, **kwargs):
        queryset=self.queryset
        data= QuestionDetailSerilizer(queryset,many=True).data
        return Response(data)

urls.py

from questionapp.views import QuestionViewset
from rest_framework import routers
router=routers.SimpleRouter()
router.register("question",QuestionViewset)
urlpatterns=router.urls


USERAPP

-models.py

-serilizers.py

-urls.py

-views.py


models.py

from django.db import models
from django.contrib.auth.models import User

class Profile(User):
    qualification= models.CharField(max_length=255,blank= True,null=True)
    location= models.CharField(max_length=255,blank=True,null=True)
    address= models.TextField(blank= True,null=True)
    country= models.CharField(max_length=100,blank=True,null=True)
    district= models.CharField(max_length= 100,blank=True,null=True)
    photo= models.ImageField(blank=True,null=True)
   
    class Meta:
        db_table='profiles'


serilizers.py

from userapp.models import Profile
from rest_framework import serializers

class ProfileSerilizer(serializers.ModelSerializer):
   
    class Meta:
        model =Profile
        fields = '__all__'
class ProfileDetailSerilizer(serializers.ModelSerializer):
   
    class Meta:
        model =Profile
        fields = ('id','username')

views.py

from userapp.models import Profile
from rest_framework.response import Response
from rest_framework import viewsets
from userapp.serializers import ProfileDetailSerilizer, ProfileSerilizer

class ProfileViewset(viewsets.ModelViewSet):
    queryset =Profile.objects.all()
    serializer_class = ProfileSerilizer
   
    def list(self, request, *args, **kwargs):
        queryset=self.queryset
        data= ProfileDetailSerilizer(queryset,many=True).data
        return Response(data)

urls.py

from userapp.views import ProfileViewset

from rest_framework import routers
router=routers.SimpleRouter()
router.register("profile",ProfileViewset)
urlpatterns=router.urls













Friday, 14 October 2022

Django rest framework Project tutorials part 1

 Create a django project

1.create a environment 

python -m venv myenv

2.activate environment

myenv/Scripts/activate


refer python environment tutorial for more information

https://mamspython.blogspot.com/2022/10/creating-python-envirnment-in-5-ways.html

3.pip install Django

4. pip install djangorestframework

5.  django-admin startproject myproject .

6. python manage.py startapp myapp


7. register installed myapp

go to myproj folder

open settings.py

goto varaible list INSTALLED_APPS = [

add 'myapp', to the list

example

INSTALLED_APPS = [

  'django_crontab',
    'widget_tweaks',

.........

'myapp',

]

8. create urls.py in myapp folder

9. add line in myproj->urls.py 

path('',include('myapp.urls')),

10.add serializers.py file in myapp







Creating python environment in 5 ways

 python environment are created several ways

before creating environment install python software on os level

https://www.python.org/ftp/python/3.10.8/python-3.10.8-amd64.exe

environment are used to separate corresponding projects requirement libraries independent with another projects ,it will also helps to versioning your projects like , one environment may be using python 3.7 version another will be python version 3.8 version


lets create a envirnment myenv

1.python -m venv myenv 

myenv folder is created after executing this comment

inside myenv you can see activate file by opening scripts or bin


there are lots of ways creating environment





to activate the environment,use the below comment

find the path of activate file in my case activate file is located D:\projects\test13\testproj\myenv\Scripts\

so I can activate myenv like 

myenv\Scripts\activate

because i am already in  D:\projects\test13\testproj\ so i need only go from testproj folder "myenv\Scripts\"

or 

by full path

 D:\projects\test13\testproj\myenv\Scripts\activate 



I usually use this method and recommend using this simple way , you can try other methods also

2. python -m virtualenv .

. (the dot is used to create env on the current folder)

for this, you may need to install

pip install virtualenv


3.mkvirtualenv myenv 

using python wrapper

pip install virtualenv
pip install virtualenvwrapper-win ( do not use pip install virtualenvwrapper)

4. you can use pycharm software (download and install pycharm)

5. using anaconda 

Please note:-

Now onwards i will use env for environment