def generate_and_store_short_url(url, author): """ generates a short url for url parameter and store it in db it tries 3 times to generate and store a short url and if all the three attempts fails returns False else returns True """ url_shortner_handler = urlShortener() count = 0 short_url = None while True: short_url = url_shortner_handler.generateShortUrl() result, reason = url_shortner_handler.saveUrl(short_url, url, author) if result: app.logger.debug('value of short url(%s) for url is (%s)', short_url, url) short_url = SITE_URL + '/' + short_url break else: if reason is 'DuplicateKeyError' and count < 3: app.logger.debug('Short URL(%s) generated is already used. Trying again', short_url) count += 1 continue else: app.logger.critical('Error in saving short url(%s) for url is (%s)', short_url, url) break return short_url
def getURL(shorturl): """ Given a short url, the code looks up the short url in database and if found redirects to the long url path. if not found sends a 404 page not found. """ url_shortener_handler = urlShortener() url = url_shortener_handler.findUrl(shorturl) app.logger.debug('value of url is %s', url) if url is not None: url_shortener_handler.increment_visited_count(shorturl) return redirect(url, code=302) else: return abort(404)
def index(): login_form = LoginForm() logout_form = LogoutForm() short_url_form = ShortURLForm() register_form = RegisterForm() table = None author = 'anonymous' short_url = None # Set the author details if current_user.is_authenticated: app.logger.debug("current user name is (%s)", current_user.get_id() ) author = current_user.get_id() # Generate short url if request.method == 'POST' and short_url_form.validate(): short_url = generate_and_store_short_url(short_url_form.url.data, author) if short_url is None: flash('Internal error try again') # Generate table of urls created if current_user.is_authenticated: url_shortner_handler = urlShortener() iterator = url_shortner_handler.find_url_of_user(author, 7) if iterator is not None: table = urlcollection.create_collection(iterator) # Display any errors flash_errors(short_url_form) return render_template('index.html', login_form=login_form, logout_form=logout_form, shorturl_form=short_url_form, register_form=register_form, shortURL=short_url, table=table)