python类localtime()的实例源码

bake_api.py 文件源码 项目:mccelections 作者: mcclatchy 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def handle(self, *args, **options):
        electiondate_arg = options['electiondate']
        model_arg = options['model']

        start_time = timezone.localtime(timezone.now())

        start_message = '\nStarted baking:\t\t' + str(unicode(start_time)) + '\n'

        message = start_message
        slackbot(message)

        bake_api_to_static(electiondate_arg, model_arg)

        end_time = timezone.localtime(timezone.now())

        end_message = '\nFinished baking:\t' + str(unicode(end_time)) + '\n\n'
        bake_length = str(unicode(end_time - start_time)) 

        message = end_message
        slackbot(message)

        message = 'Bake length:\t\t' + bake_length
        slackbot(message)
        message = '--------------------------------------------------\n'
        slackbot(message)
generate_json.py 文件源码 项目:mccelections 作者: mcclatchy 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def handle(self, *args, **options):
        electiondate_arg = options['electiondate']
        model_arg = options['model']

        start_time = timezone.localtime(timezone.now())

        start_message = '\nStarted generating:\t\t' + str(unicode(start_time)) + '\n'

        message = start_message
        slackbot(message)

        generate_json(electiondate_arg, model_arg)

        end_time = timezone.localtime(timezone.now())

        end_message = '\nFinished generating:\t\t' + str(unicode(end_time)) + '\n\n'
        generate_length = str(unicode(end_time - start_time)) 

        message = end_message
        slackbot(message)

        message = 'Generate length:\t\t' + generate_length
        slackbot(message)
        message = '--------------------------------------------------\n'
        slackbot(message)
invoice.py 文件源码 项目:zing 作者: evernote 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def _check_single_paidtask(invoice, amount):
    local_now = timezone.localtime(invoice.now)
    current_month_start = local_now.replace(day=1, hour=0, minute=0, second=0)
    PaidTask.objects.get(
        task_type=PaidTaskTypes.CORRECTION,
        amount=(-1) * amount,
        datetime=invoice.month_end,
        description='Carryover to the next month',
        user=invoice.user,
    )
    PaidTask.objects.get(
        task_type=PaidTaskTypes.CORRECTION,
        amount=amount,
        datetime=current_month_start,
        description='Carryover from the previous month',
        user=invoice.user,
    )
    assert PaidTask.objects.filter(task_type=PaidTaskTypes.CORRECTION).count() == 2
invoice.py 文件源码 项目:zing 作者: evernote 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def _add_correction(self, total_amount):
        """Adds a correction for the value of `total_amount` in the month being
        processed.
        """
        server_tz = timezone.get_default_timezone()
        local_now = timezone.localtime(self.now, server_tz)
        initial_moment = local_now.replace(day=1, hour=0, minute=0, second=0)

        PaidTask.objects.get_or_create(
            task_type=PaidTaskTypes.CORRECTION,
            amount=(-1) * total_amount,
            rate=1,
            datetime=self.month_end,
            description='Carryover to the next month',
            user=self.user,
        )
        PaidTask.objects.get_or_create(
            task_type=PaidTaskTypes.CORRECTION,
            amount=total_amount,
            rate=1,
            datetime=initial_moment,
            description='Carryover from the previous month',
            user=self.user,
        )
views.py 文件源码 项目:Server 作者: malaonline 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def get_context_data(self, **kwargs):
        context = super(LCTimeslotQuestionsView, self
                        ).get_context_data(**kwargs)
        tsid = context.get('tsid')
        lc_timeslot = models.LiveCourseTimeSlot.objects.filter(pk=tsid).first()
        context['lc_timeslot'] = lc_timeslot
        if not lc_timeslot:
            context['error_msg'] = "??????"
            return context
        lecturer = self.get_lecturer()
        lc = lc_timeslot.live_course
        context['course_name'] = lc.name
        context['lecturer_name'] = lc.lecturer.name
        context['date'] = timezone.localtime(
            lc_timeslot.start).strftime('%Y-%m-%d')
        context['start'] = timezone.localtime(
            lc_timeslot.start).strftime('%H:%M')
        context['end'] = timezone.localtime(
            lc_timeslot.end).strftime('%H:%M')
        old_groups = lc_timeslot.question_groups.filter(deleted=False)
        context['old_groups'] = old_groups
        return context
