first base of project-changed apps: Herd-livestock-tag-log-elasticsearch-

This commit is contained in:
2025-05-24 15:01:55 +03:30
parent eab40af15d
commit 90a46e493c
129 changed files with 3844 additions and 187 deletions

59
apps/core/middlewares.py Normal file
View File

@@ -0,0 +1,59 @@
from django.db import connection
from django.conf import settings
import os
def terminal_width():
"""
Function to compute the terminal width.
WARNING: This is not my code, but I've been using it forever and
I don't remember where it came from.
"""
width = 0
try:
import struct, fcntl, termios
s = struct.pack('HHHH', 0, 0, 0, 0)
x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
width = struct.unpack('HHHH', x)[1]
except:
pass
if width <= 0:
try:
width = int(os.environ['COLUMNS'])
except:
pass
if width <= 0:
width = 80
return width
class SqlPrintingMiddleware(object):
"""
Middleware which prints out a list of all SQL queries done
for each view that is processed. This is only useful for debugging.
"""
def __init__(self, get_response):
# print("heloo")
self.get_response = get_response
def __call__(self, request):
return self.process_response(request=request, response=self.get_response(request))
def process_response(self, request, response): # noqa
indentation = 2
if len(connection.queries) > 0 and settings.DEBUG:
width = terminal_width()
total_time = 0.0
for query in connection.queries:
nice_sql = query['sql'].replace('"', '').replace(',', ', ')
sql = "\033[1;31m[%s]\033[0m %s" % (query['time'], nice_sql)
total_time = total_time + float(query['time'])
while len(sql) > width - indentation:
print("%s%s" % (" " * indentation, sql[:width - indentation]))
sql = sql[width - indentation:]
print("%s%s\n" % (" " * indentation, sql))
replace_tuple = (" " * indentation, str(total_time))
print("%s\033[1;32m[TOTAL TIME: %s seconds]\033[0m" % replace_tuple)
print(response)
return response

View File

@@ -0,0 +1,21 @@
# Generated by Django 4.2.20 on 2025-05-17 06:01
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='mobiletest',
name='created_by',
),
migrations.RemoveField(
model_name='mobiletest',
name='modified_by',
),
]

View File

@@ -0,0 +1,23 @@
# Generated by Django 4.2.20 on 2025-05-17 06:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0002_remove_mobiletest_created_by_and_more'),
]
operations = [
migrations.AddField(
model_name='mobiletest',
name='created_by',
field=models.CharField(max_length=50, null=True),
),
migrations.AddField(
model_name='mobiletest',
name='modified_by',
field=models.CharField(max_length=50, null=True),
),
]

View File

@@ -0,0 +1,21 @@
# Generated by Django 4.2.20 on 2025-05-17 06:27
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0003_mobiletest_created_by_mobiletest_modified_by'),
]
operations = [
migrations.RemoveField(
model_name='mobiletest',
name='created_by',
),
migrations.RemoveField(
model_name='mobiletest',
name='modified_by',
),
]

View File

@@ -0,0 +1,26 @@
# Generated by Django 4.2.20 on 2025-05-17 06:29
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('core', '0004_remove_mobiletest_created_by_and_more'),
]
operations = [
migrations.AddField(
model_name='mobiletest',
name='created_by',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='%(class)s_createddby', to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='mobiletest',
name='modified_by',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='%(class)s_modifiedby', to=settings.AUTH_USER_MODEL),
),
]

View File

@@ -0,0 +1,23 @@
# Generated by Django 4.2.20 on 2025-05-17 06:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0005_mobiletest_created_by_mobiletest_modified_by'),
]
operations = [
migrations.AddField(
model_name='mobiletest',
name='creator_info',
field=models.CharField(max_length=100, null=True),
),
migrations.AddField(
model_name='mobiletest',
name='modifier_info',
field=models.CharField(max_length=100, null=True),
),
]

View File

@@ -1,5 +1,6 @@
from django.db import models
from django.conf import settings
from crum import get_current_user
class BaseModel(models.Model):
@@ -7,8 +8,8 @@ class BaseModel(models.Model):
modify_date = models.DateTimeField(auto_now=True)
created_by = models.ForeignKey(
settings.AUTH_USER_MODEL,
related_name="%(class)s_createdby",
on_delete=models.CASCADE,
related_name="%(class)s_createddby",
null=True,
blank=True,
)
@@ -19,11 +20,22 @@ class BaseModel(models.Model):
null=True,
blank=True,
)
creator_info = models.CharField(max_length=100, null=True)
modifier_info = models.CharField(max_length=100, null=True)
trash = models.BooleanField(default=False)
class Meta:
abstract = True
def save(self, *args, **kwargs):
user = get_current_user() # get user object
self.modified_by = user
if not self.creator_info:
self.created_by = user
self.creator_info = user.first_name + ' ' + user.last_name + '-' + user.national_code
self.modifier_info = user.first_name + ' ' + user.last_name + '-' + user.national_code
super(BaseModel, self).save(*args, **kwargs)
class MobileTest(BaseModel):
latitude = models.DecimalField(max_digits=22, decimal_places=16)

48
apps/core/permissions.py Normal file
View File

@@ -0,0 +1,48 @@
from rest_framework.permissions import BasePermissionMetaclass
from apps.authorization import models as authorize_models
import itertools
import typing
class BasePermission(metaclass=BasePermissionMetaclass):
"""
A base class from which all permission classes should inherit.
"""
def get_user_permissions(self, request, view) -> typing.Dict: # noqa
"""
get permissions by role and user specified permissions
combined permissions and returns a list
"""
organization_type = []
permissions_info = {}
relations = request.user.user_relation.select_related()
for relation in relations:
role_permissions = list(itertools.chain(*[
list(item.values()) for item in
list(relation.role.permissions.prefetch_related().values('name'))
]
))
user_permissions = list(itertools.chain(*[
list(item.values()) for item in
list(relation.permissions.prefetch_related().values('name'))])
)
result = list(set(role_permissions + user_permissions))
organization_type.append(relation.organization.type.key)
permissions_info['organization_type'] = organization_type
permissions_info['permissions'] = result
print(result, permissions_info)
return permissions_info
def has_permission(self, request, view): # noqa
"""
Return `True` if permission is granted, `False` otherwise.
"""
return True
def has_object_permission(self, request, view, obj): # noqa
"""
Return `True` if permission is granted, `False` otherwise.
"""
return True

16
apps/core/swagger.py Normal file
View File

@@ -0,0 +1,16 @@
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
schema_view = get_schema_view(
openapi.Info(
title="RasadDam Api",
default_version='v1',
description="All Apis",
terms_of_service="https://www.google.com/policies/terms/",
contact=openapi.Contact(email="contact@myapi.local"),
license=openapi.License(name="BSD License"),
),
public=True,
permission_classes=[permissions.BasePermission, permissions.IsAuthenticated]
)