django api throwing 500(internal server) error with connection to mysql - django

I get 500(Internal Server Error) for the below code, cant able to identify the problem. Please help me
urls.py
from django.conf.urls import url
from .audfile import daywisedetail,hourwisedetail
urlpatterns = [
url(r'^pyapi/api/daywise/(?P<start_date>[\w-]+)/(?P<end_date>[\w-]+)/$',daywisedetail.as_view()),
url(r'^pyapi/api/hourwise/(?P<start_date_val>[\w-]+)/(?P<end_date_val>[\w-]+)/$',hourwisedetail.as_view()),
]
audfile.py
from rest_framework.views import APIView
from django.http import JsonResponse
from django.http import HttpResponse
from django.shortcuts import render
from django.views.generic import View
from django.template.loader import get_template
from rest_framework.response import Response
from rest_framework import status
import MySQLdb
sdatabase = MySQLdb.connect(host="localhost",user="root",passwd="password",db="main")
class daywisedetail(APIView):
def get(self,request,start_date=None,end_date=None,format=None):
db = sdatabase
cursor = db.cursor()
daydetail = """select id, values, name, email from day_users where date(reg_date) between '%s' and '%s' """ % (start_date,end_date)
cursor.execute(daydetail)
getdaydetailresult = cursor.fetchall()
mainlist=[]
for v0 in getdaydetailresult:
for v1 in v0:
mainlist.append(v1)
data = {
"hours": mainlist
}
return Response(data)
class hourwisedetail(APIView):
def get(self,request,start_date_val=None,end_date_val=None,format=None):
db = sdatabase
cursor = db.cursor()
hourwisedata = """select id, values, name, email from hour_users where date(reg_date) between '%s' and '%s' """ % (start_date_val,end_date_val)
cursor.execute(hourwisedata)
hourwisedataresult = cursor.fetchall()
mainlist1=[]
for v2 in hourwisedataresult:
for v3 in v2:
mainlist1.append(v3)
data1 = {
"days": mainlist1
}
return Response(data1)
If i have single class(daywisedetail), api is working properly, if i am adding second class(hourwisedetail), both the apis are showning 500 responce.
cant able to find where is the bug, please help me.

Related

Error in authenticate a websocket with token authentication on django channels?

I face an error when calling the websocket url with passing a JWT token for authentication purpose:
my websocket request is:
ws://127.0.0.1:8000/chat/chat_2/?token=
the error is:
raise ValueError("No route found for path %r." % path)
ValueError: No route found for path 'chat/chat_2/'.
I'm using a custom authentication middleware:
middleware.py
"""
General web socket middlewares
"""
from channels.db import database_sync_to_async
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser
from rest_framework_simplejwt.exceptions import InvalidToken, TokenError
from rest_framework_simplejwt.tokens import UntypedToken
from rest_framework_simplejwt.authentication import JWTTokenUserAuthentication
from channels.middleware import BaseMiddleware
from channels.auth import AuthMiddlewareStack
from django.db import close_old_connections
from urllib.parse import parse_qs
from jwt import decode as jwt_decode
from django.conf import settings
from django.contrib.auth import get_user_model
User = get_user_model()
#database_sync_to_async
def get_user(validated_token):
try:
user = get_user_model().objects.get(id=validated_token["user_id"])
print(f"{user}")
return user
except User.DoesNotExist:
return AnonymousUser()
class JwtAuthMiddleware(BaseMiddleware):
def __init__(self, inner):
self.inner = inner
async def __call__(self, scope, receive, send):
# Close old database connections to prevent usage of timed out connections
close_old_connections()
# Get the token
token = parse_qs(scope["query_string"].decode("utf8"))["token"][0]
# Try to authenticate the user
try:
# This will automatically validate the token and raise an error if token is invalid
UntypedToken(token)
except (InvalidToken, TokenError) as e:
# Token is invalid
print(e)
return None
else:
# Then token is valid, decode it
decoded_data = jwt_decode(
token, settings.SECRET_KEY, algorithms=["HS256"]
)
print(decoded_data)
# Get the user using ID
scope["user"] = await get_user(validated_token=decoded_data)
return await super().__call__(scope, receive, send)
def JwtAuthMiddlewareStack(inner):
return JwtAuthMiddleware(AuthMiddlewareStack(inner))
routing.py:
from . import consumers
from django.urls.conf import path
websocket_urlpatterns = [
path("ws/chat/<str:room_name>/", consumers.ChatConsumer.as_asgi()),
path(
"ws/personal_chat/<str:room_name>/",
consumers.PersonalConsumer.as_asgi(),
),
]
asgi.py:
import os
import ChatApp.routing
from django.core.asgi import get_asgi_application
django_asgi_app = get_asgi_application()
from ChatApp.middlewares import JwtAuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Hookax.settings")
application = ProtocolTypeRouter(
{
"http": django_asgi_app,
"websocket": JwtAuthMiddlewareStack(
URLRouter(ChatApp.routing.websocket_urlpatterns)
),
}
)
The project based on:
Django 3.2.7
Channels 3.0.4
Any suggestions solution?

How to upload file on Django REST endpoint quickly?

