Warning: Can't synchronize with repository "(default)" (Unsupported version control system "svn": No module named svn). Look in the Trac log for more information.

Changes between Version 2 and Version 3 of UsingSqlAlchemy


Ignore:
Timestamp:
02/14/06 00:52:48 (9 years ago)
Author:
Karl Guertin
Comment:

Added Custom Col types

Legend:

Unmodified
Added
Removed
Modified
  • UsingSqlAlchemy

    v2 v3  
    103103constructor. 
    104104 
     105 
     106Custom Column Types 
     107------------------- 
     108SQLObject uses formencode to perform python to database conversions. This 
     109shows how to use the SQLAlchemy column datatypes. Below are two examples, one 
     110which converts a number representing the system timestamp to a python datetime 
     111while the other converts IPv4 addresses between integer and octet notation. 
     112 
     113.. code-block:: python 
     114  import time 
     115  from datetime import datetime 
     116 
     117  class TIMESTAMP(Numeric): 
     118      def convert_bind_param(self,value,engine): 
     119          return super(TIMESTAMP,self).convert_bind_param(time.mktime(value.timetuple()),engine) 
     120      def convert_result_value(self,value,engine): 
     121          return datetime.fromtimestamp(super(TIMESTAMP,self).convert_result_value(value,engine)) 
     122         
     123.. code-block:: python 
     124  import struct 
     125  from socket import inet_aton, inet_ntoa, error as socket_error 
     126 
     127  class IPv4AddrTypeError(TypeError): 
     128      def __init__(self, addr): 
     129          self.addr = addr 
     130      def __str__(self): 
     131          return "Illegal IPv4 address '%s'" % self.addr 
     132 
     133  class IPV4(Numeric): 
     134      def convert_bind_param(self,value,engine): 
     135          try: 
     136              return super(IPV4,self).convert_bind_param(struct.unpack('!L',inet_aton(value))[0],engine) 
     137          except socket_error: 
     138              raise IPv4AddrTypeError(value) 
     139      def convert_result_value(self,value,engine): 
     140          return inet_ntoa(struct.pack('!L',super(IPV4,self).convert_result_value(value,engine)) 
     141 
    105142Future Developments 
    106143-------------------