इस लेख में, हम देखेंगे कि Django में URL शॉर्टनर ऐप कैसे बनाया जाता है। यह एक साधारण ऐप है जो एक लंबे यूआरएल को एक छोटे यूआरएल में बदल देगा। हम इसे पायथन लाइब्रेरी का उपयोग करके हासिल करेंगे, न कि किसी Django-विशिष्ट लाइब्रेरी का, ताकि आप किसी भी पायथन प्रोजेक्ट में इस कोड का उपयोग कर सकें।
सबसे पहले, एक Django प्रोजेक्ट और एक ऐप बनाएं। कुछ बुनियादी सेटिंग करें जैसे कि settings.py. में INSTALLED_APPS में ऐप के यूआरएल और ऐप को शामिल करना।
उदाहरण
पायशॉर्टनर स्थापित करें मॉड्यूल -
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') यहां हमने दो अनुरोध हैंडलर फ़ंक्शन के साथ एक दृश्य बनाया है, हैंडलर प्राप्त करें फ़्रंटएंड html और पोस्ट हैंडलर render को रेंडर करेगा लंबा URL प्राप्त करेगा और लघु URL के साथ हमारे फ़्रंटएंड को फिर से प्रस्तुत करेगा।
एक टेम्पलेट बनाएं ऐप की निर्देशिका में फ़ोल्डर और 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>
</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> यह फ्रंटएंड है जो लंबा यूआरएल लेगा और अनुरोध भेजेगा, फिर यह छोटा यूआरएल लौटाएगा।
आउटपुट
