SQLAlchemy Columns result processing

2024/9/8 10:51:53

I'm working with a IBM DB2 database using ibm_db2 driver and sqlalchemy. My model is:

class User(Model):id          = Column('UID', Integer, primary_key=True)user        = Column('USER', String(20))password    = Column('PASSWORD', String(10))name        = Column('NAME', String(30))

String fields from the database (e.g. name) comes in the form of:

>>> "John                                "

, where the value is filled right with blanks to the full length of the field by schema.

I need to change this behavior to the sqlalchemy type String (or a derivative thereof) produced follow (e.g. value.strip()) before output results by query.all():

>>> "John"

How can I do this?

@property decorator is not applicable. I need to change the behavior of a standard sqlalchemy String class.

Answer

I would not want to change the behaviour of the standard String but to make a new type (you can then rename it to String per module basis or whatever) but it is cleanest that way:

from sqlalchemy import typesclass StrippedString(types.TypeDecorator):"""Returns CHAR values with spaces stripped"""impl = types.Stringdef process_bind_param(self, value, dialect):"No-op"return valuedef process_result_value(self, value, dialect):"""Strip the trailing spaces on resulting values.If value is false, we return it as-is; it might be nonefor nullable columns"""return value.rstrip() if value else valuedef copy(self):"Make a copy of this type"return StrippedString(self.impl.length)

Now you can use StrippedString instead of String

https://en.xdnf.cn/q/72774.html

Related Q&A

How can I access relative paths in Python 2.7 when imported by different modules

The Goal: Access / Write to the same temp files when using a common utility function called from various python modules.Background: I am using the python Unittest module to run sets of custom tests tha…

Emacs: Inferior-mode python-shell appears lagged

Im a Python(3.1.2)/emacs(23.2) newbie teaching myself tkinter using the pythonware tutorial found here. Relevant code is pasted below the question.Question: when I click the Hello button (which should …

AttributeError: module spacy has no attribute load

import spacy nlp = spacy.load(en_core_web_sm)**Error:** Traceback (most recent call last):File "C:\Users\PavanKumar\.spyder-py3\ExcelML.py", line 27, in <module>nlp = spacy.load(en_core…

No module named Win32com.client error when using the pyttsx package

Today, while surfing on Quora, I came across answers on amazing things that python can do. I tried to use the pyttsx Text to Speech Convertor and that gave me an No module named Win32com.client error.T…

Python: How to create and use a custom logger in python use logging module?

I am trying to create a custom logger as in the code below. However, no matter what level I pass to the function, logger only prints warning messages. For example even if I set the argument level = log…

Flask-Mail - Sending email asynchronously, based on Flask-Cookiecutter

My flask project is based on Flask-Cookiecutter and I need to send emails asynchronously.Function for sending email was configured by Miguel’s Tutorial and sending synchronously works fine, but i don’…

Change text_factory in Django/sqlite

I have a django project that uses a sqlite database that can be written to by an external tool. The text is supposed to be UTF-8, but in some cases there will be errors in the encoding. The text is fro…

Shuffle patches in image batch

I am trying to create a transform that shuffles the patches of each image in a batch. I aim to use it in the same manner as the rest of the transformations in torchvision: trans = transforms.Compose([t…

Python looping: idiomatically comparing successive items in a list

I need to loop over a list of objects, comparing them like this: 0 vs. 1, 1 vs. 2, 2 vs. 3, etc. (Im using pysvn to extract a list of diffs.) I wound up just looping over an index, but I keep wondering…

Geodesic buffering in python

Given land polygons as a Shapely MultiPolygon, I want to find the (Multi-)Polygon that represents the e.g. 12 nautical mile buffer around the coastlines.Using the Shapely buffer method does not work si…