django-robots

repository·master·Indexed 19 days ago

https://github.com/jazzband/django-robots

A Django application for managing robots.txt files to implement the robots exclusion protocol. It allows developers to control search engine crawlers via Rule and Url objects, integrates with the Django admin for rule management, and complements Django's built-in Sitemap support with automatic sitemap and Host directive inclusion.

Tokens
2.2K
Snippets
10
Records
13
Agent score
65%

What's inside django-robots

  1. Overview of django-robots

    master
    django-robots is a Django application used to manage robots.txt files following the robots exclusion protocol. It is designed to complement the Django Sitemap contrib app by providing a way to control how search engine crawlers interact with your site.
  2. Understand Rule and Url objects

    master

    The application uses two primary abstractions to manage robot instructions:

    Rule

    An abstract Rule defines how to respond to specific web robots (user agents). Rules can link multiple URL patterns to allow or disallow actions.

    • Crawl Delay: Supports setting a delay (in seconds) between successive crawler accesses to reduce server load.
    • Multi-site support: Uses the Django sites framework to enable different robots.txt rules per Django instance.

    Url

    An Url defines the specific pattern to match.

    • Matching: Patterns are case-sensitive and exact.
    • Trailing Slashes: A missing trailing slash in a pattern will also match files starting with that name (e.g., '/admin' matches '/admin.html').
    • Wildcards: Some search engines support * (wildcard for any sequence) and $ (end of URL). Example: '/*.jpg$' matches all JPEG files.
  3. Install django-robots

    master

    Install the package using pip and configure your Django settings to enable it.

    Installation Steps

    1. Install via PyPI:
      pip install django-robots
    2. Add 'robots' to your INSTALLED_APPS in settings.py.
    3. Ensure 'django.template.loaders.app_directories.Loader' is present in your TEMPLATES setting.
    4. Install and configure the Django sites framework.
    5. Run the database migrations:
      python manage.py migrate
    pip install django-robots
  4. Initialize robots.txt generation in URLconf

    master

    To enable the generation of robots.txt at the /robots.txt endpoint, you must include the robots.urls in your project's main urls.py file using re_path.

    from django.urls import re_path, include
    
    urlpatterns = [
        ...
        re_path(r'^robots\.txt', include('robots.urls')),
        ...
    ]
  5. Configure Host directive in robots.txt

    master

    By default, a Host statement is automatically added to the robots.txt to help select the main website and avoid mirrors.

    Configuration Options

    • Disable Host directive: Set ROBOTS_USE_HOST = False.
    • Include protocol in Host directive: To prefix the domain with the current request protocol (e.g., Host: https://www.mysite.com), set ROBOTS_USE_SCHEME_IN_HOST = True.
    ROBOTS_USE_HOST = False
    ROBOTS_USE_SCHEME_IN_HOST = True
  6. Configure Sitemap inclusion in robots.txt

    master

    By default, django-robots automatically adds a Sitemap statement to your robots.txt by reverse matching the URL of the installed Django Sitemap contrib app.

    Configuration Options

    • Disable automatic sitemap inclusion: Set ROBOTS_USE_SITEMAP = False.
    • Specify custom sitemap URLs: Provide a list of URLs via ROBOTS_SITEMAP_URLS.
    • Handle decorated or custom sitemap views: If your sitemap view uses a decorator (like cache_page) or is a custom view (e.g., Wagtail), the automatic discovery via dotted path might fail. To fix this, name your sitemap view in urls.py and provide that name to ROBOTS_SITEMAP_VIEW_NAME.

    Example for decorated sitemaps:

    In urls.py:

    re_path(r'^sitemap\.xml$', cache_page(60)(sitemap_view, {'sitemaps': [...]}), name='cached-sitemap')

    In settings.py:

    ROBOTS_SITEMAP_VIEW_NAME = 'cached-sitemap'
    ROBOTS_USE_SITEMAP = False
    ROBOTS_SITEMAP_URLS = ['http://www.example.com/sitemap.xml']
    ROBOTS_SITEMAP_VIEW_NAME = 'cached-sitemap'
  7. Configure robots.txt caching

    master

    You can cache the generated robots.txt output to improve performance. Use the ROBOTS_CACHE_TIMEOUT setting to specify the cache duration in seconds.

    Example (24-hour cache):

    ROBOTS_CACHE_TIMEOUT = 60*60*24

    If set to None (the default), no caching is applied.

    ROBOTS_CACHE_TIMEOUT = 86400
  8. Manage robots rules via Django Admin

    master

    The django-robots package provides built-in Django Admin integration to manage Rule and Url objects.

    • Rules (RuleAdmin): Allows you to define which robots (e.g., Googlebot) are subject to specific rules. It includes fieldsets for robot identification, site association, URL patterns (allowed/disallowed), and advanced options like crawl_delay.
    • URL Patterns (Url): Individual URL patterns associated with rules can be managed directly.

    To enable this in your Django project, ensure robots is included in your INSTALLED_APPS and that you have configured the Django admin site.

  9. Serve the robots.txt file using RuleList

    master

    The RuleList view is the primary entry point for serving a generated robots.txt file. It returns the file with a text/plain MIME type and automatically handles sitemap URL inclusion based on your project's configuration.

    To use it, you should point a URL pattern to rules_list (which is the as_view() instance of RuleList).

    from django.urls import path
    from robots.views import rules_list
    
    urlpatterns = [
        path('robots.txt', rules_list),
    ]
  10. Retrieve allowed and disallowed URLs from a Rule

    master

    The Rule model provides helper methods to get a human-readable list of associated URL patterns.

    • allowed_urls(): Returns a string containing a list of all URLs in the allowed relationship.
    • disallowed_urls(): Returns a string containing a list of all URLs in the disallowed relationship.
    # Assuming 'rule' is an instance of Rule
    print(rule.allowed_urls())
    print(rule.disallowed_urls())
  11. Configure robots.txt rules with the Rule model

    master

    The Rule model defines how specific web robots (user agents) interact with your site. It maps robots to allowed or disallowed URL patterns.

    Fields and Configuration:

    • robot: The user agent string (e.g., 'Googlebot'). Use an asterisk (*) to target all user agents.
    • allowed: A ManyToMany relationship to Url objects representing paths the robot is permitted to access.
    • disallowed: A ManyToMany relationship to Url objects representing paths the robot is forbidden from accessing.
    • crawl_delay: A decimal value (0.1 to 99.0) defining the delay in seconds between successive crawler accesses. This helps manage server load.
    • sites: A ManyToMany relationship to Site (from django.contrib.sites), allowing you to serve different robots.txt rules per domain/site instance.
    from robots.models import Rule, Url
    from django.contrib.sites.models import Site
    
    # 1. Create URL patterns
    admin_url = Url(pattern='/admin/')
    
    # 2. Create a rule for Googlebot
    google_rule = Rule(
        robot='Googlebot',
        crawl_delay=1.0
    )
    
    # 3. Assign patterns and site
    google_rule.allowed.add(admin_url)
    google_rule.sites.add(Site.objects.get(id=1))
    
    google_rule.save()