How to set repeat interval time in background-tasks using django? - django

I tried to run the background task code in Django. its working fine but interval time is not working. it working every second how to fix it anyone gives some solution.
views.py
from django.shortcuts import render
from django.http import HttpResponse
from background_task import background
from django.core.mail import send_mail
#background(schedule=5)
def hello():
print('hello_world')
# Create your views here.
def index(request):
hello()
return HttpResponse('<h1> Hello World </h1>')
I tried to pass repeat parameter also
from django.shortcuts import render
from django.http import HttpResponse
from background_task import background
from django.core.mail import send_mail
#background(schedule=5)
def hello():
print('hello_world')
# Create your views here.
def index(request):
hello(repeat=10)
return HttpResponse('<h1> Hello World </h1>')
I tried many ways. But still is not working.I need every One hour to print hello world.

Related

Django - Whatsapp Sessions for scheduled messages

I'm developing a system where users, in addition to all the bureaucratic part, can register their clients' whatsapp so that automatic billing messages, congratulations, etc. are sent. Where the user would read the QR code and the system would be in charge of sending messages over time, using the user's whatsapp, thus opening a user<-> clinet conversation. I'm dividing this problem into parts, for now I'm trying to read the Whatsapp Web Qr Code and display it in a template. This is already happening. The problem is that the webdriver is terminated first, as soon as the image is returned to the template, then the session cannot be validated. The webdriver remains open forever, or closes before the image is sent to the template, the image needs to go to the template via return (or another way) and the webdriver remains active for a while. How to solve this concurrent task?
# views.py
from django.shortcuts import render
from django.http import HttpResponse
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import base64
import time
from django.shortcuts import render
def read_qr_code(request):
driver = webdriver.Firefox()
# driver.implicitly_wait(30) # mantém o webdriver ativo por 2 minutos
driver.get('https://web.whatsapp.com/')
wait = WebDriverWait(driver, 10)
qr_element = wait.until(EC.presence_of_element_located((By.XPATH, '//*[#id="app"]/div/div/div[3]/div[1]/div/div/div[2]/div/canvas')))
qr_image_binary = qr_element.screenshot_as_png
qr_image_base64 = base64.b64encode(qr_image_binary).decode('utf-8')
context = {
'image_data': qr_image_base64
}
# send_qr(request, context)
# time.sleep(20) # aguarda por 2 minutos
# driver.quit() # fecha o webdriver
return render(request, 'read_qr_code.html', context)
I solved this problmes using Threds, the code is.
# views.py
from django.shortcuts import render
from django.http import HttpResponse
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import base64
import time
from django.shortcuts import render
import threading
def quit_driver_thread():
time.sleep(40)
driver.quit()
def read_qr_code(request):
global driver
driver = webdriver.Firefox()
driver.implicitly_wait(120)
driver.get('https://web.whatsapp.com/')
wait = WebDriverWait(driver, 10)
qr_element = wait.until(EC.presence_of_element_located((By.XPATH, '//*[#id="app"]/div/div/div[3]/div[1]/div/div/div[2]/div/canvas')))
qr_image_binary = qr_element.screenshot_as_png
qr_image_base64 = base64.b64encode(qr_image_binary).decode('utf-8')
context = {
'image_data': qr_image_base64
}
thread = threading.Thread(target=quit_driver_thread)
thread.start()
return render(request, 'read_qr_code.html', context)

Django dev server using old version of views.py

For some reason, the changes I make on the views.py file are not being reflected. I initially made a function inside view.py to return HttpResponse(request.POST.items()). Even after making changes to the function, it's still performing the same thing. I tried clearing the cache of the browser, restarted the server, and also tried deleting the pyc files. Nothing worked. Any guess on why this is happening?
urls.py
from . import views
urlpatterns = [
path('',views.index, name='index'),
path('proceedaction/<str:pk>/',views.ProceedAction.as_view(),name='proceedaction'),
path('uploadct/<str:pk>/',views.UploadCT.as_view(),name='uploadct'),
]
views.py
from django.shortcuts import render,redirect
from django.views import View
from .models import CreatePatient,PatientRecord,FileData
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from .filters import RecordFilter
from django.http import HttpResponse
import json
# Create your views here.
def index(request):
return render(request,'index.html')
class UploadCT(View,LoginRequiredMixin):
def get(self,request,pk):
records = PatientRecord.objects.filter(id=pk)
context={
'record' : records,
}
return render(request,'ct_upload.html',context=context)
def post(self,request):
dbdata = FileData()
return redirect('index')
I had not specified method=POST in the corresponding HTML file. Solved this issue by doing that.

