Flask Basics


What is Flask?

Flask is a lightweight, micro web framework written in Python. It is designed to be simple and easy to use, providing the basic tools needed to build a web application. Flask follows the WSGI standard and is often chosen for its flexibility and simplicity, allowing developers to build scalable applications with minimal overhead.


What is the difference between Flask and Django?

Flask and Django are both web frameworks for Python, but they have key differences:

  • Flask: A micro-framework that provides the basic tools needed to build a web application, without enforcing any particular project structure or dependencies. Flask offers flexibility and simplicity.
  • Django: A full-stack framework that comes with built-in features like an ORM, admin panel, and authentication. Django follows the "batteries-included" philosophy, offering more structure and ready-to-use tools.

How do you install Flask?

You can install Flask using pip, the Python package manager. Run the following command to install Flask:

pip install Flask

Once installed, you can verify the installation by importing Flask in a Python script or running flask --version in the terminal.


How do you create a simple Flask application?

To create a simple Flask application, you first need to import the Flask class, create an instance of it, define routes, and run the application. Here's an example of a minimal Flask app:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return "Hello, Flask!"

if __name__ == '__main__':
    app.run(debug=True)

In this example, the application defines a single route for the root URL /, which returns the message "Hello, Flask!" when accessed.


What is the purpose of the @app.route() decorator in Flask?

The @app.route() decorator in Flask is used to define a URL route for your application. It tells Flask which URL should trigger a specific function. When a user accesses the specified URL, Flask calls the corresponding function and returns the result to the user.

Example of using @app.route():

@app.route('/about')
def about():
    return "About Page"

In this example, when a user navigates to /about, the about function is called, and it returns the string "About Page" as the response.


What is the purpose of debug=True in app.run()?

Setting debug=True in app.run() enables Flask's debug mode. This allows for better development experience by automatically reloading the application when code changes, and it provides an interactive debugger in case of errors.

Example of enabling debug mode:

if __name__ == '__main__':
    app.run(debug=True)

In this example, the Flask application runs in debug mode, meaning that any code changes are reflected without needing to restart the server, and detailed error messages are displayed in the browser if exceptions occur.


What are Flask routes?

Flask routes are URL patterns that map to view functions. Each route is defined using the @app.route() decorator, and when a user visits the specified URL, the corresponding view function is executed. Routes can include dynamic components, allowing you to capture variables from the URL.

Example of a route with a dynamic component:

@app.route('/user/<username>')
def show_user(username):
    return f"User: {username}"

In this example, the route /user/<username> captures the username from the URL and passes it to the show_user function.


What are URL variables in Flask?

URL variables in Flask allow you to capture dynamic values from the URL and pass them as arguments to the view function. These variables are defined using angle brackets <> in the route definition.

Example of using URL variables:

@app.route('/profile/<username>')
def profile(username):
    return f"Profile of {username}"

In this example, the URL variable <username> captures the username from the URL, and the profile function uses it to generate a response.


How do you handle HTTP methods in Flask?

By default, Flask routes handle only GET requests. However, you can specify multiple HTTP methods for a route by passing the methods argument to the @app.route() decorator. Flask supports methods like GET, POST, PUT, DELETE, etc.

Example of handling both GET and POST requests:

@app.route('/submit', methods=['GET', 'POST'])
def submit():
    if request.method == 'POST':
        return "Form submitted"
    return "Submit Form"

In this example, the route /submit handles both GET and POST requests. If the request method is POST, it returns "Form submitted"; otherwise, it returns "Submit Form".


How do you pass data from the URL to a Flask view?

You can pass data from the URL to a Flask view by using URL variables in the route. The variables are captured from the URL and passed as arguments to the view function.

Example of passing data from the URL:

@app.route('/item/<int:item_id>')
def show_item(item_id):
    return f"Item ID: {item_id}"

In this example, the URL /item/<item_id> captures an integer item_id from the URL and passes it to the show_item function.


What is the Flask request object?

The Flask request object contains all the data sent by the client to the server, including form data, query parameters, headers, and more. It allows you to access incoming data from POST and GET requests, as well as file uploads and cookies.

Example of using the request object to access form data:

from flask import request

@app.route('/login', methods=['POST'])
def login():
    username = request.form['username']
    password = request.form['password']
    return f"Logging in with {username}"

In this example, the request object is used to access form data sent in a POST request.

Ads