Skip to content
Snippets Groups Projects
api.py 2.19 KiB
Newer Older
  • Learn to ignore specific revisions
  • from flask import jsonify, render_template
    import sqlite3
    
    def apiGet(request, url_scheme):
        try:
            userID = sAPI.dumps(s.loads(request.cookies.get('userID')))
        except:
            userID = ""
    
        return render_template("apiDocs.html", apikey=userID, domain=request.headers['Host'], url_scheme=url_scheme)
    
    def apiPost(request, domain):
        username = "error"
        try:
            username = sAPI.loads(request.form['apikey'])
        except:
            pass
    
        try:
            short = request.form['short']
        except:
            return jsonify(
                status="1",
                message="short link missing"
            )
        
        try:
            longURL = request.form['long']
        except:
            return jsonify(
                status="2",
                message="link to short is missing"
            )
    
        domain_ = short.split("/")[0]
        if not domain_ in domain:
            return jsonify(
                status="3",
                message="domain for short link is not in allowed domain list"
            )
        
        with sqlite3.connect('db/urls.db') as conn: #Check if another user already used the short link
            cursor = conn.cursor()
            res = cursor.execute('SELECT LONG_URL FROM WEB_URL WHERE SHORT_URL=?', [short])
            try:
                short2 = res.fetchone()
                already_used = False
                if short2 is not None:
                    already_used = True
            except:
                pass
    
            if not already_used: #If short link wasn't used before, insert the link in the Database.
                res = cursor.execute(
                    'INSERT INTO WEB_URL (LONG_URL, SHORT_URL, USERNAME) VALUES (?, ?, ?)',
                    [longURL, short, username]
                )
    
                try:
                    request.form['qr']
                    qr64 = "data:image/jpeg;base64," + makeQR(url_scheme + "://" + short)
                    
                    return jsonify(
                        status="0",
                        message="ok",
                        qr=qr64
                    )
                except:
                    return jsonify(
                        status="0",
                        message="ok"
                    )
            else:
                return jsonify(
                    status="4",
                    message="short url already in use"
                )