이 기사에서는 Django에서 URL 단축 앱을 만드는 방법을 살펴보겠습니다. 긴 URL을 짧은 URL로 변환해주는 간단한 앱입니다. Django 전용 라이브러리가 아닌 Python 라이브러리를 사용하여 이를 달성하므로 모든 Python 프로젝트에서 이 코드를 사용할 수 있습니다.
먼저 Django 프로젝트와 앱을 생성합니다. settings.py의 INSTALLED_APPS에 앱 URL 포함 및 앱 포함과 같은 몇 가지 기본 설정을 수행합니다.
예시
pyshorteners 설치 모듈 -
pip install pyshorteners
앱의 url.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 handler라는 두 가지 요청 처리기 함수가 있는 보기를 만들었습니다. 프런트엔드 html 및 포스트 핸들러를 렌더링합니다. 긴 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> 이것은 긴 URL을 사용하여 요청을 보낸 다음 짧은 URL을 반환하는 프런트엔드입니다.
출력
