60 questions pulled from past papers whose wording matches this week's topics, newest first, duplicates removed. Pick your answers, then press Check answers. Figures and answer keys are the originals.
A news platform wants to send a morning digest email to all subscribers every day at 7 AM. Sweta sets up the beat schedule, starts Redis and Celery Beat, and then claims: "The Worker is optional here. Beat handles the scheduling and the execution of the task, so we do not need a separate Worker process." Is Sweta's claim correct? Choose the best answer.
Yes. For tasks defined in , Celery Beat manages both the schedule and the execution, so running the Worker is redundant.text
```
beat_schedule
```
No. Celery Beat cannot trigger tasks that involve database queries or email sending. Those tasks must be triggered manually using from the Flask app.text
```
.delay()
```
No. Celery Beat is only a scheduler. At 7 AM, it pushes a task message into the Redis broker and stops there. Without a running Celery Worker to pick up that message, the digest email is never actually sent.
Yes, but only when the task is defined with instead of inside .In that case, Beat handles execution too.text
In a Celery setup, we use two separate Redis databases:
Which of the following best explains the conceptual difference between the broker and the backend?
A team builds an internal warehouse dashboard where multiple managers, each on a different computer, need to receive live low-stock alerts from the server in real time. They decide to use Flask-SSE with Redis. Which of the following best explains Redis's role in a Flask-SSE setup?
Redis is used by Flask-SSE to authenticate connected users before events can be streamed to the browser.
Redis is optional in Flask-SSE and is only recommended when the application has a very large number of concurrent users.
Redis is only needed when SSE events must be stored permanently and replayed after reconnection.
Flask-SSE uses Redis as a shared event channel so published messages can be delivered to connected clients.
Read the following code carefully and answer the given subquestions. tasks.py:
Called from a view/script:
Checked immediately, right after delay() — worker hasn't processed it yet:
Called separately, after waiting for the worker to finish the task:
What do the two print statements, print(result) and print(type(result)) in the first code block output?
text
10 **and** <class 'int'>
text
A task ID string and <class 'celery.result.AsyncResult'>
Read the following code carefully and answer the given subquestions. tasks.py:
Called from a view/script:
Checked immediately, right after delay() — worker hasn't processed it yet:
Called separately, after waiting for the worker to finish the task:
What do print(check.status) (checked immediately) and the later print(check.get(timeout=5)) (checked after the worker finishes) output?
Pratham builds a Flask route that generates a PDF report and sends it to the user via email, all inside the route handler without using Celery. A tester notices that the browser takes about 12 seconds to respond, and during that time other users are unable to use the app normally. Which of the following correctly explain this behaviour and what Celery would change?
Flask handles one request at a time per worker, so the long-running task blocks the entire process until it finishes.
Other users' requests are queued and only served after the heavy task completes, making the app feel unresponsive.
Using Celery's would make the task run faster by giving it more CPU cores.text
```
.delay()
```
With Celery, Flask immediately returns a response to the user while the report generation and email sending happen inside a separate Celery worker process in the background.
A Vue 2 component does the following: •loads initial task data from an API, •starts a timer after the component appears on the page, •clears that timer before the component is removed. Which hook choices are appropriate?
In a web application using webhooks and Redis for real-time data synchronization: Scenario: An order management system where: • When an order is created, a webhook is sent to a notification service • Redis stores the current order cache • Multiple concurrent requests update the cache Which statements about this architecture are true?
Webhooks guarantee that the notification service will process events in the exact order they were triggered
Redis is suitable for this use case because it's an in-memory data structure store that provides fast access to cached data
The webhook will automatically retry if the notification service is temporarily unavailable
Webhooks use HTTP POST requests to communicate events asynchronously
Consider the following Flask application (server.py):
server.py
```python
from flask import Flask
from flask_caching import Cache
import time
config = {
"DEBUG": True,
"CACHE_TYPE": "RedisCache",
"CACHE_REDIS_URL": "redis://localhost:6379/1",
"CACHE_DEFAULT_TIMEOUT": 300
}
app = Flask(__name__)
app.config.from_mapping(config)
cache = Cache(app)
@app.route('/data/<item>')
@cache.cached(timeout=100)
def get_data(item):
time.sleep(25)
return f"Data for {item}"
if __name__ == '__main__':
app.run()
```
The application runs on http://localhost:5000.
A client makes two consecutive requests to http://localhost:5000/data/apple within 50 seconds
What will be the approximate absolute difference between their latencies?
Suppose you are developing an application for millions of users that will perform intensive data analysis and return the results asynchronously. Arrange the following set of actions/operations to achieve an efficient and scalable design.
I. Save the result to a database
II. Invoke a callback URL
III. Queue the analysis job
Consider the following python code snippet. Assuming proper configuration for caching is done, answer the question below.
```python
from flask import Flask, request
from flask_caching import Cache
import time
app = Flask(__name__)
app.config['CACHE_TYPE'] = 'RedisCache'
app.config['CACHE_DEFAULT_TIMEOUT'] = 5
cache = Cache(app)
@app.route('/time')
@cache.cached()
def get_time():
return str(time.time())
```
Suppose the following sequence of requests is made:
Request 1: GET /time at 00:00:00
Request 2: GET /time at 00:00:02
Request 3: GET /time at 00:00:06
What will the responses be for each request?
Consider the below Celery setup.
```python
from celery import Celery
import time
app = Celery('tasks', broker='redis://localhost:6379/0')
@app.task
def long_task():
time.sleep(10)
return 'Task completed'
```
What will be the result of calling long_task.delay() (assuming more than 1 worker are available)?
The task will immediately execute and print the result 'Task completed'.
The task will execute asynchronously, and 'Task completed' will be printedafter a 10-second delay.
The task will execute synchronously, blocking the main thread for 10 seconds.
Match the following technologies with their typical use cases:
Match the following technologies with their typical use cases:
Text of the picture (copyable)
| | |
|---|---|
| 1. Webhooks | A. Real-time communication in chat applications |
| 2. Web Sockets | B. Fetching data periodically from an API endpoint |
| 3. API | C. Receiving notifications when a specific event occurs |
| 4. Polling | D. Exchanging data between client and server using HTTP requests |
| 5. Pub/Sub | E. Broadcasting messages to multiple subscribers simultaneously |
Two requests are given to localhost:5000/compute/10/20 and localhost:5000/compute/5/10 within 60 seconds. What would be the json response from the server respectively?
Text of the picture (copyable)
Consider the following Flask application with Redis caching. Redis is running
normally on port 6379.
```python
from flask import Flask, jsonify
from flask_caching import Cache
app = Flask(__name__)
app.config['CACHE_TYPE'] = 'redis'
app.config['CACHE_REDIS_HOST'] = 'localhost'
app.config['CACHE_REDIS_PORT'] = 6379
cache = Cache(app)
def compute_value(x, y):
result = x * y
return result
@app.route('/compute/<int:x>/<int:y>')
@cache.cached(timeout=60, key_prefix='compute')
def compute(x, y):
result = compute_value(x, y)
return jsonify({'result': result})
if __name__ == '__main__':
app.run(debug=True, port=5000)
```
Analyze the given HTML with embedded script.
```html
<body>
<div id="status"></div>
<div id="result"></div>
<script>
function updateStatus(message) {
document.getElementById("status").textContent = message;
}
function updateResult(message) {
document.getElementById("result").textContent = message;
}
let promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data Loaded");
}, 1000);
});
let promise2 = Promise.reject("Network Error");
promise1
.then((result) => {
updateStatus(result);
})
.catch((error) => {
updateResult(error);
});
promise2
.catch((error) => {
updateStatus(error);
return Promise.resolve("Retry Successful");
})
.then((result) => {
updateResult(result);
});
</script>
</body>
```
What will be the final state of HTML elements, after all the `setTimeout()` have finished executing.
text
#status will be "Data Loaded", and #result will be "Data Save Failed".
text
```
#status will be "Network Error", and #result will be "Retry Successful".
```
text
```
#status will be "Data Loaded", and #result will be "Retry Successful".
```
text
```
#status will be "Network Error", and #result will be "Data Save Failed".
```
You are trying to build a distributed system with N servers, each of which may need to communicate with any of the other servers. Which of the following statement(s) is/are true?
With point-to-point communication, the number of connection links will growas O(n).
With point-to-point communication, the number of connection links will growas O(n2).
With the use of a central message broker, the number of connection links willgrow as O(n).
With the use of a central message broker, the number of connection links willgrow as O(n2).
Consider the following flask application.
Consider the following flask application.
Text of the picture (copyable)
app.py
```python
from flask import Flask
from flask_caching import Cache
from time import sleep
config = {
"CACHE_TYPE": "RedisCache",
"CACHE_REDIS_HOST": "localhost",
"CACHE_REDIS_PORT": 6379,
"CACHE_REDIS_DB": 1
}
app = Flask(__name__)
app.config.from_mapping(config)
cache = Cache(app)
@app.get('/')
@cache.cached(timeout=120)
def home():
sleep(30)
return "hello world"
if __name__ == "__main__":
app.run(debug=True)
```
Suppose the application is running on "http://localhost:5000". If user1 visits the URL "http://localhost:5000" and after 50 seconds user2 visits the same URL. What will be the approx difference between the response time for user1 and user2?
Consider the flask application mentioned. Suppose the application is
running on "http://localhost:5000". If user1 visits the URL "http://localhost:5000" and
after 3 minutes user2 visits the same URL. What will be the approx difference between
the response time for user1 and user2?
```python
app.py
from flask import Flask
from flask_caching import Cache
from time import sleep
config = {
"CACHE_TYPE": "RedisCache",
"CACHE_REDIS_HOST": "localhost",
"CACHE_REDIS_PORT": 6379,
"CACHE_REDIS_DB": 1
}
app = Flask(__name__)
app.config.from_mapping(config)
cache = Cache(app)
@app.get('/')
@cache.cached(timeout=120)
def home():
sleep(30)
return "hello world"
if __name__ == "__main__":
app.run(debug=True)
```
You are trying to build a distributed system with N servers, each of which may need to communicate with any of the other servers. Which of the following statement(s) is/are false?
With point-to-point communication, the number of connection links will growas O(n).
With point-to-point communication, the number of connection links will growas O(n2).
With the use of a central message broker, the number of connection links willgrow as O(n).
With the use of a central message broker, the number of connection links willgrow as O(n2).
Consider the following flask application.
Consider the following flask application.
Text of the picture (copyable)
app.py:
```python
from flask import Flask
from flask_caching import Cache
import time
config = {
"DEBUG": True,
"CACHE_TYPE": "RedisCache",
"CACHE_REDIS_URL": "redis://localhost:6379/1",
"CACHE_DEFAULT_TIMEOUT": 300
}
app = Flask(__name__)
app.config.from_mapping(config)
cache = Cache(app)
@app.get('/name/<name>')
@cache.cached(timeout=100)
def get_name(name):
time.sleep(30)
return name
if __name__ == '__main__':
app.run()
```
Suppose the application is running on "http://localhost:5000". If the client makes two requests (one after another) to URL "http://localhost:5000/name/mohan" within 50 seconds. What will be the approximate absolute difference between their latencies?
Consider the given 2 implementations.
Consider the given 2 implementations.
Consider the given 2 implementations. Suppose there are currently 1000 users in the database, and the application is supposed to generate 1000 HTML reports. Which of the following statement(s) is/are false (assuming there are more than 1 worker available in the celery system)?
Text of the picture (copyable)
Approach 1:
driver code:
```python
import tasks
def generate_reports():
users = User.query.all()
for user in users:
tasks.job_report.delay(user)
```
celery job:
```python
@celery.task
def job_report(user):
"""
This function fetches the statistics of a given user and generates an
HTML report
"""
```
Approach 2:
driver code:
```python
import tasks
def generate_reports():
tasks.job_report.delay()
```
celery job:
```python
@celery.task
def job_report():
users = User.query.all()
for user in users:
...
# This loop fetches the statistics of a given user and generates an HTML
# report
...
```
Approach 1 will finish the task in less time than approach 2.
Approach 2 will finish the task in less time than approach 1.
Both the approaches will be comparable.
Both the approaches will be comparable if there is only 1 worker available.
Suppose you are building an application which requires sending emails to all the users stored in the database at regular intervals. Given below are the two approaches to satisfy the requirement.
Suppose you are building an application which requires sending emails to all the users stored in the database at regular intervals. Given below are the two approaches to satisfy the requirement. Choose the correct statement(s).
Text of the picture (copyable)
Approach 1:
```python
@celery.task
def send_bulk_emails():
all_users = User.query.all() // Get all the user objects from the
database
for user in all_users:
// send email to the user
send_bulk_emails.delay() // invokes celery task
```
Approach 2:
```python
@celery.task
def send_email(email):
// send email to the user
all_users = User.query.all() // Get all the user objects from the database
for user in all_users:
send_email.delay(user.email) // invokes celery task
```
Approach 1 will take more time than approach 2, if more than 2 celery workersare available.
Approach 2 will take more time than approach 1, if more than 2 celery workersare available.
Both the approaches will take same time (approx), if only 1 celery worker isavailable.
Suppose an endpoint in your flask application triggers a celery task, which generates a CSV file named “data.csv” and saves it in the static folder of a flask application. The file generator takes anywhere between 20 and 40 seconds to generate and save the CSV file. The below fetch call is used to get the file generated by the above explained celery task.
Suppose an endpoint in your flask application triggers a celery task, which generates a CSV file named “data.csv” and saves it in the static folder of a flask application. The file generator takes anywhere between 20 and 40 seconds to generate and save the CSV file. The below fetch call is used to get the file generated by the above explained celery task. Which of the following is the most efficient way to make the above fetch call so that it doesn’t fail and return the desired response?
Text of the picture (copyable)
```javascript
fetch("/static/data.csv").then(response => response.blob())
.then(data => {
// does something with the response data
})
```
Use short polling to check the state of the celery task after every 5 seconds,and make the fetch call, when the task succeeds.
Use javascript function “setTimeout” to make the fetch after 41 seconds, whichmakes sure that the file is generated and saved to the desired location.
Consider the below flask application.
Consider the below flask application.
Text of the picture (copyable)
app.py:
```python
from flask import Flask
from flask_caching import Cache
from time import sleep
config = {
"CACHE_TYPE": "RedisCache",
"CACHE_REDIS_URL": 'redis://localhost:6379/1'
}
app = Flask(__name__)
app.config.from_mapping(config)
cache = Cache(app)
@cache.memoize(timeout=120)
def get_score(name):
sleep(10)
return 0
@app.route('/match/<int:match_id>/player/<name>/score')
def score(match_id, name):
score = get_score(name)
return f"IND Vs AUS- SKY: {score}"
if __name__ == '__main__':
app.run(debug=True)
```
If the Redis server is running on "localhost:6379", and application is running on "http://127.0.0.1:5000". If a user visits the URL "http://127.0.0.1:5000/match/1/player/sky/score" at 7AM in the morning for the first time and then at 9AM for the second time. What will be the approximate absolute difference between the response time of the requests?
Suppose you are writing an application to be used by lakhs of people, which will run a brute force algorithm and gives back the result to the user of the application when ready. Considering this context, arrange the below set of actions/operations to achieve a desirable and practical design. I. Invoke the webhook II. Relieve the worker III. Dispatch a backend job