Re: [flask] Generating Tiny / Short URL's
- From:
- Ron DuPlain
- Date:
- 2011-09-19 @ 14:28
Hi,
On Mon, Sep 19, 2011 at 10:25 AM, Michael Fogleman <fogleman@gmail.com> wrote:
> I wrote a Python module for generating tiny/short URL's and wanted to
> let you guys know about it in case you find it useful. I don't think
> it's necessary to become a full-blown Flask extension (maybe a
> recipe?), just a nice helper module for web development.
I think it's worth a small extension, like Django redirects:
https://docs.djangoproject.com/en/dev/ref/contrib/redirects/
This is useful generally and not just for URL shortener services.
You could provide hooks for persisting the URL map.
Thanks,
Ron
>
> Here's where you can get it:
>
> http://code.activestate.com/recipes/576918-python-short-url-generator/
>
> Here's the gist of how it works:
>
>>>> import short_url
>>>> key = short_url.encode_url(42)
>>>> print key
> cftgg
>>>> value = short_url.decode_url(key)
>>>> print value
> 42
>
> So your URL would be something like:
>
> http://www.example.com/objects/cftgg
>
> Here's some example code for how I use it with Flask:
>
> Adding support to your database models:
>
> @property
> def short_url(self):
> return short_url.encode_url(self.id)
>
> Adding support to your views:
>
> @app.route('/objects/<key>')
> def view_object(key):
> obj = Object.query.get_or_404(short_url.decode_url(key))
>
> Generating links in your templates:
>
> <a href="{{ url_for('view_object', key=obj.short_url) }}">
>
> Hope you like it!
>
> Michael
>