1
\$\begingroup\$

I am collecting each visitor information like ip, lat, longitude, referrer and language and save it into db, then in db I have column in table with counter that increment if user revisits the web site (counter increments when visiting from different domain).

My flask app renders the template index.html which contains javascript functions that collect lat, long and pass it to this Flask endpoint registerVisitor:

@app.route("/regVisitor", methods=["POST"])
def registerVisitor():
    data = request.get_json()
    if not data:
        return jsonify({"status": "No data to process."}), 201

    visitorInfo = collectVisitorInfo(data)

    if bool(visitorInfo.get("increment", False)):
        if str(visitorInfo["referrer"]).find("searchCity") != -1 or visitorInfo["referrer"].endswith("newmsg"):
            return jsonify({"status": "coming from newmsg or SearchCity found"}), 200
        try:
            updateOrInsertToTable(request.user_agent, visitorInfo)
            return jsonify({"status" : "success"}), 200
        except Exception, er:
            return jsonify({"status": "fail:{}".format(er.message)})
    return jsonify({"status": "fail"}), 200


def collectVisitorInfo(data):
    visitorInfo = {}
    url = data.get("referrer") # coming from javascript
    visitorInfo["clientIP"] = request.access_route[0]
    visitorInfo["increment"] = data.get("increment")
    visitorInfo["coord_errorcode"] = data.get("coord_errorcode")
    visitorInfo["referrer"] = unquote(url) if url else request.referrer
    visitorInfo["cl_lat"] = data.get("lat", request.cookies.get("cl_lat", 0.0))
    visitorInfo["cl_lng"] = data.get("long", request.cookies.get("cl_lng", 0.0))
    visitorInfo["language"] = data.get("language")
    visitorInfo["visitorId"] = request.cookies.get("unique_visitor")
    return visitorInfo

The javascript function that makes call to this end point from index.html is here:

function getLocation() {
    nIntervId = setInterval(getcitydateTime, 60000)
    sendData = {
        language : window.navigator.userLanguage || window.navigator.language,
        referrer :  document.referrer || "/",
        increment : 1
    };
    $.ajax({
        type: "POST",
        url: $SCRIPT_ROOT + '/regVisitor',
        contentType: "application/json",
        data: JSON.stringify(sendData),
        dataType: "json",
        success: function(response) {
            if (navigator.geolocation) {
                try {
                    navigator.geolocation.getCurrentPosition(showPosition, showError);
                }
                catch(err) {
                    console.log(err);
                }
            } else {
                console.log("Geolocation is not supported by this browser.");
            }
        },
        error: function(err) {
            console.log(err);
        }
    });
    return false;
}

… then passes the latitude and longitude to the same endpoint:

function showPosition(position) {


    $.post($SCRIPT_ROOT + '/regVisitor', {
        lat: position.coords.latitude,
        long: position.coords.longitude,
      }, function(data) {
        console.log("ok it was " + data.status);
      });
    setCookie("cl_lat", position.coords.latitude, 365)
    setCookie("cl_lng", position.coords.longitude, 365)
    return false;
}

The reason why I do not pass lat, long at the same time as user may reject sharing geocordinates in that case some error may occur and other info won't be get passes to flask app via endpoint, so I have separated both these to two different function as you see above.

Is this the correct approach? I am doubting because most of the time the in db lat, long is not punched.

I also do not want to use google analytics as I want to map ip with lat, long of visitor and I couldn't find if google analytics provide a way of providing ip with respect to geo coordinates of visitor.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.