Home > Mobile >  How can I count access on shortner url in flask app?
How can I count access on shortner url in flask app?

Time:07-22

I have created shortner urls in flask, after that I have to count how many times user will open this link. I dont know how it count. actualy my code doesnt work properly. is shows what : `AttributeError: 'NoneType' object has no attribute 'access_counter'

also my func :

@app.route('/<short_id>')
def redirect_url(short_id):
     link = ShortUrls.query.filter_by(short_id=short_id).first()
     link.access_counter =1  
     db.session.commit()

     if link:       
         return redirect(link.original_url)
    
     else:
         flash('Invalid URL')
         return redirect(url_for('index'))

CodePudding user response:

If your database query fails because no matching entry was found, the link object is None. Because of this, an error is thrown. You can work around this by moving the database update into the if statement.

@app.route('/<short_id>')
def redirect_url(short_id):
     link = ShortUrls.query.filter_by(short_id=short_id).first()
     if link:       
         link.access_counter =1  
         db.session.commit()
         return redirect(link.original_url)
     else:
         flash('Invalid URL')
         return redirect(url_for('index'))
  • Related