leafsummer
7/24/2015 - 9:29 AM

used cache lock in django

used cache lock in django

def get_user_events(user_id, appname, new_flag=False):
    """
    get the last 7 days events from reportevent table by user_id
    param: user_id: the user id, appname: the app name
    """
    if new_flag:
        starttime = datetime.datetime.combine(datetime.date.today(), datetime.time.min)
    else:
        starttime = datetime.datetime.combine(datetime.date.today() - datetime.timedelta(days=6),
                                     datetime.time.min)
    return ReportEvent.objects.filter(insert_time__gt=starttime, user_id=user_id, app_name=appname)

def publish_report_event(user_id, appname, new_flag=False):
    """
    publish the reports event to record the situation that the reports with the license be sent
    return the newest object of the ReportEvent
    param: user_id:the user id, appname: the app name
    """
    LOCK_EXPIRE = 60 * 5
    remark = ''
    if not isinstance(appname, int):
        try:
            str_key = str(appname)
            appname = ReportEvent.APP_NAME_MAP[str_key]
        except KeyError, e:
            logger.error("the appname is wrong and not exist, appname:%s, e:%s" %(appname, e))
            raise
    lock_id = '%d-reportevent-lock-%s' % (user_id, appname)
    acquire_lock = lambda: cache.add(lock_id, 'true', LOCK_EXPIRE)
    release_lock = lambda: cache.delete(lock_id)
    try:
        while not acquire_lock():
            time.sleep(0.5)
        showing_events = ReportEvent.get_user_events(user_id, appname, new_flag=False)
        if not showing_events.exists():
            report_event = ReportEvent.objects.create(user_id=user_id, status=0, app_name=appname, insert_time=datetime.datetime.now(), remark=remark)
        elif showing_events.count() > 2:
            report_event = showing_events.order_by('-insert_time')[0]
        else:
            report_event = showing_events[0]
    except Exception, e:
        import traceback
        str_error = "%s: \n %s" % (e, traceback.format_exc())
        logger.error("creating the report event is failed: %s"%str_error)
        to_list = ['rs@nsfocus.com']
        sub = _("create report event error!")
        error_time = datetime.datetime.now()
        msg = _("the license %(lic)d in %(time)s, creating the report event is failed, error:\n %(error)s \n\n please notify the developers!")\
            %{'lic':user_id, 'time':error_time, 'error':str_error}
        send_mail(to_list, sub, msg)
        raise
    finally:
        release_lock()
    return report_event