def get_client_ip(request):
Monday, 7 August 2023
get client IP address from django request
Sunday, 15 January 2023
Django rest framework Project tutorials part 5 modelviewset
In this tutorial, we are going study more about modelviewset
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
GET
PUT
PATCH
DELETE
custom functions from action
@action(methods=['post'],detail=False,authentication_classes=[JWTTblUserAuthentication])
def change_password(self,request):
detailed explanation:-
get_queryset
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
get_authenticators
use case
remove authetication if new record is creating else use autheticator from default
authentication_classes=[JWTTblUserAuthentication]
if we are using method post then we dont need autheticator else we need JWTTblUserAuthentication
authetication
POST means we are using
create
default method is POST
use cases
1.we can manipulate the data like changing different serializer
2. checking user
3. changing response output if user is not customer,
destroy
default method is DELETE
def destroy(self, request, *args, **kwargs):
use case
we remove permission if user is destroying some others records
list
default method is GET
use case do pagination number to 50 from default
change serilizer_class
filter queryset with record type is apple only
retrieve
default method is GET
use case
check current user is the owner of the record then show detail of that record change serizlizer to detailed one
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
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
413 Request Entity Too Large
client_max_body_size 500M;
ln -s /etc/nginx/sites-available/project_name.conf /etc/nginx/sites-enabled/
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
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
4 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-
>
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
step 14
create urls.py in myapp
STEP 15
Create a funtion home in views.py of myapp
step 16
myproject-> urls.py
step 17
create routing for 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
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
urls.py
Question app
-models.py
-serilizers.py
-urls.py
-views.py
-models.py
serilizers.py
views.py
urls.py
USERAPP
-models.py
-serilizers.py
-urls.py
-views.py
models.py
serilizers.py
views.py
urls.py