[파이썬] aiohttp 응답 헤더 다루기

When working with web applications using the aiohttp library in Python, it is important to understand how to handle response headers. Response headers provide valuable information about the server’s response and can be used to extract important details or modify the behavior of the client.

In this blog post, we will explore how to access and manipulate response headers using aiohttp. We will cover common operations such as retrieving specific headers, modifying headers, and adding custom headers to the response.

Accessing Response Headers

To access the response headers in aiohttp, we can use the headers property of the aiohttp.ClientResponse object. This property returns a CIMultiDictProxy object, which is a case-insensitive multidict that allows easy access to header values.

Let’s see an example of how to retrieve a specific header from an aiohttp response:

import aiohttp
import asyncio

async def get_response_headers():
    async with aiohttp.ClientSession() as session:
        async with session.get('https://example.com') as response:
            # Retrieving the 'Content-Type' header
            content_type = response.headers.get('Content-Type')
            print(f"Content-Type: {content_type}")

# Running the asynchronous function
asyncio.run(get_response_headers())

In the above example, we create an aiohttp.ClientSession and make a GET request to https://example.com. We then retrieve the value of the ‘Content-Type’ header using the get method of the headers property.

Modifying Response Headers

In some cases, we may want to modify the response headers before sending them back to the client. This can be useful for adding additional headers or manipulating existing ones.

To modify response headers in aiohttp, we need to use the aiohttp.web.Response class. This class represents an HTTP response and provides methods to manipulate headers and content.

Here’s an example of how to modify response headers in aiohttp:

from aiohttp import web

async def handle_request(request):
    response = web.Response()
    response.headers['Custom-Header'] = 'Custom Value'
    response.headers['Content-Type'] = 'text/plain'
    return response

app = web.Application()
app.router.add_get('/', handle_request)
web.run_app(app)

In the above example, we define a request handler function that creates a new web.Response object. We then modify the headers property of the response object to add a custom header and set the content-type to “text/plain”. Finally, we return the modified response.

Adding Custom Headers

Adding custom headers to an aiohttp response is straightforward. We simply need to set the value of the desired header using the headers property of the response object.

Here’s an example of how to add custom headers to an aiohttp response:

from aiohttp import web

async def handle_request(request):
    response = web.Response()
    response.headers['X-Custom-Header'] = 'Custom Value'
    response.headers['X-Another-Header'] = 'Another Value'
    return response

app = web.Application()
app.router.add_get('/', handle_request)
web.run_app(app)

In the above example, we define a request handler function similar to the previous example. This time, we add two custom headers (‘X-Custom-Header’ and ‘X-Another-Header’) to the response object.

Conclusion

Handling response headers is an essential part of building web applications using the aiohttp library in Python. In this blog post, we explored how to access and manipulate response headers in aiohttp, including retrieving specific headers, modifying headers, and adding custom headers.

Understanding how to effectively work with response headers allows us to extract important information, modify the behavior of the client, and provide customized responses to our users.