Skip to content

Django 调用

2024-08-20
python
import os
import json

from openai import OpenAI
from django.conf import settings
from django.http import HttpRequest
from django.http import JsonResponse
from django.urls import path
from django.core.wsgi import get_wsgi_application
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods

# Django settings
settings.configure(
    DEBUG=True,
    SECRET_KEY="your_secret_key_here",
    ROOT_URLCONF=__name__,
    MIDDLEWARE=[
        "django.middleware.common.CommonMiddleware",
        "django.middleware.csrf.CsrfViewMiddleware",
    ],
    INSTALLED_APPS=[
        "django.contrib.auth",
        "django.contrib.contenttypes",
    ],
)

# OpenAI client setup
openai_client = OpenAI(
    api_key=os.getenv("OPENAI_API_KEY"),
    base_url=os.getenv("OPENAI_BASE_URL"),
)


def generate_response(text: str) -> str | None:
    response = openai_client.chat.completions.create(
        model="yi-medium",
        messages=[{"role": "user", "content": text}],
        stream=False,
    )
    return response.choices[0].message.content


@csrf_exempt
@require_http_methods(["POST"])
def chat(request: HttpRequest) -> JsonResponse:
    data = json.loads(request.body)
    text = data.get("text")
    if not text:
        return JsonResponse({"error": "No text provided"}, status=400)

    response_text = generate_response(text)
    return JsonResponse(
        {"response": response_text},
        charset="utf-8",
        json_dumps_params={"ensure_ascii": False},
    )


# URL configuration
urlpatterns = [
    path("chat", chat, name="chat"),
]

# WSGI application
application = get_wsgi_application()

if __name__ == "__main__":
    from django.core.management import execute_from_command_line

    execute_from_command_line(["manage.py", "runserver", "0.0.0.0:8000"])