Last active
January 30, 2019 22:35
-
-
Save jasonrhaas/be559a46d24db938758dfa687945a09e to your computer and use it in GitHub Desktop.
get_tiny_url
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@app.route('/', methods=['GET', 'POST']) | |
def get_tiny_url(): | |
if request.method == 'POST' and request.is_json: | |
long_url = request.get_json().get('url') | |
if not long_url: | |
abort(400) | |
if not long_url.startswith('http'): | |
long_url = f'http://{long_url}' | |
h = blake2b(long_url.encode(), digest_size=20).hexdigest() | |
app.logger.debug(h) | |
# See if URL already exists | |
url = Url.query.filter_by(hash=h).first() | |
if not url: | |
url = Url(hash=h, long=long_url) | |
app.logger.debug(url) | |
db.session.add(url) | |
db.session.commit() | |
app.logger.debug(url) | |
tiny_url = f'https://example.com/{short_url.encode_url(url.id)}' | |
return jsonify(tiny_url=tiny_url) | |
else: | |
return redirect('https://example.com') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment