Bird
Raised Fist0
Flaskframework~20 mins

Polling as fallback in Flask - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Polling Mastery in Flask
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
Polling fallback behavior in Flask app

Consider a Flask app that uses polling as a fallback to update client data. What will the client see if the polling interval is set too high?

Flask
from flask import Flask, jsonify
import time

app = Flask(__name__)

last_update = time.time()
data = {'value': 0}

@app.route('/data')
def get_data():
    global last_update, data
    if time.time() - last_update > 5:
        data['value'] += 1
        last_update = time.time()
    return jsonify(data)
AThe client sees stale data for longer than 5 seconds due to high polling interval.
BThe client sees data updates immediately without delay.
CThe client sees updated data every 5 seconds as expected.
DThe client receives an error because polling is too frequent.
Attempts:
2 left
💡 Hint

Think about what happens if the client polls less often than the server updates.

📝 Syntax
intermediate
2:00remaining
Correct polling implementation in Flask route

Which Flask route code correctly implements a polling endpoint that returns an incrementing JSON counter?

A
from flask import Flask, jsonify
app = Flask(__name__)
data = {'count': 0}
@app.route('/poll')
def poll():
    data['count'] += 1
    return jsonify(data)
B
from flask import Flask, jsonify
app = Flask(__name__)
count = 0
@app.route('/poll')
def poll():
    count += 1
    return jsonify({'count': count})
C
from flask import Flask, jsonify
app = Flask(__name__)
count = 0
@app.route('/poll')
def poll():
    count = count + 1
    return jsonify({'count': count})
D
from flask import Flask, jsonify
app = Flask(__name__)
count = 0
@app.route('/poll')
def poll():
    global count
    count += 1
    return jsonify({'count': count})
Attempts:
2 left
💡 Hint

Remember to declare global variables inside functions when modifying them.

❓ state_output
advanced
2:00remaining
Polling state update timing in Flask

Given this Flask polling endpoint, what is the value of data['value'] after 10 seconds if the client polls every 1 second?

Flask
from flask import Flask, jsonify
import time

app = Flask(__name__)

last_update = time.time()
data = {'value': 0}

@app.route('/data')
def get_data():
    global last_update, data
    if time.time() - last_update > 3:
        data['value'] += 1
        last_update = time.time()
    return jsonify(data)
Adata['value'] will be 3
Bdata['value'] will be 5
Cdata['value'] will be 0
Ddata['value'] will be 10
Attempts:
2 left
💡 Hint

Calculate how many 3-second intervals fit into 10 seconds.

🔧 Debug
advanced
2:00remaining
Debugging polling endpoint with stale data

A Flask polling endpoint returns stale data even though the server updates it every second. What is the most likely cause?

Flask
from flask import Flask, jsonify
import time

app = Flask(__name__)

last_update = time.time()
data = {'count': 0}

@app.route('/poll')
def poll():
    global last_update
    if time.time() - last_update > 1:
        data['count'] += 1
        last_update = time.time()
    return jsonify(data)
AThe Flask app is missing a route decorator.
BThe data dictionary is immutable and cannot be updated.
CThe variable last_update is not declared global inside the function, so it never updates.
DThe time module is not imported, causing errors.
Attempts:
2 left
💡 Hint

Check variable scope inside the function.

🧠 Conceptual
expert
2:00remaining
Why use polling as fallback in Flask apps?

In a Flask web app, why might polling be used as a fallback method for updating client data instead of WebSockets?

APolling is more efficient and uses less bandwidth than WebSockets.
BPolling works in all browsers and network setups, even when WebSockets are blocked or unsupported.
CPolling allows real-time two-way communication better than WebSockets.
DPolling requires less server resources because it keeps connections open.
Attempts:
2 left
💡 Hint

Consider browser and network compatibility.

Practice

(1/5)
1. What is the main reason to use polling as a fallback in Flask applications?
easy
A. To regularly ask the server for updates when real-time methods fail
B. To reduce the number of server requests to zero
C. To make the server push updates automatically without client requests
D. To avoid any communication between client and server

Solution

  1. Step 1: Understand polling purpose

    Polling sends repeated requests to the server to check for updates.
  2. Step 2: Identify fallback use

    Polling is used when real-time communication methods like WebSockets are unavailable or fail.
  3. Final Answer:

    To regularly ask the server for updates when real-time methods fail -> Option A
  4. Quick Check:

    Polling = fallback for updates [OK]
Hint: Polling means repeated requests when real-time fails [OK]
Common Mistakes:
  • Thinking polling reduces server requests
  • Confusing polling with server push
  • Believing polling stops communication