tests.py 文件源码 项目:Server 作者: malaonline 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_orders_timeslots(self):
        def weekly_2_mins(weekly):
            return ((weekly.weekday - 1) * 24 * 60 + weekly.start.hour * 60 +
                    weekly.start.minute, (weekly.weekday - 1) * 24 * 60 +
                    weekly.end.hour * 60 + weekly.end.minute)

        orders = Order.objects.filter(status='p')
        for order in orders:
            timeslots = order.timeslot_set.filter(deleted=False)
            weekly_time_slots = order.weekly_time_slots.all()
            mins = [weekly_2_mins(x) for x in weekly_time_slots]
            for timeslot in timeslots:
                timeslot.start = timezone.localtime(timeslot.start)
                timeslot.end = timezone.localtime(timeslot.end)
                cur_min = (
                        timeslot.start.weekday() * 24 * 60 +
                        timeslot.start.hour * 60 + timeslot.start.minute,
                        timeslot.end.weekday() * 24 * 60 +
                        timeslot.end.hour * 60 + timeslot.end.minute)
                self.assertIn(cur_min, mins)
views.py 文件源码 项目:Server 作者: malaonline 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def __call__(self, time_slot: models.TimeSlot):
            if time_slot.is_complete() and hasattr(time_slot, "comment"):
                comment = time_slot.comment
                if comment:
                    self.count_comment(comment)
                    if self.is_valid(comment):
                        if self.cres.is_error and self.cres.id == time_slot.comment_id:
                            the_form = forms.CommentReplyForm(initial={"reply": self.cres.reply})
                        else:
                            the_form = forms.CommentReplyForm()
                        one_comment = {
                            "name": self.name,
                            "publish_date": localtime(comment.created_at).strftime("%Y-%m-%d %H:%M"),
                            "full_star": range(comment.score),
                            "empty_star": range(5 - comment.score),
                            "comment": comment.content,
                            "class_type": self.class_type + "1?1",
                            "form": the_form,
                            "action_url": "reply/comment/{id}".format(id=comment.id),
                            "form_id": "reply_form_{id}".format(id=comment.id),
                            "reply_id": "reply_{id}".format(id=comment.id),
                            "reply_content": comment.reply
                        }
                        self.comment_list.append(one_comment)
util.py 文件源码 项目:blog_django 作者: chnpmy 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field.rel, models.ManyToManyRel):
        return ', '.join([smart_text(obj) for obj in value.all()])
    else:
        return smart_text(value)
util.py 文件源码 项目:dream_blog 作者: fanlion 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field.rel, models.ManyToManyRel):
        return ', '.join([smart_text(obj) for obj in value.all()])
    else:
        return smart_text(value)
views.py 文件源码 项目:Ares 作者: tehpug 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def get_context_data(self, **kwargs):
        """
        Manipulating template context 
        """
        ctx = super(LeagueDetail, self).get_context_data(**kwargs)
        now = timezone.localtime()
        ctx['is_registered'] = False
        ctx['is_expired'] = False
        ctx['is_full'] = self.object.robots.count() == self.object.num_robots
        if self.request.user.is_authenticated():
            ctx['is_registered'] = self.object.robots.filter(
                user=self.request.user).count() > 0
        if now > self.object.registration_end or \
                now < self.object.registration_start:
            ctx['is_expired'] = True

        if ctx['is_expired']:
            ctx['table'] = League.get_table()

        return ctx
util.py 文件源码 项目:MxOnline 作者: myTeemo 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field.rel, models.ManyToManyRel):
        return ', '.join([smart_unicode(obj) for obj in value.all()])
    else:
        return smart_unicode(value)
util.py 文件源码 项目:djangoblog 作者: liuhuipy 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field.rel, models.ManyToManyRel):
        return ', '.join([smart_text(obj) for obj in value.all()])
    else:
        return smart_text(value)
planning.py 文件源码 项目:PonyConf 作者: PonyConf 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def _add_talk(self, talk):
        room = talk.room
        dt1 = talk.start_date
        d1 = localtime(dt1).date()
        dt2 = talk.start_date + timedelta(minutes=talk.estimated_duration)
        d2 = localtime(dt2).date()
        assert(d1 == d2) # this is a current limitation
        dt1 = self.days[d1]['timeslots'].index(dt1)
        dt2 = self.days[d1]['timeslots'].index(dt2)
        col = None
        for row, timeslot in enumerate(islice(self.days[d1]['timeslots'], dt1, dt2)):
            if col is None:
                col = 0
                while col < len(self.days[d1]['rows'][timeslot][room]) and self.days[d1]['rows'][timeslot][room][col]:
                    col += 1
                self.cols[room] = max(self.cols[room], col+1)
            event = Event(talk=talk, row=row, rowcount=dt2-dt1)
            while len(self.days[d1]['rows'][timeslot][room]) <= col:
                self.days[d1]['rows'][timeslot][room].append(None)
            self.days[d1]['rows'][timeslot][room][col] = event
