Function trigger other function and ends before result - python

I'm developing an API with Django Rest Framework for handling some subscriptions
I wanted do make the registration in 2 steps.
First, i would register user in my database, after that i want to register user to other service (email marketing, for example).
I have to do it in two steps because the registering of the user in external services may take some time (or the service can be unavailable at the time of request) and i don't want users to wait everything so they can go to other pages.
My idea is: After registering user into my database, i would return http 200_ok to the front-end so user can go to other pages, and in my backend i would use that data to try to register the user in external services as many times as needed (e.g: waiting if other services are unavailable).
But rest_framework only allows me to return Response() (i'm using class-based views), so i only can return http 200_ok, but if i return the function ends and my other functions (that will take more time to run) will end aswell.
Is there a way to do this?

Have a look at https://django-background-tasks.readthedocs.io/en/latest/
This could help solve your background tasks

Related

Django - Restrict Stripe SuccessUrl access

I have just integrated Stripe Checkout with my Django app. However, from their code:
session = stripe.checkout.Session.create(
customer_email=customer.email,
payment_method_types=['card'],
line_items=line_items,
mode='payment',
success_url='http://127.0.0.1:8000/SUCCESS/?session_id={CHECKOUT_SESSION_ID}',
cancel_url='http://127.0.0.1:8000/cart'
)
It redirects to a Success_url. I would like to display their order info and send an email from the success page but currently, everyone can visit(would cause random emails etc). Is there a way i can limit this for the person that just checked out? Thank you!
The success page should really just be a page to let your users know that their payment went through. I wouldn't personally recommend triggering any app-specific logic when your users land on it. As you've pointed out this could cause accidents with users randomly stumbling on that page and triggering emails. It also offers an opportunity for bad actors to exploit your application.
Instead, I would create a webhook endpoint and listen for the checkout.session.completed event, and trigger your emails from there. Building a webhook endpoint should be no more difficult than building any other endpoint on your server, with there only being some small extra logic to verify incoming requests.
Another option would be to use a tool like Zapier to listen for these events from Stripe and trigger various flows from them: https://stripe.com/partners/zapier

Autoposting to Facebook page from django-rest-framework app

I have a simple Django Rest Framework app running. I want to auto post to app's Facebook page whenever new item is saved in the db. I was wondering if Django management commands is the best solution. The other option is google cloud functions to make a request at specified time and post to Facebook if there are new items (could be expensive and unnecessarily complex).
Any suggestions would be appreciated.
You can listen to your item model's post_save signal and connect it to a handler function which is responsible for posting your saved item data to a Facebook page. Refer to this Django Docs page on how to connect your handler to a signal.
For better performance, posting to a Facebook page can be done asynchronously by leveraging task queue like Celery so it won't affect your REST API response time.

Get list of connected users with Django

I'm looking for a way to keep track of users that are online/offline. So if I present all users in a list i could have an icon or some kind of flag to show this. Is this built in in Django's default Auth system?
My first thought was to simply have a field in my profiles called last_logout in the models and update it with the date/time each time user logged out.
With this info and the built in last_login I should be able to make some kind of function to determine if the user is loggedin/online right?
Or should I just have a boolean field called "online" that I can change when user logs in and out?
With only django it will be hard to do. For such task async frameworks are more suitable.
For example, tornado.
Users won't do logout explicitly every time they go offline. They just close their browser and that's it. You can't know it with only django auth app. It is not designed for such tasks.
Even if you will check for not expired session, it not gives you all online users, because session can be non-expired for 30 days.
So to get real online users, possible solutions are:
Every user will send some data via javascript to your server, for example every 10 seconds. You can fetch that data on server and put user into cache and set cache key to be alive for 10 seconds. So when you need to know, who are online now, you'll check your cache. But it is not a good solution, because it will need a lot of server resources.
Use async framework (tornado) at server side (you can setup separate process for exact requests). And use websockets (SockJS is a good library for that at client side). It is a more complicated solution, but it is better.
You have to consider what exactly means for the users to be "online". Since any user can close the browser window any time and without the server knowing about that action, you'd end up having lots of false "online" users.
You have two basic options:
Keep track of the user's last activity time. Every time the user loads a page you'd update the value of the timer. To get a list of all online users you'd need to select the ones with an activity before X minutes. This is what is done by some web forums.
Open a websocket, long polling connection or some heartbeat to the server. This is what Facebook chat does. You'd need more than just django, since to keep a connection open another kind of server-side resources are needed.

How to authenticate a user in a RESTful api and get their user id? (Tornado)

I would like to maintain statelessness but I also don't want to call my login function on each authenticated request. Would using tornado's secure cookie functionality be feasible for storing the userid in each request for a mobile app? I'm trying to keep performance in mind, so although basic http authentication would work, I dont want to call a login function on each request to get the users id.
I am assuming that your authentication function talks to a database and that each page in you app hits the database one or more times.
With that in mind, you should probably just authenticate each request. Many cloud/web applications have multiple database queries per page and run just fine. So when performance does get to be problem in your app (it probably won't for a long time), you'll likely already have an average of n queries per page where n is greater than 1. You can either work on bringing down that average or work on making those queries faster.

Twitter Oauth problem - I need a website to register an app

I need to use Oauth for a personal twitter script I am making. Its not commercial or anything like that. To register it here: https://dev.twitter.com/apps/new I need a website even though it is a client. It wont let me register my app without a website.
Is there anything I can do? If I just created a blog that explains the concept behind the script I am using - would they accept that and let me register the "app" (just a script I use?).
If it is just for personal use, you could put pretty much any url in that field. As far as I know it isn't double checked or subjected to approval.
Choose Client here:
In place of Application Website you can put any link. Its just the link-back url.
As mentioned above, the callback URL can be anything, but I would choose Browser, not Client, because Twitter lets you override the value of Application Website with the parameter oauth_callback. This lets you automate the final step of the OAuth flow.
Usually, since you are running a script, you would need to set oauth_callback=oob and put the user through PIN authentication, which sucks. Here is an alternative:
Choose Browser and set Application Website to http://www.whatever.com (doesn't matter).
Register your script with your operative system to handle a custom scheme, eg: myscript://
Pass oauth_callback=myscript://anystring during the OAuth flow.
The result is that once the user is authenticated, Twitter calls myscript://anything from the web browser with the two last parameters you need for the final authentication step, and the OAuth flow will complete without user interaction.

Categories

Resources