Django Cron, execute def from views - python

I have a problem.
I needto implement a function that will be called cyclically
I have to call dashgenerate functions because it generates data records
this cron.py:
from django_cron import CronJobBase, Schedule
from django.shortcuts import get_object_or_404, render, redirect
from django.http import HttpResponse, HttpResponseRedirect, Http404
class MyCronJob(CronJobBase):
RUN_EVERY_MINS = 60
schedule = Schedule(run_every_mins=RUN_EVERY_MINS)
code = 'CRM.my_cron_job'
def do(self):
return redirect('dashboard/dashgenerate/')
dashgenerate is a def from another app in project:
def dashgenerate(request):
.....

Related

How to verify Shopify webhook in Django?

How can I verify the incoming webhook from Shopify? Shopify provides a python implementation (of Flask), but how can I do it in Django/DRF?
Set these two variables in the settings.py file
# settings.py
SHOPIFY_HMAC_HEADER = "HTTP_X_SHOPIFY_HMAC_SHA256"
SHOPIFY_API_SECRET = "5f6b6_my_secret"
Then, create a verify webhook function that accepts the Django request as it's parameter
# utils.py
import base64
import hashlib
import hmac
from django.conf import settings
from django.core.handlers.wsgi import WSGIRequest
def verify_shopify_webhook(request: WSGIRequest):
shopify_hmac_header = request.META.get(settings.SHOPIFY_HMAC_HEADER)
encoded_secret = settings.SHOPIFY_API_SECRET.encode("utf-8")
digest = hmac.new(
encoded_secret,
request.body,
digestmod=hashlib.sha256,
).digest()
computed_hmac = base64.b64encode(digest)
return hmac.compare_digest(computed_hmac, shopify_hmac_header.encode("utf-8"))
Then, create a view that accepts the incoming webhook and use the verify_shopify_webhook(...) function to verify the request.
# views.py
from django.http import HttpResponse
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from .utils import verify_shopify_webhook
#method_decorator(csrf_exempt, name="dispatch")
class ShopifyWebhookView(View):
def post(self, request, *args, **kwargs):
verified = verify_shopify_webhook(request=request)
return HttpResponse(status=200 if verified else 403)
If you're using Django REST Framework, you can also use APIView as
# views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from .utils import verify_shopify_webhook
class ShopifyWebhookView(APIView):
def post(self, request, *args, **kwargs):
verified = verify_shopify_webhook(request=request)
return Response(status=200 if verified else 403)

Django: Using decorators on methods in a subclass to handle requests from urls.py

I used to have some massive files with decorated funtions called from urls.py. This wasn't sustainable so they were split into controllers, with logic somewhere else (not relevant for this question). The controllers are subclassed from a main Controller class to share frequent imports and other commonalities.
I can't get the decorator functions to work now, the closest I've gotten are
AssertionError: The `request` argument must be an instance of `django.http.HttpRequest`, not `api.controllers.FooController.FooController`.
and
AttributeError: 'functools.partial' object has no attribute '__name__'
Neither using a get() with as_view() nor a custom method work, as seen below.
I've tried #method_decorator(login_required) etc. with no success.
My files (simplified) are below. Do not mind the method contents, this is just for demonstration.
api/urls.py:
from django.urls import path
from api.controllers.FooController import FooController
urlpatterns = [
path("get_foo", FooController,as_view(), name="get_foo")
path("get_bar", FooController.foo_bar, name="get_bar")
]
api/controllers/Controller.py:
from django.views import View
from rest_framework.authentication import SessionAuthentication, TokenAuthentication
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from django.http import HttpResponse, JsonResponse, StreamingHttpResponse
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
class Controller(View):
def __init__(self):
# Set some variables
# define some methods
api/controllers/FooController.py:
from api.controllers.Controller import *
class FooController(Controller):
method_decorator(api_view(["GET"]))
method_decorator(login_required)
method_decorator(authentication_classes((SessionAuthentication, TokenAuthentication,)))
method_decorator(permission_classes((IsAuthenticated,)))
def get(self, request):
if request.user.is_authenticated:
return HttpResponse(status=200)
else:
return HttpResponse(status=401)
method_decorator(api_view(["GET"]))
method_decorator(login_required)
method_decorator(authentication_classes((SessionAuthentication, TokenAuthentication,)))
method_decorator(permission_classes((IsAuthenticated,)))
def foo_bar(self, request):
if request.user.is_authenticated:
return JsonResponse({"data": "some data"}, status=200)
Thanks so much in advance if anyone can help me with this!
In your urls.py, use paths like so:
path("get_foo", FooController.as_view({"get":"get_foo"}), name="get_foo"),
Use Django's APIView in your base Controller.py:
from rest_framework import viewsets
class Controller(viewsets.ViewSet):
def __init__(self):
# Code
Then start your FooController class in FooController.py like so:
class FooController(Controller):
authentication_classes = [SessionAuthentication, TokenAuthentication]
permission_classes = [IsAuthenticated]
def get_foo(self, request):

django-background-task not functioning

