不准确的数据被打到heroku postgresql表

时间:2017-08-25 13:42:28

标签: python postgresql heroku flask-sqlalchemy

您好我正在通过自己创建一个应用程序来学习Flask / SqlAlchemy,但是我注意到有时不准确的数据会被打孔,请参阅DataClip here这些数据是通过访问此page

生成的 visitorId N4PT3R0ZQ的dataclip条目中的

是不正确的。我通过输入网址在Windows手机中打开了该页面,但是打过的数据是我正在查看dataclip页面的iPhone或者我过去曾访问过该页面。

以下是在此表visitor中更新的代码。

def updateOrInsertToTable(user_agent, visitorInfo):
    """ Updates the table if visitor id exists else insert for new visitor
        Arguments: 
            user_agent (request.user_agent): request.user_agent object
            visitorInfo (dict): key value pair of visitor information 
    """
    visitorId =  visitorInfo["visitorId"]
    visitorIp = visitorInfo["clientIP"]
    language = visitorInfo["language"]
    referrer = visitorInfo["referrer"]
    coord_errorcode = visitorInfo.get("coord_errorcode", None)
    cl_lat = visitorInfo.get("cl_lat", 0.0)
    cl_lng = visitorInfo.get("cl_lng", 0.0)
    tz = _utils.getTimezoneFromIP(visitorIp)
    dtWithZone = _datetime.now(pytz.timezone(tz))
    visitorModel = Visitor(
        user_agent.platform,
        user_agent.browser, 
        dtWithZone, visitorId, 
        cl_lat, cl_lng,
        language, referrer,
        user_agent.version, 
        visitorIp,
        tz
    )
    existing = visitorModel.query.get(visitorId)

    if existing:
        existing.version = user_agent.version
        existing.cl_lat = float(cl_lat)
        existing.cl_lng = float(cl_lng)
        existing.ip = visitorIp
        existing.language = language
        existing.referrer = referrer
        existing.count = existing.count + 1
        existing.coord_errorcode = coord_errorcode
        existing.visitdatetime = dtWithZone
        db.session.commit()
    else:
        columnValues = {
            "platform" : user_agent.platform,
            "browser" : user_agent.browser,
            "visitorId" : visitorId,
            "cl_lat" : cl_lat,
            "cl_lng" : cl_lng,
            "language" : user_agent.language,
            "referrer" : referrer,
            "version" : user_agent.version,
            "count" : 1,
            "coord_errorcode": coord_errorcode,
            "ip" : visitorIp,
            "visitdatetime" : dtWithZone,
            "timezone": tz
        }
        insertIntoTable(dtWithZone, 'visitor', columnValues)



def insertIntoTable(dtWithZone, tableName, columValues):
    """ Insert into table with provided date time and time zone information.
    """
    db_uri = app.config["SQLALCHEMY_DATABASE_URI"]
    engine = create_engine(db_uri, connect_args={"options": "-c timezone={}".format(dtWithZone.timetz().tzinfo.zone)})
    meta = MetaData(engine, reflect=True)
    table = meta.tables[tableName]
    ins = table.insert().values(**columValues)
    conn = engine.connect()
    conn.execute(ins)
    conn.close()

我的appraoch有什么问题吗?还是我完全做错了?

非常感谢任何帮助。

0 个答案:

没有答案