-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path03_django_example.py
More file actions
153 lines (128 loc) · 5.21 KB
/
03_django_example.py
File metadata and controls
153 lines (128 loc) · 5.21 KB
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
"""
Example: Deploying a Django REST Framework application as an MCP server.
This example shows how to deploy a Django REST Framework application
using the Tadata SDK. This is a complete working example that sets up
a minimal Django configuration with drf-spectacular.
"""
import os
import django
from django.conf import settings
from tadata_sdk import deploy
def setup_django():
"""Set up a minimal Django configuration for demonstration."""
if not settings.configured:
settings.configure(
DEBUG=True,
SECRET_KEY="demo-secret-key-not-for-production",
INSTALLED_APPS=[
"django.contrib.contenttypes",
"django.contrib.auth",
"rest_framework",
"drf_spectacular",
],
REST_FRAMEWORK={
"DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",
},
SPECTACULAR_SETTINGS={
"TITLE": "Demo Django API",
"DESCRIPTION": "A demonstration Django REST Framework API",
"VERSION": "1.0.0",
},
ROOT_URLCONF=__name__, # Use this module as the URL config
USE_TZ=True,
)
django.setup()
def create_demo_api():
"""Create a simple Django REST API for demonstration."""
from django.urls import path, include
from rest_framework import serializers, viewsets, routers
from rest_framework.decorators import api_view
from rest_framework.response import Response
# Simple serializer
class ItemSerializer(serializers.Serializer):
id = serializers.IntegerField()
name = serializers.CharField(max_length=100)
description = serializers.CharField(max_length=500, required=False)
# Simple viewset
class ItemViewSet(viewsets.ViewSet):
"""A simple ViewSet for managing items."""
def list(self, request):
"""List all items."""
items = [
{"id": 1, "name": "Item 1", "description": "First item"},
{"id": 2, "name": "Item 2", "description": "Second item"},
]
serializer = ItemSerializer(items, many=True)
return Response(serializer.data)
def retrieve(self, request, pk=None):
"""Retrieve a specific item."""
item = {"id": int(pk), "name": f"Item {pk}", "description": f"Item number {pk}"}
serializer = ItemSerializer(item)
return Response(serializer.data)
# Simple API view
@api_view(["GET"])
def hello_world(request):
"""A simple hello world endpoint."""
return Response({"message": "Hello from Django!"})
# Setup URL routing
router = routers.DefaultRouter()
router.register(r"items", ItemViewSet, basename="item")
# URL patterns (this module serves as ROOT_URLCONF)
global urlpatterns
urlpatterns = [
path("api/", include(router.urls)),
path("hello/", hello_world, name="hello"),
]
def main():
"""Deploy Django REST Framework application."""
print("Setting up Django configuration...")
setup_django()
print("Creating demo API...")
create_demo_api()
print("Django setup complete! Now deploying to Tadata...")
# Get API key (you would set this in your environment)
api_key = os.getenv("TADATA_API_KEY")
if not api_key:
print("⚠️ TADATA_API_KEY environment variable not set.")
print(" For a real deployment, you would need to set this.")
print(" For this demo, we'll show what the call would look like:")
print()
print(" result = deploy(")
print(" use_django=True,")
print(" api_key='your-api-key-here',")
print(" name='my-django-api',")
print(" base_url='https://api.example.com'")
print(" )")
print()
print("Let's test the Django schema extraction instead...")
# Test the schema extraction without actually deploying
from tadata_sdk.openapi.source import OpenAPISpec
try:
spec = OpenAPISpec.from_django()
print("✅ Django schema extraction successful!")
print(f" API Title: {spec.info.title}")
print(f" API Version: {spec.info.version}")
print(f" Available paths: {list(spec.paths.keys())}")
print()
print("This OpenAPI specification would be deployed to Tadata as an MCP server.")
except Exception as e:
print(f"❌ Schema extraction failed: {e}")
return
# Deploy using Django schema extraction
try:
result = deploy(
use_django=True, # Extract schema from configured Django application
api_key=api_key,
base_url="https://api.example.com", # Your Django API base URL
)
print("✅ Deployment successful!")
print(f" MCP Server ID: {result.id}")
print(f" Created at: {result.created_at}")
if result.updated:
print(" Status: New deployment created")
else:
print(" Status: No changes detected, deployment skipped")
except Exception as e:
print(f"❌ Deployment failed: {e}")
if __name__ == "__main__":
main()