[PYTHON] A story that makes it easier to see Model debugging in the Django + SQLAlchemy environment

Background

Python and Django I'm in the first month. Rails history is about 2 years. Why is Python's Debug so hard to see? Especially Model. The following display. Who would benefit from seeing this?

>>> class Foo(object):
        pass
>>>
>>> repr(Foo())
'<__main__.Foo object at 0x02A74E50>'

If you look for the sea on the net and use repr, you can see it beautifully! Hooray! This frees you from the pain!

def __repr__(self):
    return '<Stats: description={0.description!r}, mystat={0.mystat!r}>'.format(self)

... what's this annoying.

You need to write to each class. Is it possible to add a one-shot library or something? ?? I think.

there were.

Reference: http://stackoverflow.com/a/15929677/5114776

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

if __debug__:
    # monkey-patch in useful repr() for all objects, but only in dev
    def tablerepr(self):
        return "<{}({})>".format(
            self.__class__.__name__,
            ', '.join(
                ["{}={}".format(k, repr(self.__dict__[k]))
                    for k in sorted(self.__dict__.keys())
                    if k[0] != '_']
            )
        )
    Base.__repr__ = tablerepr
>>> session.query(FooBar).get(1)
<FooBar(id=1, foo='bar', comments='foobar', hoge=1231242342341342342, fuga=datetime(2015, 5, 5, 5, 5, 5), tiger='waearsdtdygfyfguiohjohjohpp'>

However, it is still difficult to see with this reference alone. I'm not a machine! A format that is easy for people to see! Otherwise it's meaningless!

Easier to see

Base = declarative_base()

if __debug__:
    # monkey-patch in useful repr() for all objects, but only in dev
    def tab_char(max_length, target_lenght):
        tab = []
        tab_char_count = 4
        tab_count = (max_length/tab_char_count - target_lenght/tab_char_count) + 1
        for i in range(tab_count):
            tab.append('\t')
        return "".join(tab)


    def table_repr(self):
        max_length = max(map(lambda n: len(n), self.__dict__.keys()))
        return "\n<{}({})>".format(
            self.__class__.__name__,
            ', '.join(
                ["\n\t{}{}= {}".format(k, tab_char(max_length, len(k)), repr(self.__dict__[k]))
                 for k in sorted(self.__dict__.keys())
                 if k[0] != '_']
            )
        )

    Base.__repr__ = table_repr
>>> session.query(FooBar).get(1)
<FooBar(
	id					= 1
	fooooooooo			= 'bar',
	comments			= 'foobar',
	hoge				= 1231242342341342342, 
	fuga				= datetime(2015, 5, 5, 5, 5, 5), 
	tiger				= 'waearsdtdygfyfguiohjohjohpp'>

Perfect.

Recommended Posts

A story that makes it easier to see Model debugging in the Django + SQLAlchemy environment
A module that makes it easier to write Perl-like filter programs in Python fileinput
A story that makes it easy to estimate the living area using Elasticsearch and Python
A story that Qiita really wanted to see under a proxy environment
I tried to make a site that makes it easy to see the update information of Azure
Deep learning dramatically makes it easier to see the time-lapse of physical changes
I want to create an API that returns a model with a recursive relationship in the Django REST Framework
A story about PHP that was okay in the development environment but buggy in the production environment LEVEL 1-3 + 1
You who color the log to make it easier to see
One liner that formats JSON to make it easier to see
The story of a Django model field disappearing from a class
A script that makes it easy to create rich menus with the LINE Messaging API
A story that stumbled when using pip in a proxy environment
How to create a record by pasting a relation to the inheriting source Model in the Model inherited by Django
Create a web page that runs a model that increases the resolution of the image using gradio, which makes it easy to create a web screen
I wrote a class that makes it easier to divide by specifying part of speech when using Mecab in python
A story that didn't work when I tried to log in with the Python requests module
How to return the data contained in django model in json format and map it on leaflet
A story that struggled to handle the Python package of PocketSphinx
A note that you want to manually decorate the parameters passed in the Django template form item by item
[Python] How to save the installed package and install it in a new environment at once Mac environment
A story about creating a program that will increase the number of Instagram followers from 0 to 700 in a week
Added a function to register desired shifts in the Django shift table
Install Django in a pipenv virtual environment
Story of making a virtual planetarium [Until a beginner makes a model with a script and manages to put it together]
Django ~ Let's display it in the browser ~
The story of creating Botonyan that returns the contents of Google Docs in response to a specific keyword on Slack
In IPython, when I tried to see the value, it was a generator, so I came up with it when I was frustrated.
I thought it would be slow to use a for statement in NumPy, but that wasn't the case.
Implement a Custom User Model in Django
A solution to the problem that the Python version in Conda cannot be changed
The story of IPv6 address that I want to keep at a minimum
If you want to display values using choices in a template in a Django model
How to count the number of elements in Django and output to a template
The story of making a web application that records extensive reading with Django
Create a Django project and application in a Python virtual environment and start the server
The story of Django creating a library that might be a little more useful
The first thing to check when a No Reverse Match occurs in Django
[Django] Create a form that automatically fills in the address from the zip code
I want to see a list of WebDAV files in the Requests module
Define a division value in Django and easily reflect it on the screen
Instructions for connecting Google Colab. To the local runtime in a Windows environment
I referred to it when I got stuck in the django geodjango tutorial (editing)
Explaining how to make LINE BOT in the world's easiest way (2) [Preparing a bot application in a local environment with Django in Python]
A model that identifies the guitar with fast.ai
Use the latest pip in a virtualenv environment
Start Django in a virtual environment with Pipenv
Build a Django environment with Vagrant in 5 minutes
Set a fixed IP in the Linux environment
The story of viewing media files in Django
How to create a Rest Api in Django
The story that fits in with pip installation
It is a piggybacking story about the service that returns "Nyan" when you ping
The background of the characters in the text image is overexposed to make it easier to read.
A Python script that crawls RSS in Azure Status and posts it to Hipchat
A story that required preparation when trying to do a Django tutorial with plain centos7
Note that I was addicted to npm script not passing in the verification environment
A story that got stuck when trying to upgrade the Python version on GCE
Try to make a blackjack strategy by reinforcement learning (② Register the environment in gym)
The story of Linux that I want to teach myself half a year ago
[Django] Let's try to clarify the part of Django that was somehow through in the test