杰瑞科技汇

Python如何获取当前请求的URL?

Of course! In Python, getting the URL from a GET request is a common task. The exact method depends on the context: are you writing a client (making a request) or a server (receiving a request)?

Python如何获取当前请求的URL?-图1
(图片来源网络,侵删)

I'll cover both scenarios in detail.


As a Client: Making a GET Request (e.g., with requests library)

This is the most common scenario. You want to send a GET request to a URL and then access the URL you just requested.

The most popular and user-friendly library for this is requests.

Step 1: Install the requests library

If you don't have it installed, open your terminal or command prompt and run:

Python如何获取当前请求的URL?-图2
(图片来源网络,侵删)
pip install requests

Step 2: Get the URL from a GET Request

When you make a request with the requests library, the response object contains the original URL. This is useful if you were redirected, as it will show you the final URL.

Here are the key attributes to use:

  • response.request.url: This is the most reliable method. It gives you the URL of the original request that generated this response. This is the one you should use.
  • response.url: This gives you the final URL after any redirects. It might be different from the URL you initially provided.

Example Code

import requests
# The URL we intend to request
original_url = "https://httpbin.org/get?name=John&age=30"
try:
    # Make the GET request
    response = requests.get(original_url)
    # --- This is the key part ---
    # Get the URL of the original request
    # This will be 'https://httpbin.org/get?name=John&age=30'
    request_url = response.request.url
    print(f"Original Request URL: {request_url}")
    # Get the final URL after any redirects
    # httpbin.org/get does not redirect, so this will be the same as above.
    # Let's try a URL that does redirect.
    redirect_url = "http://github.com"
    redirect_response = requests.get(redirect_url)
    final_url = redirect_response.url
    print(f"Final URL (after redirect): {final_url}") # Will be 'https://github.com/'
    original_request_url = redirect_response.request.url
    print(f"Original Request URL (that was redirected): {original_request_url}") # Will be 'http://github.com'
    # You can also access other parts of the original request
    http_method = response.request.method
    print(f"HTTP Method used: {http_method}") # Will be 'GET'
except requests.exceptions.RequestException as e:
    print(f"An error occurred: {e}")

Key Takeaway for Clients: Use response.request.url to get the exact URL you sent the request to.


As a Server: Receiving a GET Request (e.g., with Flask or Django)

In this scenario, you are building a web server, and you need to get the URL from the incoming GET request to process it.

Python如何获取当前请求的URL?-图3
(图片来源网络,侵删)

The method depends entirely on the web framework you are using.

A. Using Flask

Flask provides a global request object from the flask module.

  • request.url: The full URL with the scheme, host, path, and query string.
  • request.base_url: The URL with scheme, host, and path, but without the query string.
  • request.path: Only the path part of the URL (e.g., /user/profile).
  • request.args: An object containing the query string parameters (e.g., {'name': 'John', 'age': '30'}).

Example Flask Code

from flask import Flask, request
app = Flask(__name__)
@app.route('/welcome')
def welcome_user():
    # Get the full URL including query parameters
    full_url = request.url
    # Example: http://127.0.0.1:5000/welcome?user=Alice&from=Canada
    # Get the URL without query parameters
    base_url = request.base_url
    # Example: http://127.0.0.1:5000/welcome
    # Get only the path
    path = request.path
    # Example: /welcome
    # Get query parameters as a dictionary-like object
    query_params = request.args
    # You can access them like: query_params.get('user') -> 'Alice'
    # query_params.get('from') -> 'Canada'
    return f"""
    <h1>Welcome Page</h1>
    <p>Full URL: {full_url}</p>
    <p>Base URL: {base_url}</p>
    <p>Path: {path}</p>
    <p>Query Params: {dict(query_params)}</p>
    """
if __name__ == '__main__':
    app.run(debug=True)

To run this, save it as app.py and run flask run. Then visit http://127.0.0.1:5000/welcome?user=Alice&from=Canada in your browser.

B. Using Django

Django uses a class-based HttpRequest object, which is typically passed as an argument to your view function (often named request).

  • request.get_full_path(): Returns the full path, including the query string (e.g., /articles/2025/?name=John).
  • request.build_absolute_uri(): Returns the full, absolute URL with scheme and host (e.g., http://example.com/articles/2025/?name=John).
  • request.path: Returns only the path, without the query string (e.g., /articles/2025/).
  • request.GET: An object-like dictionary containing the query string parameters.

Example Django View

# In your app's views.py
from django.http import HttpResponse
def welcome_view(request):
    # Get the full path including query string
    full_path = request.get_full_path()
    # Example: /welcome?user=Alice&from=Canada
    # Get the absolute URL of the current request
    absolute_url = request.build_absolute_uri()
    # Example: http://127.0.0.1:8000/welcome?user=Alice&from=Canada
    # Get only the path
    path = request.path
    # Example: /welcome
    # Get query parameters
    query_params = request.GET
    # You can access them like: query_params.get('user') -> 'Alice'
    response_message = f"""
    <h1>Welcome Page</h1>
    <p>Full Path: {full_path}</p>
    <p>Absolute URL: {absolute_url}</p>
    <p>Path: {path}</p>
    <p>Query Params: {dict(query_params)}</p>
    """
    return HttpResponse(response_message)

Summary Table

Context Goal Method / Attribute Library/Framework
Client Get the URL I sent a request to. response.request.url requests
Client Get the final URL after redirects. response.url requests
Server Get the full URL of the incoming request. request.url Flask
Server Get the path + query string of the incoming request. request.get_full_path() Django
Server Get the query string parameters. request.args (Flask) or request.GET (Django) Flask / Django
分享:
扫描分享到社交APP
上一篇
下一篇