util.py 文件源码 项目:sdining 作者: Lurance 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field.rel, models.ManyToManyRel):
        return ', '.join([smart_text(obj) for obj in value.all()])
    else:
        return smart_text(value)
views.py 文件源码 项目:isar 作者: ilbers 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def _modify_date_range_filter(filter_string):
    # was the date range radio button selected?
    if 0 >  filter_string.find('_daterange'):
        return filter_string,''
    # normalize GUI dates to database format
    filter_string = filter_string.replace('_daterange','').replace(':','!');
    filter_list = filter_string.split('!');
    if 4 != len(filter_list):
        return filter_string
    today = timezone.localtime(timezone.now())
    date_id = filter_list[1]
    date_from = _normalize_input_date(filter_list[2],today)
    date_to = _normalize_input_date(filter_list[3],today)
    # swap dates if manually set dates are out of order
    if  date_to < date_from:
        date_to,date_from = date_from,date_to
    # convert to strings, make 'date_to' inclusive by moving to begining of next day
    date_from_str = date_from.strftime("%Y-%m-%d")
    date_to_str = (date_to+timedelta(days=1)).strftime("%Y-%m-%d")
    filter_string=filter_list[0]+'!'+filter_list[1]+':'+date_from_str+'!'+date_to_str
    daterange_selected = re.sub('__.*','', date_id)
    return filter_string,daterange_selected
base.py 文件源码 项目:DjangoBlog 作者: 0daybug 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def _sqlite_datetime_trunc(lookup_type, dt, tzname):
    try:
        dt = backend_utils.typecast_timestamp(dt)
    except (ValueError, TypeError):
        return None
    if tzname is not None:
        dt = timezone.localtime(dt, pytz.timezone(tzname))
    if lookup_type == 'year':
        return "%i-01-01 00:00:00" % dt.year
    elif lookup_type == 'month':
        return "%i-%02i-01 00:00:00" % (dt.year, dt.month)
    elif lookup_type == 'day':
        return "%i-%02i-%02i 00:00:00" % (dt.year, dt.month, dt.day)
    elif lookup_type == 'hour':
        return "%i-%02i-%02i %02i:00:00" % (dt.year, dt.month, dt.day, dt.hour)
    elif lookup_type == 'minute':
        return "%i-%02i-%02i %02i:%02i:00" % (dt.year, dt.month, dt.day, dt.hour, dt.minute)
    elif lookup_type == 'second':
        return "%i-%02i-%02i %02i:%02i:%02i" % (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)
util.py 文件源码 项目:xadmin-markdown-editor 作者: bluenknight 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field.rel, models.ManyToManyRel):
        return ', '.join([smart_unicode(obj) for obj in value.all()])
    else:
        return smart_unicode(value)
views.py 文件源码 项目:ecs 作者: ecs-org 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
def send_expedited_reviewer_invitations(request, meeting_pk=None):
    meeting = get_object_or_404(Meeting, pk=meeting_pk)

    categories = MedicalCategory.objects.filter(
        submissions__in=meeting.submissions.expedited())
    users = User.objects.filter(profile__is_board_member=True,
        medical_categories__in=categories.values('pk'))
    start = meeting.deadline_expedited_review
    for user in users:
        subject = _('Expedited Review at {}').format(
            timezone.localtime(start).strftime('%d.%m.%Y'))
        send_system_message_template(user, subject,
            'meetings/messages/expedited_reviewer_invitation.txt',
            {'start': start})

    meeting.expedited_reviewer_invitation_sent_at = timezone.now()
    meeting.save(update_fields=('expedited_reviewer_invitation_sent_at',))

    return redirect('ecs.meetings.views.meeting_details', meeting_pk=meeting.pk)
feeds.py 文件源码 项目:django-danceschool 作者: django-danceschool 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def __init__(self,object,**kwargs):

        timeZone = pytz.timezone(getattr(settings,'TIME_ZONE','UTC'))
        if kwargs.get('timeZone',None):
            try:
                timeZone = pytz.timezone(kwargs.get('timeZone',None))
            except pytz.exceptions.UnknownTimeZoneError:
                pass

        self.id = 'event_' + str(object.event.id) + '_' + str(object.id)
        self.type = 'event'
        self.id_number = object.event.id
        self.title = object.event.name
        self.description = object.event.description
        self.start = timezone.localtime(object.startTime,timeZone) \
            if timezone.is_aware(object.startTime) else object.startTime
        self.end = timezone.localtime(object.endTime,timeZone) \
            if timezone.is_aware(object.endTime) else object.endTime
        self.color = object.event.displayColor
        self.url = object.event.get_absolute_url()
        if hasattr(object,'event.location'):
            self.location = object.event.location.name + '\n' + object.event.location.address + '\n' + object.event.location.city + ', ' + object.event.location.state + ' ' + object.event.location.zip
        else:
            self.location = None