my django-background-task does nothing, even if I just ask it to do something simple like printing a string.
I dont know what I am doing wrong though.
views.py:
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
from .forms import UserRegistrationForm
from .models import Player, PlayerStats, TotalLevels
from django.core import management
from background_task import background
import random
# background task
#background(schedule=5)
def play_run():
print('it works!')
# management.call_command('runscript', 'runnerscript')
def random_logo():
logo = random.randint(1, 5)
logo_file = 'logo-nav'+str(logo)+'.png'
return logo_file
# Main website views
def home(request):
return render(request, template_name='main/home.html')
# bloxors website specific views
def homepage(request):
logo_file = random_logo()
return render(request, template_name='bloxors/homepage.html', context={'logo':logo_file})
# view in which background task is called
#login_required
def play_redirect(request):
play_run()
return HttpResponse('Please wait while we redirect you...')
Can someone help me by telling what is going wrong?
As always, I appreciate any and all answers!
While the server is running, open another terminal or command prompt with your virtual environment activated then run python manage.py process_tasks
https://django-background-tasks.readthedocs.io/en/latest/

Django - How use generic views from a Django external App in my own App?

I'm new to Django...
I have installed a Django external App called Haystack, this external App have a "views.py" file inside "python2.6/site-packages/haystack". I think this "views.py" is called a "generic view" in Django terms.
This generic view is called using "urls.py" like this:
urlpatterns = patterns('haystack.views',
url(r'^search/$', FacetedSearchView(form_class=FacetedSearchForm, searchqueryset=sqs), name='haystack_search'),
)
I need to make the jump from this generic views to my App. My question goes in the direction of How Can I Do This?
The code of Haystack "views.py" goes like this:
from django.conf import settings
from django.core.paginator import Paginator, InvalidPage
from django.http import Http404
from django.shortcuts import render_to_response
from django.template import RequestContext
from haystack.forms import ModelSearchForm, FacetedSearchForm
from haystack.query import EmptySearchQuerySet
RESULTS_PER_PAGE = getattr(settings, 'HAYSTACK_SEARCH_RESULTS_PER_PAGE', 20)
class SearchView(object):
...
def __init__(self, template=None, load_all=True, form_class=None, searchqueryset=None, context_class=RequestContext, results_per_page=None):
...
def __call__(self, request):
...
def build_form(self, form_kwargs=None):
...
def get_query(self):
...
def get_results(self):
...
def build_page(self):
...
def extra_context(self):
...
def create_response(self):
...
def search_view_factory(view_class=SearchView, *args, **kwargs):
...
class FacetedSearchView(SearchView):
...
def __init__(self, *args, **kwargs):
...
def build_form(self, form_kwargs=None):
...
def extra_context(self):
...
def basic_search(request, template='search/search.html', load_all=True, form_class=ModelSearchForm, searchqueryset=None, context_class=RequestContext, extra_context=None, results_per_page=None):
...
Can someone give what steps I should follow to take out the code from the "urls.py" and put the thing working in my "views.py" App?
Best Regards,
Try to put (r'^search/', include('haystack.urls')),. You also might want to read "Getting started with Haystack"
Try:
#your root urls.py
from django.conf.urls.defaults import *
from haystack.forms import FacetedSearchForm
from haystack.query import SearchQuerySet
from haystack.views import FacetedSearchView
sqs = SearchQuerySet().filter(author='john')
urlpatterns = patterns('haystack.views',
url(r'^/my_custom_very_special_url$', FacetedSearchView(
template='my/special/path/to/faceted_search.html',
searchqueryset=sqs,
form_class=FacetedSearchForm
), name='haystack_search'),
)
BTW, it's all in the docs.
Did you follow all the steps in the docs?
Use the extra_context method to add or overwrite the other variables in the context.

Problem with import custun storage. Django

Hi I'm siting with my custom storage system 1 day. And now when I'm trying import it it gives me this Error.
I put in file models.py
from FTPStorage import FTPStorage
import datetime
from django.db import models
fs=FTPStorage()
class Upload(models.Model):
"""Uploaded files."""
file = models.FileField(upload_to='uploads', store=fs)
timestamp = models.DateTimeField(default=datetime.datetime.now)
notes = models.CharField(max_length=255, blank=True)
class Meta:
ordering = ['-timestamp',]
def __unicode__(self):
return u"%s" % (self.file)
#property
def size(self):
return filesizeformat(self.file.size)
here is my views.py:
from forms import UploadForm
from models import Upload
import ftplib
import os
import datetime
from django.forms import save_instance
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from FTPStorage import FTPStorage
from django.core.files.storage import Storage
def initial(request):
data = {
'form': UploadForm(),
}
return render_to_response('upload.html', data, RequestContext(request))
def upload(request):
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
upload = Upload()
upload.timestamp = datetime.datetime.now()
save_instance(form, upload)
return HttpResponseRedirect(reverse('initial'))
and file custom storage system FTPStorage.py is in direectory app
I have this problem:
Request Method: GET
Request URL: http://localhost:2121/
Exception Type: ViewDoesNotExist
Exception Value:
Could not import app.views. Error was: cannot import name FTPStorage
Exception Location: C:\BitNami DjangoStack\apps\django\django\core\urlresolvers.py in _get_callback, line 134
Please help me. I confuse.
It seems to me that you need to update the PYTHONPATH for your runtime. Based on your error page I think you're using mod_python so try this setting in apache:
PythonPath "sys.path+['/mydir']"
Where /mydir is the full path to wherever the FTPStorage module resides.

Categories

Resources