0

I am using Django 1.9 to build a link shortener. I have created a simple HTML page where the user can enter the long URL. I have also coded the methods for shortening this URL. The data is getting stored in the database and I am able to display the shortened URL to the user.

I want to know what I have to do next. What happens when a user visits the shorter URL? Should I use redirects or something else? I am totally clueless about this topic.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Stupid Man
  • 885
  • 2
  • 14
  • 31
  • Are you using any third party packages to shorten the url or writing your own logic to shorten the url? – MicroPyramid Jun 20 '16 at 12:32
  • @MicroPyramid I have written my own method. – Stupid Man Jun 20 '16 at 12:32
  • Yes, use redirects - look up the actual URL in your database then return a permanent (so the browser heads straight there in the future) redirect to that site. – jonrsharpe Jun 20 '16 at 12:33
  • Redirection to the original URL is the desired functionality here. Some services do redirect automatically, some do after a delay, while some other require manual clicking I think. – Barun Jun 20 '16 at 12:33
  • Please post the url pattern in which you are creating the shorten url? – MicroPyramid Jun 20 '16 at 12:36
  • @MicroPyramid I am first storing the long url in a database and then converting the auto increment field integer into base 62 string. Is it OK or can you suggest some better ways to do it. Its described here http://stackoverflow.com/questions/742013/how-to-code-a-url-shortener – Stupid Man Jun 20 '16 at 12:40
  • 2
    Write a middleware such that, if the shortened url is in the model that you stored the you can redirect the shortened url to the long url using HttpResponseRedirect. – MicroPyramid Jun 20 '16 at 12:44

3 Answers3

1

Normally when you provide a url shortner, after calling the url, you have to redirect to main url by 301 Permanently moved.

def resolve_url(request,url):
    origin_url=resolve(url) # read from redis or so.
    return HttpResponseRedirect(origin_url)

EDIT: add code using @danny-cullen hint

Ali Nikneshan
  • 3,500
  • 27
  • 39
1

You could just navigate to the URL via HttpResponseRedirect

Danny Cullen
  • 1,782
  • 5
  • 30
  • 47
1

Write a middleware instead of writing same code in every view, such that, if the shortened url is in the model that you stored the you can redirect the shortened url to the long url using HttpResponseRedirect.

class RedirectMiddleware(object):
    # Check if client IP is allowed
    def process_request(self, request):
       '''you can get the current url from request and just filter with the model and redirect to longurl with HttpResponseRedirect.'''
        return HttpResponseRedirect(full_url)
MicroPyramid
  • 1,570
  • 19
  • 22