I am using Django REST framework to upload a large csv file and extract the data from the file and save the data in the data. By large file I mean file of like 10 to 50mb but when I upload a file its taking way longer then expected like 10 to 15mins but the endpoint keeps on processing and does not returns the response here is how my views.py looks like:
from asyncore import read
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework.response import Response
import pandas as pd
from .models import ExtractedData
from .urls import urlpatterns
from django.urls import path
# Create your views here.
class FileUploadView(APIView):
parser_classes = ( MultiPartParser, FormParser)
def put(self, request, format=None):
file_obj = request.FILES['file']
df = pd.read_csv(file_obj)
dict_data = df.to_dict(orient='records')
for dict in dict_data:
ExtractedData.objects.get_or_create(data=dict)
return Response({'details':"File Saved Succesfully"}, status=204)

pdfkit django in digitalocean

pdfkit works in the local machine everything works successfully displays as pdf, but in digitalocean sends to the server error 500, why?
views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse
from django.template.loader import get_template
import pdfkit
from .models import Buses
def pdf(request, id):
bus = Buses.objects.get(id=id)
template = get_template('buses/pdf.html')
html = template.render({'bus': bus})
options = {
'page-size': 'Letter',
'encoding': "UTF-8",
}
pdf = pdfkit.from_string(html, False, options)
response = HttpResponse(pdf, content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="{}_{}.pdf"'.format(bus.company, bus.name)
return response
If your template references other files, you may need to set 'enable-local-file-access': True in your options.
See: https://github.com/wkhtmltopdf/wkhtmltopdf/issues/4460
I am not sure but your problem could be the location of wkhtmltopdf
It is always a better option to specify the wkhtmltopdf location. So on your digital ocean server - start by installing wkhtmltopdf - if you dont have it yet.
This is a great tutorial to use for any version of Ubuntu - https://computingforgeeks.com/install-wkhtmltopdf-on-ubuntu-debian-linux/
Then on your command line:
which wkhtmltopdf
Note the location, your code will then look like this:
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse
from django.template.loader import get_template
import pdfkit
from .models import Buses
def pdf(request, id):
bus = Buses.objects.get(id=id)
template = get_template('buses/pdf.html')
html = template.render({'bus': bus})
options = {
'page-size': 'Letter',
'encoding': "UTF-8",
}
config = pdfkit.configuration(wkhtmltopdf='/usr/local/bin/wkhtmltopdf') #use your actual location here
pdf = pdfkit.from_string(html, False, configuration=config, options=options)
response = HttpResponse(pdf, content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="{}_{}.pdf"'.format(bus.company, bus.name)
return response

Does django server support url callbacks (webhooks)?

I am trying to implement url callbacks. And trying to test it. But seems like it is not working. I have been following this article for callbacks implementation.
I have defined two urls in urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^agent205', 'agent205.views.test'),
url(r'^agent206', 'agent205.views.test2'),
)
and their views in views.py
__author__ = 'rai'
from django.shortcuts import HttpResponse, render_to_response, render
from django.http.request import HttpRequest
import urllib, urllib2, json
from django.contrib.auth.decorators import login_required
import json
from rest_framework.views import APIView
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def test(request):
data = {'foo': 'bar', 'hello': 'world'}
print request.body
return HttpResponse(json.dumps(data), content_type='application/json')
#csrf_exempt
def test2(request):
return HttpResponse(json.dumps(request.body), content_type='application/json')
Then I test from postman like
I am getting HTTP 200 OK response instead of getting 202 Accepted. What should I do for callback to work? Or am I missing something
If your issue is to return a 202 HTTP status code instead of the default 200, you could try to use the status parameter as follows:
#csrf_exempt
def test(request):
data = {'foo': 'bar', 'hello': 'world'}
print request.body
return HttpResponse(json.dumps(data), content_type='application/json', status=202)

Custom template in django form wizard - NameError

I am trying to create custom templates for a simple contact form as per the django docs but I am getting a NameError. Looks like a simple issue but I can't figure it out. Any help will be greatly appreciated. The error message is:
"NameError at /contact/
name 'wizardcustomtemplate' is not defined"
where 'wizardcustomtemplate' is the app. Here is my code:
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
from wizardcustomtemplate.forms import SubjectForm, SenderForm, MessageForm
from wizardcustomtemplate.views import ContactWizard
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^contact/$', ContactWizard.as_view(FORMS)),
)
views.py
import os
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.core.mail import send_mail
from django.core.context_processors import csrf
from django.contrib.formtools.wizard.views import SessionWizardView
from django.contrib.formtools.wizard.views import WizardView
from django.core.files.storage import FileSystemStorage
from django.core.files import File
FORMS = [("0", wizardcustomtemplate.forms.SubjectForm),
("1", wizardcustomtemplate.forms.SenderForm),
("2", wizardcustomtemplate.forms.MessageForm)
]
TEMPLATES = {"0": "wizardcustomtemplate/subject.html",
"1": "wizardcustomtemplate/sender.html",
"2": "wizardcustomtemplate/message.html"
}
class ContactWizard(SessionWizardView):
def get_template_names(self):
return [TEMPLATES[self.steps.current]]
def done(self, form_list, **kwargs):
form_data = process_form_data(form_list)
return render_to_response('wizardcustomtemplate/thanks.html', {'form_data': form_data})
def process_form_data(form_list):
form_data = [form.cleaned_data for form in form_list]
return form_data
forms.py
from django import forms
class SubjectForm(forms.Form):
subject = forms.CharField(max_length = 100,initial='Wizard')
class SenderForm(forms.Form):
sender = forms.EmailField(initial='abcd#efgh.org')
class MessageForm(forms.Form):
message = forms.CharField(initial='How r u?')
The form wizard works fine if I don't use the custom templates (FORMS, TEMPLATES etc.) Please let me know if you need additional information.
Solved it by adding import wizardcustomtemplate in views.py as suggested by #Rohan.