Execute the task immediately after receiving the JSON response

Whenever the mobile app requests specific data, I must execute a task. The user may not need the task completed immediately, but within the next 2 minutes.

Being relatively new to Python and web development, I am unsure of how to achieve this.

I prefer not to make the user wait for the task to complete, even though it may take around 30 seconds. Is there a way to make it 30 seconds faster?

Is there a method to send an immediate response to the user with the required information, while the task is carried out after sending the JSON?

Can I send a Response to the mobile app without using return, so that the method can continue to perform the task without making the user wait?

@app.route('/image/<image_id>/')
def images(image_id):
   # retrieve the resource (irrelevant code removed)
   return Response(js, status=200, mimetype='application/json')
   # execute some action once the JSON response is sent
   # (what I would like to do, but unsure how to implement)

Upon further consideration, perhaps I should carry out this action asynchronously to avoid blocking the router, yet ensuring it is executed immediately after returning the JSON.


UPDATE - in response to some answers

To handle such tasks, is a Worker server on Heroku recommended or necessary, or is there a more cost-effective alternative?

Answer №1

If you need to handle additional tasks, consider creating a separate thread:

t = threading.Thread(target=some_function, args=[argument])
t.setDaemon(False)
t.start()

Another option to explore is using celery or python-rq

Answer №2

A task queue is essential for your needs. Fortunately, there are several options available to choose from.

For more information, take a look at this related question: uWSGI for uploading and processing files

It's worth noting that your code may not be correct, as the function terminates once you use the return statement, halting further execution within that function.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve the maximum number of slots from a JSON file and implement them into the

I've encountered an issue with my upload form. After uploading and previewing an image, I want to add it to a list as long as the list still has available slots. Here's an example: If the maximum number of slots is set to 5, then you can add up ...

Uncover the secrets to retrieving JSON data using the React fetch method

I've been struggling to retrieve data from an API using various methods, but without success. I have included my code and the API below in hopes of utilizing this JSON data with the React fetch method. // Fetching Data from API fetchData() { ...

No visible alterations were observed to the object following the invocation of JSONDecoder

I'm facing an issue with parsing JSON data into a struct using JSONDecoder in my function called by viewDidLoad. Even though the API call works correctly in postman, I can't seem to print the movie data in the console when I try to access it. Ins ...

iOS: Retrieving null data from a dictionary

When trying to display data using JSON parsing in my project, I encountered an issue where the second NSDictionary returns a Null value. Below is the code snippet for reference: -(void)hdata { NSString *post = [NSString stringWithFormat:@"data[User ...

Serialize long values in exponential notation format using Spring MVC's REST JsonSerializer

My Spring MVC REST application has a custom Json serializer (for ObjectMapper) for handling LocalDate objects: public class DateSerializer extends JsonSerializer<LocalDate> { public LocalDateSerializer() { super(); } @Overr ...

Learn how to execute JavaScript code in Selenium without launching a web browser

I am currently using the Selenium API for web scraping on pages that contain JavaScript code. Is there a way to retrieve the code without having to open a web browser? I am still learning how to use this API Is this even feasible? ...

Validation in Ajax Response

When receiving an object from my API call, I want to perform error checking before displaying the JSON data in my view. function response(oResponse) { if (oResponse && oResponse != null && typeof oResponse === "object" && oResponse.response ...

The soft time limit for celery was not activated

I am facing an issue with a celery task where the soft limit is set at 10 and the hard limit at 32: from celery.exceptions import SoftTimeLimitExceeded from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings @app.ta ...

Creating an index on a JSON array type in MySQL 5.7 can optimize the performance of your

Currently, I am using an SQL script similar to SELECT * FROM user WHERE JSON_CONTAINS(users, '[1]');. However, this method scans the entire table and is inefficient. I would like to create an index on the users column. For instance, if I have a ...

Using the method .Add within a Jobject to insert a nested element

If I were to have a Json Object: { "data":{ "SomeArray":[ { "name":"test1" }, { "name":"test2" }, { "na ...

I am having difficulty locating or clicking on an element on my page using Selenium, Python, findelement, and Xpath methods

I am facing difficulty in locating an element on a webpage after logging in successfully to the website. My goal is to click on a button that appears only after midnight to participate in an activity. However, I do not want to stay glued to my PC just to ...

Adding an image within the body of text in a Django model, where both the text and image coexist

I am currently seeking a method to seamlessly insert an image within the text of my Django-powered blog. My goal is to achieve a layout similar to the one showcased in this example: https://i.stack.imgur.com/cFKgG.png The desired layout consists of two c ...

What are the available choices for constructing HTML based on an ajax response?

Are there any alternatives or libraries available for constructing html from an ajax response? Currently, I am taking the json data received, creating the html as a string, and using a jQuery function to insert it into the DOM. However, I believe there mu ...

How can consecutive values be identified in a 3D numpy array in Python without relying on the groupby function?

Consider having a 3D numpy array like the one below: matrices= numpy.array([[[1, 0, 0], #Level 0 [1, 1, 1], [0, 1, 1]], [[0, 1, 0], #Level 1 [1, 1, 0], [0, 0, 0]], [[0, 0, ...

What is the most effective method for ensuring a Vue application can accurately interpret the environmental variables configured on Heroku?

I implemented a Vue app that is currently being hosted on Heroku. Since Heroku doesn't support static apps, I decided to create a basic express server to serve my app. //server.js const express = require('express') const serveStatic = requi ...

A guide on showing POST values from javascript XMLHttpRequest() in php

I have encountered an issue where I am using the XMLHttpRequest() javascript function to send parameters in Json format to another php page, but for some reason $_POST['appoverGUID'] is not receiving the posted values. Below is my Javascript cod ...

Executing a Python script asynchronously from a Node.js environment

I am currently managing a node.js program that handles approximately 50 different python script instances. My goal is to implement a throttling mechanism where only 4 processes can run in parallel at any given time. Initially, I attempted to create a simp ...

Locate a Sub-Child href Element using Selenium

I am attempting to interact with a link using Selenium automation tool. <div id="RECORD_2" class="search-results-item"> <a hasautosubmit="true" oncontextmenu="javascript:return IsAllowedRightClick(this);" class="smallV110" href="#;cacheurl ...

Selenium in Python encounters difficulty locating web element

I've been attempting to extract posts from a forum I found at this specific URL: The main content I'm trying to pull is located within: <div class="post-content"> However, no matter if I use get element to search by XPATH or CLA ...

Using Observables in Angular 2 to send polling requests

I have the following AngularJS 2 code snippet for polling using GET requests: makeHtpGetRequest(){ let url ="http://bento/supervisor/info"; return Observable.interval(2000) .map(res => res.json()) //Error here ...