Sobes.tech
Junior

What do you need to send to the browser to perform a redirect to another page?

sobes.tech AI

Answer from AI

HTTP header Location with the URL of the target page and a redirect status code (3xx).

Redirect status codes:

  • 301 Moved Permanently: The target resource has been permanently moved.
  • 302 Found: The target resource has been temporarily moved.
  • 303 See Other: The browser should get the resource from another URI using the GET method.
  • 307 Temporary Redirect: The target resource has been temporarily moved, and the browser should use the same HTTP method as the original request.
  • 308 Permanent Redirect: The target resource has been permanently moved, and the browser should use the same HTTP method as the original request.

Example of usage in Flask:

# flask
from flask import Flask, redirect, url_for # Import necessary modules

app = Flask(__name__) # Create Flask app instance

@app.route('/')
def index():
    # Redirect to another page
    return redirect(url_for('another_page'), code=302) # Use redirect and specify status 302 (temporary)

@app.route('/another_page')
def another_page():
    # Content of the target page
    return "This is another page!" # Return simple text

if __name__ == '__main__':
    app.run(debug=True) # Run Flask web server

Example of usage in Django:

# python
from django.shortcuts import redirect # Import redirect function

def my_view(request):
    # Redirect to another page
    return redirect('/another-page/', permanent=False) # Use redirect, permanent=False means 302 (temporary)

def another_view(request):
    # Content of the target page
    return HttpResponse("This is another page!") # Return HTTP response