I touched "Orator" so I made a note

Orator Overview

The range written in this memo

Memo details

DB settings

Specify dirver and database. Currently, there are three DBs supported: PostgreSQL, MySQL, and SQLite. Set driver, user (DB user), password (DB password), database (DB location), etc. For example, in the case of SQLite, it can be defined as follows.

DATABASES = {                                                                   
   'development': {                                                            
        'driver': 'sqlite',  
        'database': '/tmp/authgate.sqlite'
    }
}

Creating a table

You can create an instance of DatabaseManager and access the DB with that instance. When creating an instance, pass the DB definition.

from orator import DatabaseManager

DATABASES = {                                                                   
   'development': {                                                            
        'driver': 'sqlite',  
        'database': '/tmp/authgate.sqlite'
    }
}
db = DatabaseManager(DATABASES)

You can operate on DB with Schema Builder. Create a Schema instance by passing an instance of DatabaseManager. After that, use the Schema instance to call the method according to the column of the table you want to define.

create-database.py


from orator import DatabaseManager
from orator import Schema

DATABASES = {                                                                   
   'development': {                                                            
        'driver': 'sqlite',  
        'database': '/tmp/authgate.sqlite'
    }
}

db = DatabaseManager(DATABASES)
schema = Schema(db)

with schema.create('samples') as table:
    table.increments('id')
    table.string('string_column').nullable()
    table.integer('integer_column')

When the above file created is executed, a DB based on the definition is created.

$ python create-database.py

For more information, see Orator's Schema Builder section. http://orator.readthedocs.org/en/latest/schema_builder.html)を参照。

Creating a class that will be a Model

Basic syntax

Create by inheriting the Model class of Orator. The following example is a class mapped to the ** samples ** table that has two columns, ** string_column ** and ** integer_column ** created earlier.

class Sample(Model):                                                              
    __table__ = 'samples'                                                                                            
    __fillable__ = ['string_column'] 
    __guarded__ = ['integer_column'] 

__fillable__ and __guarded__

Use properly depending on whether mass-assignment is allowed or not. Mass-assignment is not allowed for the parameters defined in __guarded__. If you do not want to allow mass-assignment for all attributes, you can write as follows.

class AllBlockSample(Model):                                                              
    __table__ = 'samples'
    __guarded__ = ['*']

Pinch and eat various other properties

In Orator, there are various properties represented by __ property name __. Sometimes it can be achieved just by setting the property, so it seems that you will be happy if you read it. Below is an example of it.

** · __hidden__ property **

Consider the following model as an example.

class User(Model):
    __table__ = 'user'
    __fillable__ = ['login_id', 'password', 'name']
    __guarded__ = ['access_token']
    __hidden__ = ['password', 'access_token']

Orator provides a dedicated method for enumerating class properties.

Those set to __hidden__ are not displayed when using the above method. In the example of User class, only login_id and name are displayed (id is ** PRIMARY KEY **). Of course, the Python standard __dict __ andvars ()do not have the effect of __hidden__.

** · __timestamp__ property **

By default, Orator automatically generates a column that records the table creation time (** created_at ) and update time ( updated_at **). If you don't want it to be auto-generated, add __timestamps__ = False.

class SampleModel(Model):
    __table__ = 'samples'
    __timestamps__ = False

Saving data to DB

You can save it with save () or create ().

sample_model = SampleModel()
sample_model.string_column = "test"
sample_model.integer_column = 100
sample_model.save()

sample_model = SampleModel.create(string_column='test')

You cannot pass the __guarded__ parameter as an argument to create. Even if it is passed, it will be ignored and the corresponding parameter will remain None.

Also, if __guarded__ = ['*'] is specified when creating the Model class, ʻorator.exceptions.orm.MassAssignmentError` will occur when calling the create method.

I can't understand the small difference between save () and create () due to lack of research.

At the end

I wrote a series of notes about the setting method and the definition method of the class. I intended to write about "Migration" and "Issuing Select / Delete / Update queries", but I was exhausted. On another occasion.

Recommended Posts

I touched "Orator" so I made a note
〇✕ I made a game
I stumbled upon using MoviePy, so make a note
I made a python text
I made a discord bot
I touched PyAutoIt for a moment
I made a CUI-based translation script (2)
I made a wikipedia gacha bot
I made a fortune with Python.
I made a CUI-based translation script
I made a daemon with Python
[Python] I tried to implement stable sorting, so make a note
Postgres environment construction with Docker I struggled a little, so note
I made a segment tree with python, so I will introduce it
I made a new AWS S3 bucket
I made a dash docset for Holoviews
I made a payroll program in Python!
I made a character counter with Python
Beginner: I made a launcher using dictionary
I made a conversation partner like Siri
I made a script to display emoji
I made a Hex map with Python
I made a life game with Numpy
I made a stamp generator with GAN
I made a browser automatic stamping tool.
After studying Python3, I made a Slackbot
I tried using pipenv, so a memo
I made a roguelike game with Python
I made a simple blackjack with Python
I made a configuration file with Python
I made a library for actuarial science
I made a WEB application with Django
I made a neuron simulator with Python
I made a note of Google colaboratory which can use Spleeter easily.
I made a GAN with Keras, so I made a video of the learning process.
I was addicted to trying Cython with PyCharm, so make a note
I made a stamp substitute bot with line
I made a python dictionary file for Neocomplete
I made a competitive programming glossary with Python
I made a weather forecast bot-like with Python.
I touched graph-rcnn which generates a scene graph
I made a useful tool for Digital Ocean
I touched HaikuFinder
I touched Flask
I made a Twitter fujoshi blocker with Python ①
I made a crazy thing called typed tuple
[Python] I made a Youtube Downloader with Tkinter.
I made a router config collection tool Config Collecor
I made a simple Bitcoin wallet with pycoin
I made a downloader for word distributed expression
I made a LINE Bot with Serverless Framework!
I made a tool to compile Hy natively
I couldn't escape from the futon, so I made a fully automatic futon peeling machine.
I made a tool to get new articles
Just a note
I made a random number graph with Numpy
I made a peeping prevention product for telework.
I made a simple RSS reader ~ C edition ~
I made a Caesar cryptographic program in Python.
I made a bin picking game with Python
I made a Mattermost bot with Python (+ Flask)