Flask Comprehensive Quiz & Projects
30 questions on Flask Basics Tutorial.
Question 1: In Flask, what is the difference between the Application Context and the Request Context?
- A. Application context handles database connection pools, while request context compiles HTML templates.
- B. Application context tracks application-level variables (e.g. current_app, g), while request context tracks request-level variables (e.g. request, session). β (correct answer)
- C. Application context runs on the client side, while request context runs on the server side.
- D. They are identical and used interchangeably.
Explanation: Flask uses contexts to make variables globally accessible within a thread. Application context holds configuration, request context holds details of the active HTTP request.
Question 2: How does a Flask route converter like @app.route('/user/<int:id>') protect the application?
- A. By converting the database ID into an encrypted format automatically.
- B. By enforcing that the path segment matches the integer type, throwing a 404 error otherwise, and passing it as an int to the view. β (correct answer)
- C. By limiting the route to accept only positive float values.
- D. By blocking users whose usernames contain integer characters.
Explanation: Route converters validate request parameters at the URL level, casting matching values to the target type.
Question 3: What is the primary purpose of Blueprints in Flask?
- A. To generate visual system architecture diagrams of the API.
- B. To configure database replication schemas dynamically.
- C. To organize an application into distinct modules or sub-applications (e.g., auth, admin) for scalability. β (correct answer)
- D. To define the styling layout of HTML templates.
Explanation: Blueprints record operations to execute on an application, modularizing codebases and structuring large Flask applications.
Question 4: How does Flask handle session security when using client-side cookies?
- A. By encrypting the cookie payload using AES-256 keys.
- B. By storing sessions in server RAM and sending a randomized key reference.
- C. By cryptographically signing the cookie with the application's SECRET_KEY to prevent tampering. β (correct answer)
- D. By sending session data in raw plain text to reduce network footprint.
Explanation: Flask signs client-side cookies. Users can read session variables but cannot modify them without invalidating the signature.
Question 5: Which module is typically used to enable Cross-Origin Resource Sharing (CORS) in a Flask API?
- A. flask_ssl
- B. flask_cors β (correct answer)
- C. flask_headers
- D. flask_security
Explanation: The flask_cors package handles cross-origin requests, adding required headers to preflight options.
Question 6: What is the default port Flask development server runs on?
- A. 8000
- B. 5000 β (correct answer)
- C. 3000
- D. 8080
Explanation: By default, app.run() hosts the local microframework server on port 5000.
Question 7: How do you access JSON request bodies in a Flask route handler?
- A. request.json()
- B. request.get_json() β (correct answer)
- C. request.body.json
- D. request.form['json']
Explanation: request.get_json() parses incoming application/json headers, returning Python dictionaries.
Question 8: What does the 'g' object represent in Flask?
- A. Global variables that persist across all server restarts.
- B. A developer-managed namespace for temporary variables that are reset on every HTTP request. β (correct answer)
- C. The master database model connector.
- D. The configuration keys list.
Explanation: Flask's g object is a request-bound global storage for variables like database connections or users.
Question 9: Which function renders Jinja2 template files in Flask?
- A. render_html()
- B. render_template() β (correct answer)
- C. load_view()
- D. render_view()
Explanation: render_template(filename, **context) loads files from templates/ and compiles Jinja tags.
Question 10: In Flask, how do you redirect a user to a different endpoint named 'login'?
- A. redirect(url_for('login')) β (correct answer)
- B. redirect('/login')
- C. goto('login')
- D. response.redirect('login')
Explanation: url_for() dynamically resolves routes based on functions, preventing hardcoded path bugs.
Question 11: What is the Application Factory pattern in Flask?
- A. A tool to compile CSS files during runtime.
- B. A design pattern where the Flask application object is instantiated inside a function (e.g. create_app()), enabling multiple test instances. β (correct answer)
- C. A class that generates database schemas automatically.
- D. A server configuration wrapper.
Explanation: The factory pattern makes testing and configuration changes clean, avoiding global app declarations.
Question 12: How do you capture query string parameters (e.g., ?page=2) in a Flask request?
- A. request.query.page
- B. request.args.get('page') β (correct answer)
- C. request.form['page']
- D. request.params['page']
Explanation: request.args is a MultiDict containing the parsed key-values from the URL query parameters.
Question 13: What template engine does Flask use out of the box?
- A. Blade
- B. Jinja2 β (correct answer)
- C. Pug
- D. Django Templates
Explanation: Jinja2 is the default sandboxed template engine, using syntax like {{ }} and {% %}.
Question 14: How do you register a custom error handler in Flask for a 404 Page Not Found error?
- A. @app.error(404)
- B. @app.errorhandler(404) β (correct answer)
- C. @app.handle_error(404)
- D. @app.catch(404)
Explanation: Theerrorhandler decorator maps specific HTTP status codes or Python exceptions to custom templates.
Question 15: Which Flask extension is standard for handling database migrations?
- A. Flask-SQLAlchemy
- B. Flask-Migrate β (correct answer)
- C. Flask-DB
- D. Alembic-Flask
Explanation: Flask-Migrate utilizes Alembic to handle schema migrations for SQLAlchemy models.
Question 16: How do you define a route that accepts only POST requests in Flask?
- A. @app.post('/route')
- B. @app.route('/route', methods=['POST']) β (correct answer)
- C. @app.route('/route', type='POST')
- D. @app.add_post('/route')
Explanation: The methods argument limits the HTTP methods that the route handler will accept.
Question 17: What is Flask-WTF primarily used for?
- A. Caching views to Redis databases.
- B. Form validation, rendering, and CSRF protection wrapper for Flask. β (correct answer)
- C. Multi-threaded network routing.
- D. Logging server errors to files.
Explanation: Flask-WTF integrates WTForms with Flask, securing forms with CSRF validation by default.
Question 18: What does flash() do in a Flask application?
- A. Reboots the development server.
- B. Saves a message to the session that can be retrieved and displayed on the next request view (flash messages). β (correct answer)
- C. Clears the browser cache instantly.
- D. Deletes session cookie parameters.
Explanation: Flashing is useful for sending status notifications (e.g. 'Saved!') across redirects.
Question 19: Which dictionary-like object represents a user's signed, client-side session data in Flask?
- A. request.session
- B. session β (correct answer)
- C. g.session
- D. request.cookies
Explanation: The session object works like a dict, storing variables cryptographically signed by the server.
Question 20: What is the function of the Flask CLI?
- A. It compiles python binary modules.
- B. It provides command-line commands for running servers, executing migrations, and opening shell contexts. β (correct answer)
- C. It allows users to write SQL queries.
- D. It configures network firewalls.
Explanation: Custom commands can be defined to run script tasks within the application context.
Question 21: How does Flask-SQLAlchemy declare a database table relationship?
- A. db.ForeignKey()
- B. db.relationship() β (correct answer)
- C. db.join()
- D. db.Column(relationship)
Explanation: db.relationship() defines a high-level model connection, fetching related records automatically.
Question 22: How do you access uploaded files in a Flask route handler?
- A. request.body.files
- B. request.files β (correct answer)
- C. request.form['files']
- D. request.get_files()
Explanation: request.files is a MultiDict holding files parsed from multipart/form-data payloads.
Question 23: How do you return a JSON response with status code 400 from a Flask view?
- A. return jsonify(error='Invalid'), 400 β (correct answer)
- B. return json.dumps({'error': 'Invalid'}), 400
- C. return make_response('Invalid', 400)
- D. return abort(400, 'Invalid')
Explanation: Flask views allow returning tuples in the format (response, status_code).
Question 24: What is the function of a context processor in Flask?
- A. It speeds up payload parsing speeds.
- B. A mechanism to inject variables automatically into all Jinja2 templates without passing them to render_template(). β (correct answer)
- C. It compiles SCSS files to CSS.
- D. It opens database transactions.
Explanation: @app.context_processor returns a dictionary of keys available globally to all layouts.
Question 25: Which function instantly halts a Flask route, returning a specified HTTP error code?
- A. stop()
- B. abort() β (correct answer)
- C. terminate()
- D. fail()
Explanation: abort(code) raises an HTTP exception that is caught by errorhandlers to render error pages.
Question 26: What is Flask?
- A. A relational database management engine.
- B. A WSGI micro web framework written in Python, designed to be simple and highly extensible. β (correct answer)
- C. A package compiler for python assets.
- D. A server container manager.
Explanation: Flask is a microframework because it does not require particular tools or libraries.
Question 27: What does it mean if you run Flask with debug=True?
- A. The server runs on port 80.
- B. The server auto-reloads on file modifications and provides an interactive debugger in the browser on crash. β (correct answer)
- C. The database is formatted on every reload.
- D. The server runs in multi-threaded mode only.
Explanation: Debug mode is critical for local development but must be disabled in production for security.
Question 28: Which WSGI server is standard for deploying Flask applications in production?
- A. Apache
- B. gunicorn β (correct answer)
- C. Node.js
- D. Nginx
Explanation: gunicorn is a production-ready, multi-process WSGI HTTP server designed for Python apps.
Question 29: How do you execute logic before every request handler in Flask?
- A. @app.before
- B. @app.before_request β (correct answer)
- C. @app.middleware
- D. @app.preprocess
Explanation: Functions decorated with before_request execute before the matching view, useful for auth.
Question 30: Which object parses incoming form inputs in standard POST requests?
- A. request.args
- B. request.form β (correct answer)
- C. request.body
- D. request.inputs
Explanation: request.form holds key-value fields submitted via URL-encoded form POST requests.