Using Django ORM in plain python script / infinite task - python

I have application in plain python with some basic libraries. I'm looking to use Django as main framework for this application and maintain frontend.
My question is, can I still use my already written application and switch to Django ORM and maybe controlling the application via some callbacks. This application is running infinitely with asincio library.
Or is there any way how to run background tasks in Django? I found celery but I'm not sure about starting this process. Maybe use of some Django commands and supervisor.
TLDR: I need some way of running background task (command, controller, python script) infinitely long without user interaction.

You can do that with Django Background Tasks.
Define your background-task as a function with the decorator #background.
Since you want your task to run infinitely, call it in your main urls.py and just set
repeat_until = None, then it will repeat infinitely.
Copied Example from the linked tutorial:
from django.shortcuts import render,HttpResponse
from background_task import background
# Create your views here.
#background(schedule=5)
def hello():
print "Hello World!"
def background_view(request):
hello(repeat=10)
return HttpResponse("Hello world !")
And this is your call in the urls.py:
from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
from background_app.views import hello
urlpatterns = [
url(r'^admin/', admin.site.urls),
url( r'^', include('background_app.urls',namespace='background')),
]
hello(repeat=10,repeat_until=None) # This is how you call it
Doc:
https://django-background-tasks.readthedocs.io/en/latest/
Tutorial with small example:
https://medium.com/#robinttt333/running-background-tasks-in-django-f4c1d3f6f06e

Related

Using django-stripe's built-in webhook support

I'm using Django 3.0, dj-stripe 2.0, and the Stripe CLI. dj-stripe provides native support for Stripe webhooks, and their documentation says to include the following in my django project's main urls.py file to expose the webhook endpoint:
url(r"^stripe/", include("djstripe.urls", namespace="djstripe")),
I have done this, but how do I now leverage the endpoint?
As a separate experiment, I created a payments app, setup the URL conf, and successfully called the view when triggering the non dj-stripe webhook endpoint via the Stripe CLI. But it doesn't use any dj-stripe functionality:
# project urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('stripe/', include("djstripe.urls", namespace="djstripe")),
path('payments/', include("payments.urls", namespace="payments")),
]
# payments/urls.py
from django.urls import path
from . import views
app_name="payments"
urlpatterns = [
path("", views.my_handler, name="my-handler"),
]
# payments/views.py
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def my_handler(request, **kwargs):
print(request.body)
return HttpResponse(status=200)
Running stripe listen --forward-to localhost:8000/payments/ and, in a separate window, stripe trigger product.created returns a 200 response.
But stripe listen --forward-to localhost:8000/stripe/webhook/ and stripe trigger product.created returns a 500.
Thank you in advance for your help.
[UPDATE]
I have not modified the default DJSTRIPE_WEBHOOK_URL or DJSTRIPE_WEBHOOK_VALIDATION settings. In settings.py I have:
STRIPE_LIVE_PUBLIC_KEY = os.environ.get("STRIPE_LIVE_PUBLIC_KEY")
STRIPE_LIVE_SECRET_KEY = os.environ.get("STRIPE_LIVE_SECRET_KEY")
STRIPE_TEST_PUBLIC_KEY = os.environ.get("STRIPE_TEST_PUBLIC_KEY")
STRIPE_TEST_SECRET_KEY = os.environ.get("STRIPE_TEST_SECRET_KEY")
STRIPE_LIVE_MODE = os.environ.get("STRIPE_LIVE_MODE")
DJSTRIPE_WEBHOOK_SECRET = "*************************************"
The test keys are pulled from env/bin/activate:
export STRIPE_LIVE_PUBLIC_KEY="pk_live_****...."
export STRIPE_LIVE_SECRET_KEY="sk_live_****...."
export STRIPE_TEST_PUBLIC_KEY="pk_test_****...."
export STRIPE_TEST_SECRET_KEY="sk_test_****...."
export STRIPE_LIVE_MODE="False"
When I run stripe listen --forward-to localhost:8000/stripe/webhook/ and trigger stripe trigger customer.created I get the following 500 error:
stripe.error.InvalidRequestError: Request req_NTtzsTFS8uVdfL: No such customer; a similar object exists in test mode, but a live mode key was used to make this request.
But I don't understand how my keys could be getting mixed up, because the webhooks work fine when I trigger the same event and listen via the /payments/ endpoint.
Thank you again for your time.
In summary, you need to decorate a handler function using the #webhooks.handler decorator.
You have some examples in the webhooks section of the dj-stripe documentation.

Django cant be reached via parameterized url

