इस लेख में, हम देखेंगे कि Django में URL शॉर्टनर ऐप कैसे बनाया जाए। यह एक साधारण ऐप है जो एक लंबे URL को छोटे में बदल देगा। हम इसे एक पायथन लाइब्रेरी का उपयोग करके प्राप्त करेंगे, किसी Django-विशिष्ट लाइब्रेरी का नहीं, इसलिए आप इस कोड का उपयोग किसी भी पायथन प्रोजेक्ट में कर सकते हैं।
सबसे पहले, एक Django प्रोजेक्ट और एक ऐप बनाएं। settings.py में ऐप के urls शामिल करने और INSTALLED_APPS में ऐप शामिल करने जैसी कुछ बुनियादी सेटिंग्स करें।
उदाहरण
pyshorteners मॉड्यूल इंस्टॉल करें:
pip install pyshorteners
ऐप के urls.py में:
from django.urls import path
from .views import url_shortner
urlpatterns = [
path('', url_shortner.as_view(), name="url-shortner"),
]
यहां हमने व्यूसेट को होम url पर व्यू के रूप में सेट किया।
अब views.py में:
from django.shortcuts import render
import pyshorteners
from django.views import View
class url_shortner(View):
def post(self, request):
long_url = 'url' in request.POST and request.POST['url']
pys = pyshorteners.Shortener()
short_url = pys.tinyurl.short(long_url)
return render(request, 'urlShortner.html', context={'short_url': short_url, 'long_url': long_url})
def get(self, request):
return render(request, 'urlShortner.html')
यहां हमने दो रिक्वेस्ट हैंडलर फंक्शन्स के साथ एक व्यू बनाया, get हैंडलर फ्रंटएंड HTML रेंडर करेगा और post हैंडलर लंबा URL प्राप्त करेगा और हमारे फ्रंटएंड को शॉर्ट URL के साथ पुनः रेंडर करेगा।
ऐप की डायरेक्टरी में एक templates फोल्डर बनाएं और इसमें urlShortner.html जोड़ें और यह लिखें:
<!DOCTYPE html>
<html>
<head>
<title>Url Shortner</title>
</head>
<body>
<div>
<h1>URL Shortner Application</h1>
<form method="POST">{% csrf_token %}
<input type="url" name="url" placeholder="Enter the link here" required>
<button>Shorten URL</button>
</form>
</div>
{% if short_url %}
<div>
<h3>Your shortened URL</h3>
<div>
<input type="url" id="short_url" value={{short_url}}>
<button name="short-url">Copy URL</button>
<small id="copied" class="px-5"></small>
</div>
<br>
<span><b>Long URL: </b></span> <a href="{{long_url}}">{{long_url}}</a>
</div>
{% endif %}
</body>
</html>
यह फ्रंटएंड है जो लंबा URL लेगा और रिक्वेस्ट भेजेगा, फिर यह शॉर्ट URL लौटाता है।
आउटपुट