Can I print just the content of a html template in django?

I am using Django with python to create a web application, I am a beginner in this. I hope that you can help me.
I want to print this page by clicking a button.
Now, I am just trying to generate the pdf first.
I want just to print the content, like that
I tried these functions.
#views.py
from django.views.generic.detail import DetailView
from MagasinProject.views import PdfMixin
from MagasinProject.utils import generate_pdf, render_to_pdf_response, pdf_decorator
from django.contrib.auth.models import User
from django.shortcuts import render
def test_view(request):
resp = HttpResponse(content_type='application/pdf')
result = generate_pdf('demande/demande.html', file_object=resp)
return result
#urls.py
from django.urls import path
from . import views
from django.conf.urls import url
urlpatterns=[
path('demande',views.index, name='demande'),
url(r'^test_view$', views.test_view),
]
This is what I got
You can print the HTML page with a print button like this (see w3schools):
<button onclick="window.print()">Print this page</button>

How to insert seperate Python scripts in Django

I have created a webscraper in Python and now I want to insert this file into my views.py and execute them using the HTML button created on the HTML page.
My scraper name is maharera.py and it is saved in same folder where I have saved views.py
My views.py looks like this:
from django.shortcuts import render
from django.conf.urls import url
from django.conf.urls import include
from django.http import HttpResponse
# Create your views here.
def index(request):
first = {"here":"will enter more details"}
return render(request, "files/first-page.html", context=first)
#return HttpResponse("<em>Rera details will be patched here</em>")
After inserting it in views.y I want to execute that file using html HTML I created. How can I do that?
Actual answer to question
Lets say the contents of maharera.py are as follows
def scraper(*args, **kwargs):
#the scraper code goes here
then you'll need to import it as follows in the views.py file
from django.shortcuts import render
from django.conf.urls import url
from django.conf.urls import include
from django.http import HttpResponse
# Create your views here.
import maharera
def index(request):
first = {"here":"will enter more details"}
return render(request, "files/first-page.html", context=first)
#return HttpResponse("<em>Rera details will be patched here</em>")
def scraper_view(request):
maharera.scraper()
return HttpResponse("<em>Scraper started</em>")
It is advisable to not run a web scraper through a http requests like these. Http requests are supposed to return response within fraction of seconds and should not take long.
When you hit scraper_view it will start executing the code inside it. In scraper view, there is call to the scraper and we don't know how long will it take for that function to end. Till that function doesn't end, the response of the page will not be returned to the user.
For such long running tasks, you should look into task queues.
Looking into celery

Following django form submission, redirect to page using newly created pk

I am trying to redirect the user to edit details of a task after task submission, but am having troubles redirecting to a page based on the newly created pk. Each view works without the return HttpResponseRedirect line. I have also tried arge=(instance.id) and kwargs=(instance.id) for the variable.
views.py
...
from django.http import HttpResponseRedirect, HttpResponseServerError, HttpResponseForbidden, Http404, HttpResponse
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response, get_object_or_404,render
...
def new_task(request):
...
...
task.save()
instance = task.save()
return HttpResponseRedirect(reverse('task_values', instance.id))
def task_values(request, task_id):
...
urls.py
from django.conf.urls.defaults import patterns, include, url
from django.http import HttpResponseRedirect
from django.views.generic.simple import direct_to_template
urlpatterns += patterns('core.views_entry',
#Task viewing/editing
(r'^task/(?P<task_id>\d+)/$','task_values'),
(r'^enter/$','new_task'),
return HttpResponseRedirect(reverse('task_values', kwargs={'task_id': instance.id}))
Also note that you don't need to save the task twice.
Edit OK, there's another problem. You haven't given your URLs specific names, which means that the only way to identify them is to pass the fully qualified view name:
reverse('core.views_entry.task_values', kwargs=...)
Or, better, use the the url() function to name your URL:
url(r'^task/(?P<task_id>\d+)/$','task_values', name='task_values'),
and you can use the original version I gave above.
Note that the error isn't telling you it's going to enter/<id>/, just that in that view it's trying to create the reverse URL for the redirection and failing.