Login

Protect anti robots template tag

Author:
marinho
Posted:
May 6, 2008
Language:
Python
Version:
.96
Score:
1 (after 1 ratings)

This code works like that in the Google Groups you see and when try to see an e-mail and it is like this "[email protected]" with a link to write a captcha code and see the true value.

You can use it for anything you want: links, blocks of texts, block of HTML, etc.

To use in your template, place the a code like this (remember to load the template tags file with a {% load file_name %} before):

{% protectantirobots %}
  <a href="mailto: {{ office.email }}">{{ office.email }}</a>
{% endprotectantirobots %}

You can also use django-plus application to do this:

http://code.google.com/p/django-plus/

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
# Middleware

import hmac, sha, base64, os

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse
from django.utils.translation import ugettext as _

class ProtectAntiRobotsMiddleware(object):
    def process_request(self, request):
        if request.get_full_path().startswith('/protectantirobots/'):
            if request.get_full_path() == '/protectantirobots/img/':
                s = base64.b64decode(request.session['protectantirobots_key'])
                size = (100,30)
                img = Image.new("RGB", size, "white")

                draw = ImageDraw.Draw(img)
                font = ImageFont.truetype(os.path.dirname(__file__)+"/FreeSansBold.ttf", 24)
                draw.text((2,2), s, fill="red", font=font)

                draw.line((0, 0) + img.size, fill=128)
                draw.line((0, img.size[1], img.size[0], 0), fill=128)
                del draw

                ret = HttpResponse(mimetype='image/gif')
                img.save(ret, "GIF")
                return ret
            elif 'k' in request.GET:
                if request.POST:
                    n = request.POST['n']
                    sec = base64.b64decode(request.session['protectantirobots_key'])
                    if n == sec:
                        request.session['protectantirobots_sec'] = sec
                        return HttpResponseRedirect(request.session['protectantirobots_referer'])
                    return render_to_response(
                        'protectantirobots.html',
                        {'msg': _('Invalid number!')},
                        context_instance=RequestContext(request),
                        )
                else:
                    request.session['protectantirobots_key'] = request.REQUEST['k']
                    request.session['protectantirobots_referer'] = request.META.get('HTTP_REFERER', '')
                    return render_to_response(
                        'protectantirobots.html',
                        locals(),
                        context_instance=RequestContext(request),
                        )

# Template tag

import base64
from datetime import datetime, timedelta

from django.template import Library, Node
from django.utils.translation import ugettext as _

class ProtectAntiRobotsNode(Node):
    nodelist = ''

    def __init__(self, nodelist):
        super(ProtectAntiRobotsNode, self).__init__()

        self.nodelist = nodelist

    def __repr__(self):
        return "<ProtectAntiRobotsNode>"

    def render(self, context):
        request = context['request']
        if 'protectantirobots_sec' in request.session and \
           'protectantirobots_key' in request.session:
            if request.session['protectantirobots_sec'] == base64.b64decode(request.session['protectantirobots_key']):
                output = self.nodelist.render(context)
                return output
        
        sec = base64.b64encode(datetime.now().strftime("%H%m%S"))
        return '<a href="%s">%s</a>' %(self.get_url(sec), _('Let us know if you are human'))

    def get_url(self, sec):
        return "/protectantirobots/?k=" + sec

def do_protectantirobots(parser, token):
    nodelist = parser.parse(('endprotectantirobots',))
    parser.delete_first_token()
    return ProtectAntiRobotsNode(nodelist)
do_protectantirobots= register.tag('protectantirobots', do_protectantirobots)

# Template (protectantirobots.html file) - you can change layout and other things

<html>
    <body>
        What number is this?
        <form method="post">
            <img src="/protectantirobots/img/"/>
            <input name="n"/>
            <input type="submit"/>
        </form>

        {% if msg %}
        <strong>{{ msg }}</strong>
        {% endif %}
    </body>
</html>

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

marinho (on August 12, 2008):

Fixed line 65 (not subscriptable request object)

#

Please login first before commenting.