__init__.py :  » Development » SnapLogic » snaplogic » components » computils » Python Open Source

Home
Python Open Source
1.3.1.2 Python
2.Ajax
3.Aspect Oriented
4.Blog
5.Build
6.Business Application
7.Chart Report
8.Content Management Systems
9.Cryptographic
10.Database
11.Development
12.Editor
13.Email
14.ERP
15.Game 2D 3D
16.GIS
17.GUI
18.IDE
19.Installer
20.IRC
21.Issue Tracker
22.Language Interface
23.Log
24.Math
25.Media Sound Audio
26.Mobile
27.Network
28.Parser
29.PDF
30.Project Management
31.RSS
32.Search
33.Security
34.Template Engines
35.Test
36.UML
37.USB Serial
38.Web Frameworks
39.Web Server
40.Web Services
41.Web Unit
42.Wiki
43.Windows
44.XML
Python Open Source » Development » SnapLogic 
SnapLogic » snaplogic » components » computils » __init__.py
# $SnapHashLicense:
# 
# SnapLogic - Open source data services
# 
# Copyright (C) 2009, SnapLogic, Inc.  All rights reserved.
# 
# See http://www.snaplogic.org for more information about
# the SnapLogic project. 
# 
# This program is free software, distributed under the terms of
# the GNU General Public License Version 2. See the LEGAL file
# at the top of the source tree.
# 
# "SnapLogic" is a trademark of SnapLogic, Inc.
# 
# 
# $

# $Id: __init__.py 8544 2009-08-11 16:32:57Z dmitri $

""" 
This package contains general utility functions for components.

"""

__docformat__ = "epytext en"

from datetime import date,datetime
from decimal import Decimal
from types import NoneType
from snaplogic.common.data_types import SnapString,SnapNumber,SnapDateTime
from datetime import datetime,timedelta
import time

from snaplogic.common.snap_exceptions import *

def convert_to_supported_type(value):
    """
    Converts python types to type expected by SnapLogic records.
    
    The following types are converted:
    
    1) str to unicode
    
    2) float, int and long to Decimal
    
    3) date to datetime
    
    @param value: Value to be converted
    @type value:  varies
    
    @return: The converted value.
    @rtype:  datetime/unicode/Decimal/bool
    
    """

    t = type(value)
    if t == str:
        value = value.decode('utf-8')
    elif t == date:
        value = datetime(value.year, value.month, value.day)
    elif t == float or t == int or t == long:
        value = Decimal(str(value))
    # Now we've done the needed conversions...
    # Is this type even allowed?
    elif not (t in [datetime, unicode, Decimal, bool, NoneType]): 
        raise SnapObjTypeError("Cannot handle type: %s" % str(t))
    
    return value

_DATE_FORMAT_1 = "%Y-%m-%dT%H:%M:%S" # Matches TypeConverter
_DATE_FORMAT_2 = "%Y-%m-%d %H:%M:%S" # Variant of TypeConverter
_DATE_FORMAT_3 = '%Y-%m-%d'          # Matches DateDimension 
_DATE_FORMATS = [_DATE_FORMAT_1, _DATE_FORMAT_2, _DATE_FORMAT_3]
_DATE_FORMAT_PRESENTATION = ["yyyy-mm-ddThh:mm:ss", "yyyy-mm-dd hh:mm:ss", "yyyy-mm-dd"]

SQLITE_DATE_FORMAT_STRING = _DATE_FORMAT_2

def convert_to_field_type(type, value):
    """ Convert value from string to number or date """
    # Strings or Nones don't require any conversion
    if type == SnapString or value is None:
        return value
    elif type == SnapNumber:
        try:
            if isinstance(value, float):
                return Decimal(str(value))
            else:
                return Decimal(value)
        except Exception:
            raise SnapComponentError("'%s' is not a number" % value)
    elif type == SnapDateTime:
        for datetime_fmt in _DATE_FORMATS:
            try:
                return datetime(*time.strptime(value, datetime_fmt)[0:6])
            except:
                # Try the next mask in the for loop 
                pass
        # We've tried all date masks, and neither one worked.
        raise SnapComponentError("Cannot convert '%s' to date.  Value did not match any supported format: %s" %
                                 (value, ", ".join(_DATE_FORMAT_PRESENTATION)))

def parse_date_with_fractions(s, fmt=SQLITE_DATE_FORMAT_STRING):
    """
    Parse a string containing microseconds into a datetime 
    object, because strptime does not understand fractions 
    of a second (milliseconds, microseconds, etc).
    
    @param s: String to parse into date
    @type s: string
    
    @param fmt: Format string
    @type fmt: str
    
    @return: datetime object
    @rtype: datetime
    
    """
    micros = None
    if '.' in s:
        dot_idx = s.index('.')
        micros = s[dot_idx+1:]
        micros_mult = 10 ** (6 - len(micros))
        micros = int(micros) * micros_mult
        s = s[:dot_idx]
    result = datetime(*(time.strptime(s, fmt)[0:6]))
    if micros:
        delta = timedelta(0, 0, micros)
        result += delta
    return result        
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.