base.py 文件源码 项目:trydjango18 作者: wei0104 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def _sqlite_datetime_trunc(lookup_type, dt, tzname):
    try:
        dt = backend_utils.typecast_timestamp(dt)
    except (ValueError, TypeError):
        return None
    if tzname is not None:
        dt = timezone.localtime(dt, pytz.timezone(tzname))
    if lookup_type == 'year':
        return "%i-01-01 00:00:00" % dt.year
    elif lookup_type == 'month':
        return "%i-%02i-01 00:00:00" % (dt.year, dt.month)
    elif lookup_type == 'day':
        return "%i-%02i-%02i 00:00:00" % (dt.year, dt.month, dt.day)
    elif lookup_type == 'hour':
        return "%i-%02i-%02i %02i:00:00" % (dt.year, dt.month, dt.day, dt.hour)
    elif lookup_type == 'minute':
        return "%i-%02i-%02i %02i:%02i:00" % (dt.year, dt.month, dt.day, dt.hour, dt.minute)
    elif lookup_type == 'second':
        return "%i-%02i-%02i %02i:%02i:%02i" % (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)
forms.py 文件源码 项目:hawkpost 作者: whitesmith 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def clean_expires_at(self):
        # Validate the expiration date
        expires_at = self.cleaned_data.get("expires_at", "")
        never_expires = self.cleaned_data.get("never_expires", "")
        current_tz = timezone.get_current_timezone()
        if never_expires:
            expires_at = None
            self.cleaned_data["expires_at"] = expires_at
        if expires_at:
            # Check if the expiration date is a past date
            if timezone.localtime(timezone.now(), current_tz) > expires_at:
                self.add_error('expires_at', _('The date must be on the future.'))
        if not expires_at and not never_expires:
            self.add_error('expires_at',
                           _('This field is required, unless box is set to '
                             'never expire.'))
        return expires_at
tz.py 文件源码 项目:lifesoundtrack 作者: MTG 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def localtime_tag(parser, token):
    """
    Forces or prevents conversion of datetime objects to local time,
    regardless of the value of ``settings.USE_TZ``.

    Sample usage::

        {% localtime off %}{{ value_in_utc }}{% endlocaltime %}
    """
    bits = token.split_contents()
    if len(bits) == 1:
        use_tz = True
    elif len(bits) > 2 or bits[1] not in ('on', 'off'):
        raise TemplateSyntaxError("%r argument should be 'on' or 'off'" %
                                  bits[0])
    else:
        use_tz = bits[1] == 'on'
    nodelist = parser.parse(('endlocaltime',))
    parser.delete_first_token()
    return LocalTimeNode(nodelist, use_tz)
wagtail_hooks.py 文件源码 项目:moore 作者: UTNkar 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def queryset(self, request, queryset):
        now = timezone.now()
        # When time zone support is enabled, convert "now" to the user's time
        # zone so Django's definition of "Today" matches what the user expects.
        if timezone.is_aware(now):
            now = timezone.localtime(now)

        this_year = now.replace(
            month=1, day=1, hour=0, minute=0, second=0, microsecond=0
        )
        next_year = date(year=this_year.year + 1, month=1, day=1)
        last_year = date(year=this_year.year - 1, month=1, day=1)

        if self.value() == 'this':
            return queryset.filter(
                term_from__gte=this_year,
                term_from__lt=next_year
            )
        elif self.value() == 'last':
            return queryset.filter(
                term_from__gte=last_year,
                term_from__lt=this_year
            )
        elif self.value() == 'before':
            return queryset.filter(term_from__lt=last_year)
util.py 文件源码 项目:eduDjango 作者: yuzhou6 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field.rel, models.ManyToManyRel):
        return ', '.join([smart_unicode(obj) for obj in value.all()])
    else:
        return smart_unicode(value)
util.py 文件源码 项目:Django-IMOOC-Shop 作者: LBruse 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field.rel, models.ManyToManyRel):
        return ', '.join([smart_unicode(obj) for obj in value.all()])
    else:
        return smart_unicode(value)
