Link shortener with flask
In this section, we will implement a service to shorten links, similar to those you see on social networks or websites. Shortening links allows you to save characters and enables you to convert:
- π A long URL, such as
https://www.example.com/with/a/very/long/url/and/many/parameters
. - π©³ Into a short URL, like
http://server:5000/6231aa1
.
For this to work, a service is needed to remember the relationship between both URLs. When someone tries to access the short one, it redirects to the long one.
- The server stores the relationship π©³
β
π.
In this example, we will implement a web service with flask
that allows us to shorten URLs. We will have two endpoints:
/short
: Given a long URL, it returns a short one and stores the relation./
: Given a short URL, it uses the stored relation to redirect to the long one.
from flask import Flask, request, redirect
import hashlib
app = Flask(__name__)
url_map = {}
@app.route('/short', methods=['POST'])
def shorten_url():
long_url = request.form['url']
url_short = shorten_url(long_url)
url_map[url_short] = long_url
return f'Shortened: {long_url} -> {url_short}'
@app.route('/<url_short>')
def short_to_long(url_short):
long_url = url_map.get(url_short)
if long_url:
return redirect(long_url)
else:
return 'Not found!', 404
def shorten_url(full_url):
hashed = hashlib.sha256(full_url.encode()).hexdigest()
return hashed[:7]
if __name__ == '__main__':
app.run(debug=True)
To see the example in action, if you install curl
, you can do the following. This makes a request to your application indicating that you want to shorten the Google address, and it stores the short URL ac6bb66
.
curl -X POST -d "url=http://www.google.com" http://localhost:5000/short
# Shortened: http://www.google.com -> ac6bb66
Now, in your browser, if you type http://localhost:5000/ac6bb66
, you will see how it redirects you to Google.
βοΈ Exercises:
- Use the
sqlite3
package to persist theurl_map
information if the application is restarted. As it is now, if the application is restarted, the shortened URLs will be lost. Persist that information to disk and load it on startup.