2. Which Flask code snippet correctly implements a simple polling endpoint that returns JSON data?
easy
A. from flask import Flask app = Flask(__name__) @app.route('/poll') def poll(): return {'status': 'ok', 'time': datetime.now()}
B. from flask import Flask app = Flask(__name__) @app.route('/poll') def poll(): return 'status: ok'
C. from flask import Flask, json app = Flask(__name__) @app.route('/poll') def poll(): return json.dumps({'status': 'ok'})
D. from flask import Flask, jsonify app = Flask(__name__) @app.route('/poll') def poll(): return jsonify({'status': 'ok'})

Solution

  1. Step 1: Check Flask imports and response format

    Using jsonify is the correct way to return JSON responses in Flask.
  2. Step 2: Verify route and function syntax

    from flask import Flask, jsonify app = Flask(__name__) @app.route('/poll') def poll(): return jsonify({'status': 'ok'}) uses @app.route and returns jsonify({'status': 'ok'}) correctly.
  3. Final Answer:

    Correct Flask polling endpoint returning JSON with jsonify -> Option D
  4. Quick Check:

    jsonify for JSON response = from flask import Flask, jsonify app = Flask(__name__) @app.route('/poll') def poll(): return jsonify({'status': 'ok'}) [OK]
Hint: Use jsonify to return JSON responses in Flask [OK]
Common Mistakes:
  • Returning plain string instead of JSON
  • Using json.dumps without Response object
  • Returning dict directly without jsonify
3. Given this Flask polling endpoint code, what will the client receive when requesting '/poll'?
from flask import Flask, jsonify
app = Flask(__name__)

@app.route('/poll')
def poll():
    data = {'message': 'Hello', 'count': 5}
    return jsonify(data)
medium
A. Hello 5
B. {"message": "Hello", "count": 5}
C. {message: Hello, count: 5}
D. Error: jsonify not defined

Solution

  1. Step 1: Understand jsonify output

    jsonify converts Python dict to JSON string with double quotes and correct syntax.
  2. Step 2: Check returned data format

    The returned JSON string will be {"message": "Hello", "count": 5} as a JSON response.
  3. Final Answer:

    {"message": "Hello", "count": 5} -> Option B
  4. Quick Check:

    jsonify returns JSON string = {"message": "Hello", "count": 5} [OK]
Hint: jsonify returns JSON string with double quotes [OK]
Common Mistakes:
  • Expecting plain text instead of JSON
  • Confusing Python dict syntax with JSON
  • Assuming jsonify is undefined
4. Identify the error in this Flask polling endpoint code:
from flask import Flask, jsonify
app = Flask(__name__)

@app.route('/poll')
def poll():
    data = {'status': 'ok'}
medium
A. Function poll() is missing a return statement
B. Missing @app.route decorator
C. Flask app is not created properly
D. Returning a dict directly without using jsonify causes an error

Solution

  1. Step 1: Check for return statement

    The poll() function defines data but does not return it.
  2. Step 2: Verify function completeness

    Missing return statement means the endpoint returns None by default, causing unexpected empty response.
  3. Final Answer:

    Function poll() is missing a return statement -> Option A
  4. Quick Check:

    Missing return in view function [OK]
Hint: Always include return statement in Flask route handlers [OK]
Common Mistakes:
  • Missing return statement in route function
  • Forgetting route decorator
  • Not creating Flask app instance
5. You want to implement polling as a fallback in a Flask app that first tries WebSocket for real-time updates. Which approach correctly combines both methods?
hard
A. Use WebSocket and polling simultaneously without fallback logic
B. Only use polling and ignore WebSocket support
C. Use WebSocket for updates; if unsupported, client polls '/poll' endpoint every 5 seconds
D. Use polling only on the server side without client requests

Solution

  1. Step 1: Understand fallback strategy

    Fallback means trying WebSocket first, then polling if WebSocket fails or is unsupported.
  2. Step 2: Identify correct client-server interaction

    Client tries WebSocket; if it fails, client sends repeated requests to '/poll' endpoint every few seconds.
  3. Final Answer:

    Use WebSocket for updates; if unsupported, client polls '/poll' endpoint every 5 seconds -> Option C
  4. Quick Check:

    Fallback = WebSocket then polling [OK]
Hint: Try WebSocket first, then poll if needed [OK]
Common Mistakes:
  • Ignoring fallback and using only polling
  • Using polling without client requests
  • Running both methods without fallback logic
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard