Membuat Custom Middleware di Django 1.8 dan 1.10.5

Apa fungsi middleware? Banyak, salah satunya adalah melakukan sesuatu sebelum atau sesudah request di jalankan. Pada salah satu project, saya ingin me-redirect semua request yang di URL mengandung parameter ‘PageSpeed’ ke halaman itu juga namun parameter ‘PageSpeed’ dihilangkan. Bingung ya? Begini contohnya:

URL ini:

http://www.example.com/read/1?PageSpeed=noscript

ingin saya redirect ke

http://www.example.com/read/1

Kenapa ada 2 versi Django? Karena membuat custom middleware di kedua versi tersebut berbeda. Dan inilah custom middleware yang saya buat:

Django 1.8

import re

from django.http import HttpResponsePermanentRedirect


class StripPageSpeedMiddleware(object):
    def process_request(self, request):
    req = request.build_absolute_uri()

    if 'PageSpeed=noscript' in req:
        clean_url = re.sub('[?&]PageSpeed=noscript', '', req)
        return HttpResponsePermanentRedirect(clean_url)

Django 1.10.5

import re

from django.http import HttpResponsePermanentRedirect


def StripPageSpeedParam(get_response):
    # One-time configuration and initialization.

    def middleware(request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        req = request.build_absolute_uri()
        if 'PageSpeed' in req:
            clean_url = re.sub('[?&]PageSpeed=noscript', '', req)
            return HttpResponsePermanentRedirect(clean_url)

        response = get_response(request)

        # Code to be executed for each request/response after
        # the view is called.

        return response

    return middleware

Simpan baris kode di atas ke dalam sebuah file di

myapp/mymiddleware.py

Kemudian panggil di settings.py

MIDDLEWARE_CLASSES untuk Django 1.8 atau MIDDLEWARE di Django 1.10.5. Contoh

MIDDLEWARE = [
    ...
    'myapp.mymiddleware.StripPageSpeedParam',
]
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s