llms.txt لـ Django

أربعة نهوج لـ Django: ملف ثابت (يقدمه Nginx)، وعرض بسيط يعيد HttpResponse، وعرض ديناميكي مولد من نماذج قاعدة بياناتك، أو عرض مخزّن مؤقتاً للمواقع عالية الحركة.

آخر تحديث:

الخيار 1: ملف ثابت عبر STATICFILES_DIRS

صيغة Django staticfiles ينسخ الملفات من STATICFILES_DIRS إلى STATIC_ROOT عند تشغيلك collectstatic. ويمكنك عندها ضبط Nginx لتقديم الملف مباشرةً، لكن لاحظ أن عنوان URL سيكون تحت STATIC_URL البادئة (مثلاً /static/llms.txt)، لا في الجذر.

static/llms.txt, approach notes
# Django static file approach
#
# 1. Place llms.txt in one of your STATICFILES_DIRS:
#    myproject/
#    ├── static/
#    │   └── llms.txt   ← add this
#    └── myapp/
#
# 2. In settings.py, make sure STATICFILES_DIRS includes the static/ folder:
#    STATICFILES_DIRS = [BASE_DIR / "static"]
#
# 3. Run collectstatic to copy it to STATIC_ROOT:
#    python manage.py collectstatic
#
# NOTE: Django's staticfiles serve files under the STATIC_URL prefix (/static/ by default).
# This means the file will be at /static/llms.txt, NOT /llms.txt.
# Use the view approach below to serve at the root path /llms.txt.

للتقديم على /llms.txt من ملفاتك الثابتة، واضبط Nginx باستخدام alias توجيه يشير إلى الملف المجموع في STATIC_ROOT. راجع مقتطف Nginx في قسم النشر أدناه.

الخيار 2: عرض مخصص مع HttpResponse

أنظف نهج في Django هو عرض بسيط يعيد محتوى الملف مع content_type. ويعمل هذا مع أي هدف نشر ويقدم الملف بالضبط على /llms.txt.

myapp/views.py
# myapp/views.py
from django.http import HttpResponse

LLMS_TXT_CONTENT = """# My Site

> One-sentence description of what my site or product does.

## Documentation

- [Getting Started](https://mysite.com/docs/start/): Install and configure in minutes.
- [API Reference](https://mysite.com/docs/api/): Full endpoint catalog with examples.

## Product

- [Overview](https://mysite.com/product/): Core features and capabilities.
- [Pricing](https://mysite.com/pricing/): Plans and billing details.

## Optional

- [Changelog](https://mysite.com/changelog/): Release history.
- [GitHub](https://github.com/my-org/my-repo): Source code.
"""


def llms_txt(request):
    return HttpResponse(
        LLMS_TXT_CONTENT,
        content_type="text/plain; charset=utf-8",
        headers={
            "Cache-Control": "public, max-age=3600, stale-while-revalidate=86400",
        },
    )

اربطه في جذر موقعك urls.py:

myproject/urls.py
# myproject/urls.py
from django.urls import path
from myapp.views import llms_txt

urlpatterns = [
    # Serve at /llms.txt (root path)
    path("llms.txt", llms_txt, name="llms-txt"),
    # ... your other URL patterns
]

الـ path("llms.txt", ...) نمط (من دون شرطة مائلة أولى) يطابق عنوان URL /llms.txt. يزيل Django الشرطة المائلة الأولى قبل المطابقة.

الخيار 3: توليد ديناميكي من النماذج

بالنسبة إلى المواقع التي تُخزَّن صفحات توثيقها في قاعدة البيانات، ولّد محتوى الملف من queryset. استخدم المضمّن في Django cache_page الزخرفة لتجنب ضرب قاعدة البيانات في كل طلب.

myapp/views.py, dynamic
# myapp/views.py
# Dynamic generation from database models
from django.http import HttpResponse
from django.views.decorators.cache import cache_page
from myapp.models import DocumentPage


# Cache for 1 hour, regenerated automatically when cache expires
@cache_page(60 * 60)
def llms_txt(request):
    docs = DocumentPage.objects.filter(
        published=True,
        include_in_llms=True,
    ).order_by("order").values("title", "slug", "summary")

    lines = ["# My Site", "", "> Documentation and API reference.", "", "## Documentation", ""]

    for doc in docs:
        url = f"https://mysite.com/docs/{doc['slug']}/"
        lines.append(f"- [{doc['title']}]({url}): {doc['summary']}")

    lines += [
        "",
        "## Optional",
        "",
        "- [Changelog](https://mysite.com/changelog/): Release history.",
    ]

    return HttpResponse(
        "\n".join(lines),
        content_type="text/plain; charset=utf-8",
    )

أضف حقلاً منطقياً include_in_llms إلى نموذجك للتحكم في الصفحات التي تظهر في الملف. شغّل المدقّق بعد أي ترحيل للمحتوى لاكتشاف تراجعات الصياغة.

نشر WSGI/ASGI ‏(Gunicorn وuWSGI وNginx)

يعمل عرض Django مع جميع إعدادات النشر الشائعة. والعرض نفسه متزامن وخفيف ولا يحتاج إلى async.

nginx.conf, proxy to Gunicorn
# nginx.conf snippet, proxy to Gunicorn upstream
server {
    listen 80;
    server_name mysite.com;

    # Serve llms.txt directly from Gunicorn (Django view)
    location = /llms.txt {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_cache_valid 200 1h;
        add_header Cache-Control "public, max-age=3600";
    }

    # Optionally serve a pre-built static copy faster:
    # location = /llms.txt {
    #     alias /srv/mysite/static_root/llms.txt;
    #     add_header Content-Type "text/plain; charset=utf-8";
    # }
}
  • Gunicorn، ويعمل فوراً. يعيد العرض استجابة 200 مع text/plain؛ لا يلزم إعداد خاص.
  • uWSGI، مثل Gunicorn. وإذا استخدمت تقديم الملفات الثابتة في uWSGI، يمكنك ربط /llms.txt مباشرةً إلى ملف في STATIC_ROOT مع static-map = /llms.txt=/path/to/llms.txt.
  • ASGI (Daphne وUvicorn)، ويكون العرض متوافقاً كما هو. ويغلف Django العروض المتزامنة تلقائياً في منفذ خيوط.
  • ذاكرة Nginx المؤقتة، أضف proxy_cache_valid 200 1h في كتلة موقع Nginx لتخزين الاستجابة مؤقتاً على طبقة البروكسي وتجنب الوصول إلى Django في كل طلب زاحف.

تحقّق

بعد النشر، تأكد من تقديم الملف بصورة صحيحة:

Verification
curl -I https://mysite.com/llms.txt
# Expected:
# HTTP/2 200
# content-type: text/plain; charset=utf-8

curl https://mysite.com/llms.txt | head -5
# Should print the first lines of your file

أدلة ذات صلة

المصادر