~0x44/nova/bug838466

« back to all changes in this revision

Viewing changes to nova/utils.py

  • Committer: Brian Waldon
  • Date: 2011-07-29 19:26:14 UTC
  • mto: This revision was merged to the branch mainline in revision 1364.
  • Revision ID: brian.waldon@rackspace.com-20110729192614-68rrnpbg9i27dooi
adding more on return_type in docstrings

Show diffs side-by-side

added added

removed removed

Lines of Context:
19
19
 
20
20
"""Utilities and helper functions."""
21
21
 
 
22
import base64
22
23
import datetime
23
24
import functools
24
25
import inspect
29
30
import random
30
31
import re
31
32
import socket
 
33
import string
32
34
import struct
33
35
import sys
34
36
import time
48
50
 
49
51
 
50
52
LOG = logging.getLogger("nova.utils")
51
 
ISO_TIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
52
 
PERFECT_TIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%f"
 
53
TIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
53
54
FLAGS = flags.FLAGS
54
55
 
55
56
 
360
361
    utcnow.override_time = None
361
362
 
362
363
 
363
 
def strtime(at=None, fmt=PERFECT_TIME_FORMAT):
364
 
    """Returns formatted utcnow."""
 
364
def isotime(at=None):
 
365
    """Returns iso formatted utcnow."""
365
366
    if not at:
366
367
        at = utcnow()
367
 
    return at.strftime(fmt)
368
 
 
369
 
 
370
 
def parse_strtime(timestr, fmt=PERFECT_TIME_FORMAT):
371
 
    """Turn a formatted time back into a datetime."""
372
 
    return datetime.datetime.strptime(timestr, fmt)
373
 
 
374
 
 
375
 
def isotime(at=None):
376
 
    """Returns iso formatted utcnow."""
377
 
    return strtime(at, ISO_TIME_FORMAT)
 
368
    return at.strftime(TIME_FORMAT)
378
369
 
379
370
 
380
371
def parse_isotime(timestr):
381
372
    """Turn an iso formatted time back into a datetime."""
382
 
    return parse_strtime(timestr, ISO_TIME_FORMAT)
 
373
    return datetime.datetime.strptime(timestr, TIME_FORMAT)
383
374
 
384
375
 
385
376
def parse_mailmap(mailmap='.mailmap'):
513
504
    return value
514
505
 
515
506
 
516
 
def to_primitive(value, convert_instances=False, level=0):
517
 
    """Convert a complex object into primitives.
518
 
 
519
 
    Handy for JSON serialization. We can optionally handle instances,
520
 
    but since this is a recursive function, we could have cyclical
521
 
    data structures.
522
 
 
523
 
    To handle cyclical data structures we could track the actual objects
524
 
    visited in a set, but not all objects are hashable. Instead we just
525
 
    track the depth of the object inspections and don't go too deep.
526
 
 
527
 
    Therefore, convert_instances=True is lossy ... be aware.
528
 
 
529
 
    """
530
 
    if inspect.isclass(value):
531
 
        return unicode(value)
532
 
 
533
 
    if level > 3:
534
 
        return []
535
 
 
536
 
    # The try block may not be necessary after the class check above,
537
 
    # but just in case ...
538
 
    try:
539
 
        if type(value) is type([]) or type(value) is type((None,)):
540
 
            o = []
541
 
            for v in value:
542
 
                o.append(to_primitive(v, convert_instances=convert_instances,
543
 
                                      level=level))
544
 
            return o
545
 
        elif type(value) is type({}):
546
 
            o = {}
547
 
            for k, v in value.iteritems():
548
 
                o[k] = to_primitive(v, convert_instances=convert_instances,
549
 
                                    level=level)
550
 
            return o
551
 
        elif isinstance(value, datetime.datetime):
552
 
            return str(value)
553
 
        elif hasattr(value, 'iteritems'):
554
 
            return to_primitive(dict(value.iteritems()),
555
 
                                convert_instances=convert_instances,
556
 
                                level=level)
557
 
        elif hasattr(value, '__iter__'):
558
 
            return to_primitive(list(value), level)
559
 
        elif convert_instances and hasattr(value, '__dict__'):
560
 
            # Likely an instance of something. Watch for cycles.
561
 
            # Ignore class member vars.
562
 
            return to_primitive(value.__dict__,
563
 
                                convert_instances=convert_instances,
564
 
                                level=level + 1)
565
 
        else:
566
 
            return value
567
 
    except TypeError, e:
568
 
        # Class objects are tricky since they may define something like
569
 
        # __iter__ defined but it isn't callable as list().
570
 
        return unicode(value)
 
507
def to_primitive(value):
 
508
    if type(value) is type([]) or type(value) is type((None,)):
 
509
        o = []
 
510
        for v in value:
 
511
            o.append(to_primitive(v))
 
512
        return o
 
513
    elif type(value) is type({}):
 
514
        o = {}
 
515
        for k, v in value.iteritems():
 
516
            o[k] = to_primitive(v)
 
517
        return o
 
518
    elif isinstance(value, datetime.datetime):
 
519
        return str(value)
 
520
    elif hasattr(value, 'iteritems'):
 
521
        return to_primitive(dict(value.iteritems()))
 
522
    elif hasattr(value, '__iter__'):
 
523
        return to_primitive(list(value))
 
524
    else:
 
525
        return value
571
526
 
572
527
 
573
528
def dumps(value):