extra collection:
al the important concept are collected here and other more information can be get from this page before filtering ., after filtering all the concept a=will be posted in particular pages.
27.6678695,85.3658704
Python:
now = datetime.now(timezone.utc)
today_start = datetime(now.year, now.month, now.day, tzinfo=timezone.utc)
from datetime import datetime,timezone
from pytz import timezone as tz
# abc=datetime.now(timezone.utc)
# # print(abc)
# # print(abc.strftime('%Y-%m-%d %H:%M:%S %Z%z'))
# # print(abc.strftime('%I:%M %p'))
# # local_tz = timezone('Asia/Kathmandu')
# # local_time = abc.astimezone(local_tz)
# # print(local_time)
# # print(local_time.strftime('%Y-%m-%d %H:%M:%S %Z%z'))
# # print(local_time.strftime('%I:%M %p'))
from datetime import datetime
from pytz import timezone
# Current time in UTC
utc_now = datetime.now(timezone('UTC'))
utc_now = '2025-01-14T05:12:56.346000'
print(utc_now)
# Convert to Kathmandu time
local_tz = timezone('Asia/Kathmandu')
kathmandu_time = utc_now.astimezone(local_tz)
# Print time in the desired format
print(kathmandu_time.strftime('%I:%M %p'))
print(utc_now.strftime('%I:%M %p'))
FastAPI:
@router.post("/register")
async def user_register(request: Request, user: SignUp):
# Log the Pydantic model
logging.error(f"User Data: {user}")
# Retrieve and log raw body
body = await request.json()
logging.error(f"Raw Body: {body}")
# Retrieve and log headers
headers = dict(request.headers)
logging.error(f"Headers: {headers}")
# Retrieve and log query parameters
query_params = dict(request.query_params)
logging.error(f"Query Params: {query_params}")
# Retrieve and log cookies
cookies = request.cookies
logging.error(f"Cookies: {cookies}")
# Retrieve client IP and other connection details
client_host = request.client.host
client_port = request.client.port
logging.error(f"Client Host: {client_host}, Client Port: {client_port}")
return JSONResponse(status_code=status.HTTP_200_OK, content={"message": "success"})
from fastapi import Response
@router.post("/testing")
async def user_testing(request: Request,response=Response):
response = JSONResponse(
status_code=status.HTTP_200_OK,
content={"message": "Token stored successfully"}
)
response.set_cookie(
key="access_token",
value="Bearer access_token_amrit",
httponly=True
)
return response
response = JSONResponse(status_code=status.HTTP_200_OK, content=data)
response.set_cookie(
key="token", # Cookie name
value=token, # Token value
httponly=True, # Make the cookie HTTP only
max_age=10 * 60, # Cookie expiration time in seconds (5 minutes)
samesite="Strict", # Adjust this based on your security needs
secure=False # Set to True if using HTTPS
)
return response
@router.post("/register")
async def register(request: Request):
# Get the method of the request
method = request.method
headers = dict(request.headers)
# Get the client IP address
client = request.client
# Get the body as JSON (assuming JSON data is sent)
# body = await request.json()
# Respond with the received body and other information
return JSONResponse(content={
"message": "Success",
"method": method,
"headers": headers,
"client": str(client)
})
............................
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
app = FastAPI()
@app.get("/", response_class=HTMLResponse)
async def show_location():
latitude = 27.6678695
longitude = 85.3658704
# Replace `YOUR_GOOGLE_MAPS_API_KEY` with your Google Maps API key
html_content = f"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Location Viewer</title>
</head>
<body>
<h1>Location Viewer</h1>
<iframe
width="100%"
height="600"
src="https://www.google.com/maps/embed/v1/place?key=YOUR_GOOGLE_MAPS_API_KEY&q={latitude},{longitude}"
frameborder="0"
style="border:0"
allowfullscreen>
</iframe>
</body>
</html>
"""
return HTMLResponse(content=html_content)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
.......................................
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
<p class="card-text">{{post.content|safe|slice:":200" }}</p>
{% if is_paginated %}
<nav aria-label="Page navigation conatiner"></nav>
<ul class="pagination justify-content-center">
{% if page_obj.has_previous %}
<li><a href="?page={{ page_obj.previous_page_number }}" class="page-link">« PREV </a></li>
{% endif %}
{% if page_obj.has_next %}
<li><a href="?page={{ page_obj.next_page_number }}" class="page-link"> NEXT »</a></li>
{% endif %}
</ul>
</nav>
</div>
{% endif %}
{{ comment.body | linebreaks }}
django-debug-toolbar==3.2.2
django-summernote==0.8.11.6
import webbrowser
def open_google_maps(latitude, longitude):
# Create the URL for Google Maps with the provided coordinates
url = f"https://www.google.com/maps?q={latitude},{longitude}"
# Open the URL in the default web browser
webbrowser.open(url)
# Latitude and Longitude
latitude = 27.6678695
longitude = 85.3658704
# Open Google Maps
open_google_maps(latitude, longitude)
...........................
import folium
import webbrowser
def show_location(latitude, longitude):
# Create a map centered at the given location
map_location = folium.Map(location=[latitude, longitude], zoom_start=15)
# Add a marker at the location
folium.Marker([latitude, longitude], tooltip="Click for more info").add_to(map_location)
# Save the map to an HTML file
map_file = "location_map.html"
map_location.save(map_file)
# Open the map in the default browser
webbrowser.open(map_file)
query = {
"customer_member_id": customer_member_id,
"$or": [
{"deleted": False}, # Not deleted
{"deleted": {"$exists": False}}, # Deleted does not exist
],
}
data = (
await db.mongo_db["Notifications"]
.find(query)
.sort("created_time", -1) # Sort by latest created_time
.skip(offset) # Pagination: skip 'offset' items
.limit(limit) # Pagination: limit results to 'limit' items
.to_list(length=None)
)
sort=[
("created_at", -1),
("_id", -1)
]
......................
- {"$set": model.model_dump()},
+ {"$set": model.model_dump(exclude_unset=True)},
The model_dump method is called without any arguments. Consider specifying exclude_unset=True to ensure only explicitly set fields are updated.
52.84.206.128:443
import requests
# IP address to lookup
ip_address = "52.84.206.128"
# Use ipinfo.io API
response = requests.get(f"https://ipinfo.io/{ip_address}/json")
data = response.json()
# Extract country and city
city = data.get("city", "N/A")
country = data.get("country", "N/A")
print(f"City: {city}, Country: {country}")
Momgodb:
db.Customer_Member.updateMany(
{},
{
$set: {
is_verified: true,
is_onboarding: true
}
}
)
Django:
from django.db import IntegrityError
except IntegrityError:
.........................
class Blogcomment(models.Model):
sno = models.AutoField(primary_key=True)
comment = models.TextField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Blog, on_delete=models.CASCADE)
parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True)
Timestamp = models.DateTimeField(default=now)
def __str__(self):
return str(self.user) + ' commented'
def postcomment(request):
if request.method == 'POST':
comment = request.POST['comment']
user = request.user
postsno = request.POST.get('postsno')
hello = Blog.objects.get(sno=postsno)
parentsno = request.POST.get('parentsno')
print(comment)
print(hello)
print(parentsno)
# comment ,user aayo. postno le chai blog ko id fetch garxa.tei id use garera aako comment lai blog sanga associate gareko ho
if parentsno == "":
comment = Blogcomment(comment=comment, user=user, post=hello)
comment.save()
messages.success(request, "Successfully posted comment")
else:
parent = Blogcomment.objects.get(sno=parentsno)
comment = Blogcomment(
comment=comment, user=user, post=hello, parent=parent)
comment.save()
messages.success(request, "Successfully posted reply")
return redirect(f'/blogpost/{hello.slug}')
def blogpost(request, slug):
blog = Blog.objects.filter(slug=slug).first()
comments = Blogcomment.objects.filter(post=blog, parent=None)
replies = Blogcomment.objects.filter(post=blog).exclude(parent=None)
# for reply
replyDict = {}
for reply in replies:
if reply.parent.sno not in replyDict.keys():
replyDict[reply.parent.sno] = [reply]
else:
replyDict[reply.parent.sno].append(reply)
return render(request, 'Blog/blogpost.html', {
'blog': blog,
'comments': comments,
'replyDict': replyDict
})
from django import template
register = template.Library()
@register.filter(name="get_val")
def get_val(dict,key):
return dict.get(key)
main.yml for django applicaion:
on:
push:
branches:
- main
name: ???? Deploy website on push
jobs:
web-deploy:
name: ???? Deploy
runs-on: ubuntu-latest
steps:
- name: ???? Get latest code
uses: actions/checkout@v2
- name: ???? Sync files
uses: SamKirkland/[email protected]
with:
server: ${{ secrets.ftp_server }}
username: ${{ secrets.ftp_username }}
password: ${{ secrets.ftp_password }}
server-dir: /Abinash-blog-backend/
from django.http import HttpResponse
from django.shortcuts import redirect
#the role of decorator is to render the views with respect to its role
def unauthenticated_user(view_func):
def wrapper_func(request, *args, **kwargs):
if request.user.is_authenticated:#if user is authenticated,home ma redirect garxa natra views ma bhako function call hunxa
return redirect('home')
else:
return view_func(request, *args, **kwargs)
return wrapper_func
decorator.py.....
# if user login with admin kun view dekhau ne bhnna lai
#if customer logins with customer ,xuttai vieww dekhua na ko lagi
#yo functionality use garna lai,admin panel ma gayera group create pani garnu parxa
def admin_only(view_func):
def wrapper_function(request, *args, **kwargs):
group = None
if request.user.groups.exists():
group = request.user.groups.all()[0].name
if group == 'customer':
return redirect('userpage')
if group == 'admin':
return view_func(request, *args, **kwargs)
return wrapper_function
def allowed_users(allowed_roles=[]):
def decorator(view_func):
def wrapper_func(request, *args, **kwargs):
group = None
if request.user.groups.exists():
group = request.user.groups.all()[0].name
if group in allowed_roles:
return view_func(request, *args, **kwargs)
else:
return HttpResponse('You are not authorized to view this page')
return wrapper_func
return decorator
views.py
from django.shortcuts import render, HttpResponse, redirect
from .models import *
from django.forms import inlineformset_factory
from .forms import Orderform, CreateUserForm,Customerform
from .filters import OrderFilter
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from .decorators import unauthenticated_user, allowed_users, admin_only
from django.contrib.auth.models import Group
# Create your views here.
@login_required(login_url='login')
@admin_only
def home(request):
order = Order.objects.all()
Customers = customer.objects.all()
total_customers = Customers.count()
total_orders = order.count()
deliverd = order.filter(Status='Delivered').count()
pending = order.filter(Status='Pending').count()
content = {'customers': Customers,
'orders': order,
'tot_cust': total_customers,
'tot_orders': total_orders,
'delivered': deliverd,
'pending': pending
}
return render(request, 'system/Dashboard.html', content)
@login_required(login_url='login')
def customers(request, pk_test):
Customers = customer.objects.get(id=pk_test)
# inherting childs objects(order) from parent class i.e customer
orders = Customers.order_set.all() # customer ko help bata order call gareko
total_order = orders.count()
fil = OrderFilter(request.GET, queryset=orders)
orders = fil.qs
context = {'customer': Customers,
'order': orders, 'total_order': total_order, 'fill': fil}
return render(request, 'system/customer.html', context)
@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def products(request):
Products = product.objects.all()
content = {'products': Products}
return render(request, 'system/products.html', content)
@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def createorder(request, pk):
# customers=customer.objects.get(id=pk)
# form=Orderform(initial={'customer':customers})
OrderFormSet = inlineformset_factory(
customer, Order, fields=('Products', 'Status'), extra=6)
Customer = customer.objects.get(id=pk)
formset = OrderFormSet(queryset=Order.objects.none(), instance=Customer)
if request.method == "POST":
formset = OrderFormSet(request.POST, instance=Customer)
if formset.is_valid():
formset.save()
return redirect('/')
context = {'form': formset}
return render(request, 'system/order_form.html', context)
@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def updateorder(request, pk):
order = Order.objects.get(id=pk)
form = Orderform(instance=order)
if request.method == "POST":
form = Orderform(request.POST, instance=order)
if form.is_valid():
form.save()
return redirect('/')
context = {'form': form}
return render(request, 'system/order_form.html', context)
@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def deleteorder(request, pk):
order = Order.objects.get(id=pk)
if request.method == "POST":
order.delete()
return redirect('/')
context = {'item': order}
return render(request, 'system/delete_order.html', context)
@unauthenticated_user
def registerPage(request):
if request.user.is_authenticated:
return redirect('/')
else:
regis = CreateUserForm() # imported from forms
if request.method == "POST":
regis = CreateUserForm(request.POST)
if regis.is_valid():
user = regis.save()
messages.success(request, 'Account was created')
return redirect('login')
context = {'regis': regis}
return render(request, 'system/register.html', context)
@unauthenticated_user
def loginPage(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
messages.info(request, 'Username OR password is incorrect')
context = {}
return render(request, 'system/login.html', context)
@login_required(login_url='login')
def logoutUser(request):
logout(request)
return redirect('login')
@login_required(login_url='login')
@allowed_users(allowed_roles=['customer'])
def userpage(request):
order = request.user.customer.order_set.all() #user bata customer ko obejct haru le ko
total_orders = order.count()
deliverd = order.filter(Status='Delivered').count()
pending = order.filter(Status='Pending').count()
context = {'order': order,
'tot_orders': total_orders,
'delivered': deliverd,
'pending': pending
}
return render(request, 'system/userpage.html', context)
@login_required(login_url='login')
@allowed_users(allowed_roles=['customer'])
def settingpage(request):
Customer=request.user.customer
form=Customerform(instance=Customer)
if request.method=="POST":
form=Customerform(request.POST,request.FILES,instance=Customer)
if form.is_valid():
form.save()
context={'form':form}
return render(request,'system/account_setting.html',context)
filters.py
import django_filters
from django_filters import DateFilter,CharFilter
from .models import *
#this is for search
class OrderFilter(django_filters.FilterSet):
start_date = DateFilter(field_name="date_created", lookup_expr='gte')
end_date = DateFilter(field_name="date_created", lookup_expr='lte')
note=CharFilter(field_name='note',lookup_expr='icontains')
class Meta:
model = Order
fields = '__all__'
exclude = ['Customer', 'date_created']
signals.py
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.contrib.auth.models import Group
from .models import customer
#signal chai user create garda customer pani banau ko lagi ho
def customer_profile(sender, instance, created, **kwargs):
if created:
# user register bhayepaxi kun group ma halni bhanna ko lagi-->admin or customer banaune
group = Group.objects.get(name='customer')
instance.groups.add(group)
customer.objects.create(
user=instance,
name=instance.username,
)
print('Profile created!')
post_save.connect(customer_profile, sender=User)
from django.utils.timezone import now
Timestamp = models.DateTimeField(default=now)
<input type="hidden" name="postsno" value="{{blog.sno}}" />
<input type="hidden" name="parentsno" value="{{comments.sno}}" />
<input type="submit" value="submit" class="btn btn-primary" />
reply comment scenario....
# for reply
replyDict = {}
for reply in replies:
if reply.parent.sno not in replyDict.keys():
replyDict[reply.parent.sno] = [reply]
else:
replyDict[reply.parent.sno].append(reply)
templatestags for replays:
from django import template
register = template.Library()
@register.filter(name="get_val")
def get_val(dict,key):
return dict.get(key)
for makeing social icon at fix position
.icon-bar {
position: fixed;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}
{% load humanize %}
{{comments.Timestamp|naturaltime}}
comments:
<!-- comments starts -->
<div class="form-group container">
{% if request.user.is_authenticated %}
<form action="{%url 'postcomment'%}" method="POST">
{% csrf_token %}
<label for="comment">Post your comments:</label>
<input type="text" class="form-control" name="comment" placeholder="Enter your comment here." /><br />
<input type="hidden" name="postsno" value="{{blog.sno}}" />
<input type="hidden" name="parentsno" value="" />
<input type="submit" value="submit" class="btn btn-primary" />
</form>
{% else %}
<p>Login required to post a comment!</p>
{% endif %}
</div>
<div class="container">
<h3 class="my-3">Comments({{comments.count}})</h3>
{% for comments in comments %}
<div class="row mx-0">
<div class="col-1 col-sm-1 col-md-1 mx-0">
<img src="{%static 'images/profile.png'%}" class="rounded w-100" />
</div>
<!-- added humanize in seeting and naturaltime in timestamp -->
<div class="col-11 col-sm-11 col-md-11 mx-0 mb-3">
<b>{{comments.user}}</b>
<span class="badge badge-secondary">{{comments.Timestamp|naturaltime}}</span>
<br />
{{comments.comment}}<br>
{% comment %} for reply section {% endcomment %}
{% if request.user.is_authenticated %}
<span><a data-toggle="collapse" href="#collapseExample" data-target="#reply{{comments.sno}}" role="button"
aria-expanded="false" aria-controls="collapseExample">
Reply</span>
</a><br />
{% comment %} Used collapse link: jun parent post ma click garyo teskai ma matra reply khulxa
{% endcomment %}
<div class="collapse" id="reply{{comments.sno}}">
<div class="card card-body">
<form action="{%url 'postcomment'%}" method="POST">
{% csrf_token %}
<label for="comment">Post your Reply:</label>
<input type="text" class="form-control" name="comment" placeholder="Enter your reply here." /><br />
<input type="hidden" name="postsno" value="{{blog.sno}}" />
<input type="hidden" name="parentsno" value="{{comments.sno}}" />
<input type="submit" value="submit" class="btn btn-primary" />
</form>
</div>
</div>
{% else %}
<span><a data-toggle="collapse" href="#collapseExample" data-target="#reply{{comments.sno}}" role="button"
aria-expanded="false" aria-controls="collapseExample" disabled>
Login to Reply</span>
</a><br />
{% endif %}
<div class="replies my-2">
{% comment %} get_val chai custome template tag ho {% endcomment %}
{% for reply in replyDict|get_val:comments.sno %}
<div class="row my-3 mx-0 ">
<div class="col-1 pd-3">
<img src="{%static 'images/profile.png'%}" class="rounded mx-0 w-100" />
</div>
<div class="col-11 pd-3 mx-0">
<b>{{comments.user}}</b>
<span class="badge badge-secondary">{{comments.Timestamp|naturaltime}}</span><br>
<span class="">{{reply.comment}} </span>
<br />
</div>
</div>
{% endfor %}
</div>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
.............................................
from django.db import models
from django.contrib.auth.models import (
BaseUserManager,
AbstractBaseUser,
)
# Create your models here.
class UserManager(BaseUserManager):
def create_user(self, email, password=None):
"""
Creates and saves a User with the given email and password.
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
)
user.set_password(password)
user.save(using=self._db)
return user
def create_staffuser(self, email, password):
"""
Creates and saves a staff user with the given email and password.
"""
user = self.create_user(
email,
password=password,
)
user.staff = True
user.save(using=self._db)
return user
def create_superuser(self, email, password):
"""
Creates and saves a superuser with the given email and password.
"""
user = self.create_user(
email,
password=password,
)
user.staff = True
user.admin = True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
is_active = models.BooleanField(default=True)
staff = models.BooleanField(default=False) # a admin user; non super-user
admin = models.BooleanField(default=False) # a superuser
doctor = models.BooleanField(default=False) # a superuser
# notice the absence of a "Password field", that is built in.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = [] # Email & Password are required by default.
def get_full_name(self):
# The user is identified by their email address
return self.email
def get_short_name(self):
# The user is identified by their email address
return self.email
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
@property
def is_staff(self):
"Is the user a member of staff?"
return self.staff
@property
def is_admin(self):
"Is the user a admin member?"
return self.admin
objects = UserManager()
................
from django.db import models
from account.models import User
class Receptionist(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='receptionist')
name = models.CharField(max_length=100, blank=True, null=True)
address = models.CharField(max_length=100, blank=True, null=True)
phone = models.CharField(max_length=100, blank=True, null=True)
joined_on = models.DateField(auto_now_add=True)
class Doctor(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='doctors')
name = models.CharField(max_length=100, blank=True, null=True)
address = models.CharField(max_length=100, blank=True, null=True)
contact = models.CharField(max_length=100, blank=True, null=True)
specialist = models.CharField(max_length=100, blank=True, null=True)
joined_on = models.DateField(auto_now_add=True)
class Patient(models.Model):
name = models.CharField(max_length=200, blank=True, null=True)
address = models.CharField(max_length=200, blank=True, null=True)
phone = models.CharField(max_length=200, blank=True, null=True)
illness = models.CharField(max_length=200, blank=True, null=True)
symptoms = models.CharField(max_length=300, blank=True, null=True)
assigned_doctor = models.ForeignKey(Doctor, on_delete=models.SET_NULL, blank=True, null=True, related_name='assigned_doctor')
checked_up = models.DateField(auto_now=True)
# Create your models here.
.....
from dataclasses import fields
from pyexpat import model
from unicodedata import name
from wsgiref.validate import validator
from rest_framework import serializers
from .models import Doctor, Patient, Receptionist
from account.models import User
def phonenumber_validation(value):
if '+977' in value or len(value)>14 or '9' in value:
pass
else:
raise serializers.ValidationError('Invalid Phonenumber')
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
exclude = ['password',]
class ReceptionistSerializer(serializers.ModelSerializer):
name = serializers.CharField(max_length=200)
address = serializers.CharField(max_length=200)
phone = serializers.CharField(max_length=14, validators=[phonenumber_validation])
class Meta:
model = Receptionist
fields = ['name','address','phone','joined_on']
class DoctorSerializer(serializers.ModelSerializer):
name = serializers.CharField(max_length=200)
address = serializers.CharField(max_length=200)
contact = serializers.CharField(max_length=14, validators=[phonenumber_validation])
specialist = serializers.CharField(max_length=200)
class Meta:
model = Doctor
fields = ['name','address','contact','specialist','joined_on']
class PatientSerializer(serializers.ModelSerializer):
class Meta:
model = Patient
fields = '__all__'
......
from django.urls import include, path
from .views import *
urlpatterns = [
path('receptionist/', ReceptionistAPIView.as_view(), name='receptioonist'),
path('doctor/', DoctorAPIView.as_view(), name='doctor'),
path('patient/', PatientAPIView.as_view(), name='patient'),
path('patient/<int:id>/', PatientRudView.as_view(), name='patientrud'),
path('login/', LoginView.as_view(), name='login'),
......
import email
from rest_framework.response import Response
from rest_framework import (
generics,
permissions,
status,
)
from rest_framework.views import APIView
from .models import Receptionist, Patient, Doctor
from .serializers import UserSerializer, DoctorSerializer, PatientSerializer, ReceptionistSerializer
from datetime import datetime, timedelta
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework.views import APIView
from django.contrib.auth import get_user_model
User = get_user_model()
class UserAPIView(generics.ListCreateAPIView):
serializer_class = UserSerializer
permissions_classes = (permissions.AllowAny,)
def get_queryset(self):
return User.objects.all()
def post(self, request):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.save()
refresh = RefreshToken.for_user(user)
token = str(refresh.access_token)
return Response(serializer.data, status=status.HTTP_201_CREATED)
class ReceptionistAPIView(generics.ListCreateAPIView):
serializer_class = ReceptionistSerializer
permissions_classes = (permissions.AllowAny,)
def get_queryset(self):
if self.request.user.is_superuser:
return Receptionist.objects.all()
def post(self, request):
serializer = self.serializer_class(data=request.data)
data = request.data
serializer.is_valid(raise_exception=True)
user = User.objects.create(email=data.get('email'))
user.set_password(data.get('password'))
user.staff = True
user.save()
serializer.save(user=user)
refresh = RefreshToken.for_user(user)
token = str(refresh.access_token)
return Response(serializer.data, status=status.HTTP_201_CREATED)
class DoctorAPIView(generics.ListCreateAPIView):
serializer_class = DoctorSerializer
permissions_classes = (permissions.AllowAny,)
def get_queryset(self):
if self.request.user.is_superuser or self.request.user.staff == True:
return Doctor.objects.all()
def post(self, request):
serializer = self.serializer_class(data=request.data)
data = request.data
serializer.is_valid(raise_exception=True)
user = User.objects.create(email=data.get('email'))
user.set_password(data.get('password'))
user.doctor = True
user.save()
serializer.save(user=user)
refresh = RefreshToken.for_user(user)
print("refresh", refresh)
token = str(refresh.access_token)
print("access", token)
return Response(serializer.data, status=status.HTTP_201_CREATED)
class PatientAPIView(generics.ListCreateAPIView):
serializer_class = PatientSerializer
permissions_classes = (permissions.IsAuthenticated,)
def get_queryset(self):
if self.request.user.is_superuser or self.request.user.staff == True:
return Patient.objects.all()
else:
return Patient.objects.filter(assigned_doctor=self.request.user)
def post(self, request):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
class PatientRudView(generics.RetrieveUpdateDestroyAPIView):
lookup_field = 'id' # slug, id # url(r'?P<pk>\d+')
serializer_class = PatientSerializer
permission_classes = [permissions.IsAuthenticated]
def get_queryset(self):
return Patient.objects.all()
def get_serializer_context(self, *args, **kwargs):
if self.request.user.staff == True:
id = self.kwargs['id']
data = self.request.data
if Patient.objects.filter(id=id).exists():
patient = Patient.objects.get(id=id)
if data.get('name') is not None:
patient.name=data.get('name')
if data.get('address') is not None:
patient.address=data.get('address')
if data.get('phone') is not None:
patient.phone=data.get('phone')
if data.get('illness') is not None:
patient.illness=data.get('illness')
if data.get('symptoms') is not None:
patient.symptoms=data.get('symptoms')
if data.get('assigned_doctor') is not None:
if Doctor.objects.filter(id=data.get('assigned_doctor')).exists():
patient.assigned_doctor=Doctor.objects.get(id=data.get('assigned_doctor'))
patient.save()
else:
return Response({"message":"You are not Receptionist"}, status=401)
class LoginView(APIView):
permission_classes = [permissions.AllowAny]
def post(self, request, format=None):
data = request.data
email = data.get('email', None)
password = data.get('password', None)
user = User.objects.get(email=email.lower())
if user is None:
raise AuthenticationFailed('User not found!')
if not user.check_password(password):
raise AuthenticationFailed('Wrong password!')
refresh = RefreshToken.for_user(user)
token = str(refresh.access_token)
# token = jwt.encode(payload, 'secret', algorithm='HS256').decode('utf-8')
response = Response()
response.set_cookie(key='jwt', value=token, httponly=True)
response.data = {
'userfield': email,
'token': token,
}
return response
...................................
yml github ci-cd for react with vite
name: Build and Deploy React App via FTP
on:
push:
branches: [master]
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
# This workflow contains a single job called "build-and-deploy"
build-and-deploy:
# The type of runner that the job will run on
runs-on: ubuntu-latest
# Steps represent a sequence of tasks that will be executed as apart of the job
steps:
# checks-out your respotory under $GITHUB_WORKSPACE, so your job can access it
- name: Checkout code
uses: actions/checkout@v2
# Runs a set of commands using the runners shell
- name: Run react build script
run: yarn && yarn build
env:
CI: false # if any warning push would be stop
- name: FTP-Deploy-Action
uses: SamKirkland/[email protected]
with:
server: ftp.namankhabar.com
username: [email protected]
password: O7mk(yI{O#z=
local-dir: dist/ React:
import axios from 'axios';
const handleRegister = async () => {
const data = {
customer_id: "12345",
customer_name: "John Doe",
access_code: "abc123"
};
try {
const response = await axios.post('http://127.0.0.1:8000/register', data, {
headers: {
'Content-Type': 'application/json'
}
});
console.log(response.data);
} catch (error) {
console.error(error.response ? error.response.data : error.message);
}
};
responses_collection = db.mongo_db['DynamicSurveyResponses']
total_completed = await responses_collection.count_documents({"study_id": study_id})
important links collections
https://imgur.com/meme-generator
https://imgur.com/upload
https://postimages.org/
https://postimages.org/
https://www.filestack.com/products/file-upload/
https://idx.google.com/
flutter build apk
https://studio.firebase.google.com/
https://calendly.com/bishworajpoudelofficial/
https://app.pictory.ai/
https://github.com/10manik01/stdmanagement_flaskapp
https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.3
https://dev.to/adamghill/python-package-manager-comparison-1g98
https://pentester.com/
How to expands row and colums in excel
1. select all the row and columns to be expand Ctrl + All
2.Alt + H + O +I // width autot;
3.Alt + H + O + A // height auto
4.Ctrl + Thow to take full screenshot of any website
1.inspect the website
2.ctr+shift+p
3.Command will be open then enter
screenshot then select capture full size screenshot
4.then it will downlaod the full screenshot
syntax: https://placehold.co/widthxheight/bg_hex_color/text_hex_color/image_format
https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests
https://placehold.co/600x400/pnf/000000/FFF
<img src="c" alt="Hero Banner" class="rounded-lg shadow-lg mb-8 w-full object-cover h-64">
https://source.unsplash.com/1600x400/?technology,developer
https://placehold.co/
https://source.unsplash.com/1600x400/?technology,developer
In ths Mongodb atlast database access like this:
db['DynamicSurvey'].find()
db["Customer_Member"].count_documents(find({"email":/amritpanta/}))
count = db["Customer_Member"].count_documents({ "email": { "$regex": "amritpanta" } })
count_documents
const count = await db.collection("Customer_Member").countDocuments({ email: /amritpanta/ });
@field_validator("interview_language", mode="before")
@classmethod
def parse_interview_language(cls, v):
if isinstance(v, list):
# Convert to dict assuming it's just the language name in a list
return {
"language": v[0] if v else "English",
"voice": "alloy",
"voice_region": "United States",
"voice_accent": "General American"
}
return v
point t be noticed:
1.from dotenv import load_dotenv
load_dotenv()
2.from pydantic import StrPath
3.
## Testing on ngrok. Assumes port number 3200 . Check this for details , this steps needs an ngrok account setup https://dashboard.ngrok.com/get-started/setup
ngrok http 3200
.........................
import uuid
unique_id = uuid.uuid4().hex # This removes hyphens automatically
.......................
.isoformat()
(method) def isoformat(
sep: str = ...,
timespec: str = ...
) -> str
Return the time formatted according to ISO.
The full format looks like 'YYYY-MM-DD HH:MM:SS.mmmmmm'.
By default, the fractional part is omitted if self.microsecond == 0.
If self.tzinfo is not None, the UTC offset is also attached, giving
giving a full format of 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM'.
Optional argument sep specifies the separator between date and
time, default 'T'.
The optional argument timespec specifies the number of additional
terms of the time to include. Valid options are 'auto', 'hours',
'minutes', 'seconds', 'milliseconds' and 'microseconds'.
mongodb database
1.https://account.mongodb.com/account/login?nds=true
mongodb+srv://<username>:<password>@<mongodb_uri>/?retryWrites=true&w=majority&appName=devDB
You need to secure your MongoDB Atlas cluster before you can use it. Set which users and IP addresses can access your cluster now. Read more
Add a connection IP address
Your current IP address (27.34.73.149) has been added to enable local connectivity. Only an IP address you add to your Access List will be able to connect to your project's clusters. Add more later in Network Access.
Create a database user
A database user has been added to this project. Create another user later in Database Access.
You'll need your database user's credentials in the next step.
https://www.streamingmediablog.com/2023/07/microsoft-retires-media-services.html
https://qualzstudydatastorage.blob.core.windows.net/mediatest/6800abdd3fe97e624a0b0094/test1/video/test1_0.webm
https://azure.microsoft.com/en-us/pricing/details/media-services/
https://learn.microsoft.com/en-us/previous-versions/azure/media-services/latest/
https://azure.microsoft.com/en-us/products/#media
https://learn.microsoft.com/en-us/previous-versions/azure/media-services/latest/
https://learn.microsoft.com/en-us/previous-versions/azure/media-services/latest/player-media-players-concept
https://github.com/supabase/supabase-py
############################### Important concept that i learn in python today #############################
1.to check the whether key is presence or not in the dictionay
if 'key' in dictionaty:
pass
2.importance of isinstance() function
example: isinstance('abc',str)
print(isinstance('abc',(dict,int)))
3 importance of any() and all() function
4Converts the result to a True or False value
example: bool('hello')-> True
bool('')->False
bool(1) -> True
bool(0) - > False
print(bool([])) - False
print(bool(['1','2'])) - True
print(bool({})) - False
print(bool({'1':'2'})) - True
5.learn about regular expression
re.fullmatch(r"[a-f0-9]{24}", val)
6.load balancing,celery,redis,kafka,websocker,throttling,rate limit,pagination,
7.
8.
9.
10.
study_cursor = db.mongo_db["Qualitative_Studies"].find()
qualitative_studies = await study_cursor.to_list(length=None)
await db.mongo_db["Qualitative_Studies"].update_one(
{"_id": item["_id"]},
{"$set": update_fields}
)
class Section(BaseModel):
id: str = Field(default_factory=random_object_id)
section_title: str
section_index: int
questions: list[Question]
@root_validator(pre=True)
def enforce_object_id(cls, values):
if not is_object_id(values.get("id", "")):
values["id"] = random_object_id()
return values
@root_validator(pre=True) allows you to inspect and modify input before model validation happens.
We check if the provided id is not a valid ObjectId, and if not, we generate a new one.
This ensures every section and question always ends up with a proper MongoDB-style ObjectId, even if the LLM gives junk values like 1.1 or question-3.
# Find Qualitative_Items doc
# await db.mongo_db["Qualitative_Items"].update_one(
# {"study_id": study_id, "participant_id": participant_id},
# {
# "$setOnInsert": {
# "study_id": study_id,
# "participant_id": participant_id,
# # include other default fields if needed
# }
# },
# upsert=True
# )
await db.mongo_db["Qualitative_Items"].update_one(
{"study_id": study_id, "participant_id": participant_id},
{
"$setOnInsert": {
"study_id": study_id,
"participant_id": participant_id,
# include other default fields if needed
}
},
upsert=True
)
application/bond-compact-binary
git checkout -b feat-vtv-sharing origin/feat-vtv-sharing
https://shields.io/
<div align="center">
<br />
<a href="https://www.youtube.com/watch?v=8GK8R77Bd7g" target="_blank">
<img src="https://github.com/user-attachments/assets/1c0131c7-9f2d-4e3b-b47c-9679e76d8f9a" alt="Project Banner">
</a>
<br />
<div>
<img src="https://img.shields.io/badge/-Next.JS-black?style=for-the-badge&logoColor=white&logo=nextdotjs&color=black" alt="next.js" />
<img src="https://img.shields.io/badge/-Vapi-white?style=for-the-badge&color=5dfeca" alt="vapi" />
<img src="https://img.shields.io/badge/-Tailwind_CSS-black?style=for-the-badge&logoColor=white&logo=tailwindcss&color=06B6D4" alt="tailwindcss" />
<img src="https://img.shields.io/badge/-Firebase-black?style=for-the-badge&logoColor=white&logo=firebase&color=DD2C00" alt="firebase" />
</div>
<h3 align="center">Prepwise: A job interview preparation platform powered by Vapi AI Voice agents</h3>
## ???? <a name="table">Table of Contents</a>
1. ???? [Introduction](#introduction)
2. ?? [Tech Stack](#tech-stack)
3. ???? [Features](#features)
4. ???? [Quick Start](#quick-start)
5. ????? [Snippets (Code to Copy)](#snippets)
6. ???? [Assets](#links)
7. ???? [More](#more)
## <a name="introduction">???? Introduction</a>
**Authentication**
```bash
git clone https://github.com/adrianhajdin/ai_mock_interviews.git
cd ai_mock_interviews
```
**Installation**
Install the project dependencies using npm:
```bash
npm install
```
`.env.local`
```env
NEXT_PUBLIC_VAPI_WEB_TOKEN=
NEXT_PUBLIC_VAPI_WORKFLOW_ID=
```
Replace the placeholder values with your actual **[Firebase](https://firebase.google.com/)**, **[Vapi](https://vapi.ai/?utm_source=youtube&utm_medium=video&utm_campaign=jsmastery_recruitingpractice&utm_content=paid_partner&utm_term=recruitingpractice)** credentials.
<details>
<summary><code>globals.css</code></summary>
```css
@import "tailwindcss";
@plugin "tailwindcss-animate";
@custom-variant dark (&:is(.dark *));
@theme {
--color-success-100: #49de50;
--color-success-200: #42c748;
--font-mona-sans: "Mona Sans", sans-serif;
--bg-pattern: url("/pattern.png");
}
:root {
--radius: 0.625rem;
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
}
```
</details>
- [Git](https://git-scm.com/)
- [Node.js](https://nodejs.org/en)
- [npm](https://www.npmjs.com/) (Node Package Manager)
https://mail.google.com/mail/u/0/#search/from%3Anotifications%40stripe.com
in mail search bar
from:[email protected]
sudo apt update
sudo apt install portaudio19-dev
https://www.freecodecamp.org/news/how-do-zsh-configuration-files-work/
https://github.com/openai/openai-python
https://github.com/openai/openai-python/blob/main/api.md