Hello StackOverflow community,
I'm currently learning how to use the library Django combined with Python. However, I've ran into some issues which are somehow strange. My situation is the following. I have a project called "animals" which is the base of the Django application. My app is called "polls". Then I've defined the following views.
polls/views.py
from django.shortcuts import render
from django.http import HttpResponse
def animals(request, animal_id):
return HttpResponse("%s" % animal_id)
def index(request):
return HttpResponse('Hello world')
So far, so good. Unfortunatly I can't say the same about the urlpatterns.
polls/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('',views.index,name='index'),
# Redirects to localhost:8000/polls/<animal_id>
path('<int:animal_id>/',views.animals,name='animals')
]
Whenever I want to navigate to the url "localhost:8000/polls/10/" Django reminds me of the fact, that the url is not accepted by the application and a 404 Error is thrown inside my browser. Am I missing something here?
UPDATE
I've managed to resolve the problem by fixing a rather trivial error. While the polls/urls.py was alright, the problem lay inside the animals/urls.py file. This file looked like this:
animals/urls.py
from django.conf.urls import url
from django.contrib import admin
from django.urls import include,path
urlpatterns = [
url(r'^admin/', admin.site.urls),
path('polls',include('polls.urls')),
]
As one can see, the "polls" path is not finished with a "/" sign. This indicates to Django that my desired route would be localhost:8000/polls where is any integer I add to the url. However, you have to add the slash at the end. Otherwise Django won't work as expected.

How start background periodic task with django-background-tasks

I want to create periodic task for check values in my SQLite file. I tried to create repeating task with django-background-tasks but it doesn't work. It works fine when I used python manage.py process_tasks in cmd. How start this task with start django and without use this command?
I develop my web app on Windows 10.
urls.py
from django.contrib import admin
from django.urls import path, include
from client import tasks as task
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('client.urls')),
path('account/', include('account.urls')),
]
task.check_groups(repeat=10, repeat_until=None)
tasks.py
from background_task import background
from django.utils import timezone
from client.models import StudyGroup, Account
#background()
def check_groups():
check_active_groups()
check_inactive_groups()
From the docs:
setup a cron task (or long running process) to execute the tasks
You have to setup cron or some other periodic runner to call that command because Django by itself will not be able to do this.

Where to instantiate a client for an external service in Django?

What is the accepted practice in Django for creating an instance of a client for an external service (e.g. Zookeeper, Cassandra, Redis, etc.)?
I need this client to perform a "set key" operation from inside a view and I don't want to create the client on each request due to high overhead.
Currently I've declared it as a global variable in views.py, but that's not really ok, because it gets instantiated when I do python manage.py makemigrations too.
A really stripped down example of the issue:
urls.py
from django.conf.urls import url
from app.views import MyView
urlpatterns = [
url(r'^', MyView.as_view()),
]
views.py
from django.shortcuts import render
from django.views import View
from django.http import HttpResponse
from kazoo.client import KazooClient
import logging
logging.basicConfig(level=logging.DEBUG)
zk = KazooClient(hosts="127.0.0.1:2181")
zk.start()
# Create your views here.
class MyView(View):
def get(self, request):
value, _ = zk.get("/my_zk_key")
return HttpResponse("value: {}".format(value))
The problem is that the zookeeper client gets created and connects in cases other than runserver, like this:
$ python manage.py makemigrations
INFO:kazoo.client:Connecting to 127.0.0.1:2181
DEBUG:kazoo.client:Sending request(xid=None): Connect(protocol_version=0, last_zxid_seen=0, time_out=10000, session_id=0, passwd=b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', read_only=None)
INFO:kazoo.client:Zookeeper connection established, state: CONNECTED
No changes detected
$
I'm looking for an accepted practice in Django for dealing with such cases.
If your problem can be reduced to the last point, you can avoid setting your global variable during the migration with:
import sys
if 'makemigrations' not in sys.argv and 'migrate' not in sys.argv:
# variable setting here

Python Django 1.6 execute function for every request before getting to view

I'm writing some API functionality for my project using Python 3.4 and Django 1.6.
All functionality works fine, but I want execute one function for all that kind of requests.
For Example: I have following urls.py file in my API application in Django project
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^getposts', 'Postigs.views.get_posts', name='getPosts'),
url(r'^addpost', 'Postigs.views.add_post', name='addPost'),
url(r'^addcomment', 'Postigs.views.add_comment', name='addComment'),
)
And views.py for that URL requests handling.
So is it possible to execute some function for Example:
def pre_execute(request):
do_something_before_view_function()
I've worked before with many PHP frameworks , there are always some pre_execute() function ... also I've worked with ASP.NET MVC , Node.js Express.js , and all have that function which is firing before request action.
I don't believe that Django didn't have it , but I can't find how implement that functionality.
Thanks.
Middlewares are what you want: https://docs.djangoproject.com/en/dev/topics/http/middleware/
example middleware: https://github.com/django/django/blob/master/django/middleware/common.py
Like iskorum mentioned above, Middlewares is the answer. Or there is also a chance that you are looking for View Decorators. Here is the link https://docs.djangoproject.com/en/dev/topics/http/decorators/

Categories