util.py 文件源码 项目:StudyOnline 作者: yipwinghong 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field.rel, models.ManyToManyRel):
        return ', '.join([smart_unicode(obj) for obj in value.all()])
    else:
        return smart_unicode(value)
util.py 文件源码 项目:xadmin_python3 作者: mahongquan 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field.rel, models.ManyToManyRel):
        return ', '.join([smart_unicode(obj) for obj in value.all()])
    else:
        return value#smart_unicode(value)
views.py 文件源码 项目:supervisoradmin 作者: jimmy201602 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def get(self,request,node_name, process_name):
        if request.session['usertype'] == 0 or request.session['usertype'] == 1:
            try:
                node_config = Config(CONFIG_FILE).getNodeConfig(node_name)
                node = Node(node_config)
                if node.connection.supervisor.stopProcess(process_name):
                    if node.connection.supervisor.startProcess(process_name):
                        add_log = open(ACTIVITY_LOG, "a")
                        add_log.write("%s - %s restarted %s node's %s process .\n"%( timezone.localtime().ctime(), request.session['username'], node_name, process_name ))
                        return JsonValue(process_name, node_name, "restart").success()
            except xmlrpclib.Fault as err:
                add_log = open(ACTIVITY_LOG, "a")
                add_log.write("%s - %s unsucces restart event %s node's %s process .\n"%( timezone.localtime().ctime(), request.session['username'], node_name, process_name ))
                return JsonValue(process_name, node_name, "restart").error(err.faultCode, err.faultString)
        else:
            add_log = open(ACTIVITY_LOG, "a")
            add_log.write("%s - %s is unauthorized user request for restart. Restart event fail for %s node's %s process .\n"%( timezone.localtime().ctime(), request.session['username'], node_name, process_name ))
            return jsonify(status = "error2",
                           message = "You are not authorized this action" )

# Process start
views.py 文件源码 项目:supervisoradmin 作者: jimmy201602 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def get(self,request,node_name, process_name):
        if request.session['usertype'] == 0 or request.session['usertype'] == 1:
            try:
                node_config = Config(CONFIG_FILE).getNodeConfig(node_name)
                node = Node(node_config)
                if node.connection.supervisor.startProcess(process_name):
                    add_log = open(ACTIVITY_LOG, "a")
                    add_log.write("%s - %s started %s node's %s process .\n"%( timezone.localtime().ctime(), request.session['username'], node_name, process_name ))
                    return JsonValue(process_name, node_name, "start").success()
            except xmlrpclib.Fault as err:
                add_log = open(ACTIVITY_LOG, "a")
                add_log.write("%s - %s unsucces start event %s node's %s process .\n"%( timezone.localtime().ctime(), request.session['username'], node_name, process_name ))
                return JsonValue(process_name, node_name, "start").error(err.faultCode, err.faultString)
        else:   
            add_log = open(ACTIVITY_LOG, "a")
            add_log.write("%s - %s is unauthorized user request for start. Start event fail for %s node's %s process .\n"%( timezone.localtime().ctime(), request.session['username'], node_name, process_name ))
            return JsonResponse({'status' : "error2",
                           'message' : "You are not authorized this action"} )


# Process stop
views.py 文件源码 项目:supervisoradmin 作者: jimmy201602 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def get(self,request,node_name, process_name):
        if request.session['usertype'] == 0 or request.session['usertype'] == 1:
            try:
                node_config = Config(CONFIG_FILE).getNodeConfig(node_name)
                node = Node(node_config)
                if node.connection.supervisor.stopProcess(process_name):
                    add_log = open(ACTIVITY_LOG, "a")
                    add_log.write("%s - %s stopped %s node's %s process .\n"%( timezone.localtime().ctime(), request.session['username'], node_name, process_name ))
                    return JsonValue(process_name, node_name, "stop").success()
            except xmlrpclib.Fault as err:
                add_log = open(ACTIVITY_LOG, "a")
                add_log.write("%s - %s unsucces stop event %s node's %s process .\n"%( timezone.localtime().ctime(), request.session['username'], node_name, process_name ))
                return JsonValue(process_name, node_name, "stop").error(err.faultCode, err.faultString)
        else:
            add_log = open(ACTIVITY_LOG, "a")
            add_log.write("%s - %s is unauthorized user request for stop. Stop event fail for %s node's %s process .\n"%( timezone.localtime().ctime(), request.session['username'], node_name, process_name ))
            return JsonResponse({'status' : "error2",
                           'message' : "You are not authorized this action"} )

# Node name list in the configuration file


问题


面经


文章

微信
公众号

扫码关注公众号