Getting started in Python to write ORM frameworks

Source: Internet
Author: User
Tags instance method

This article mainly introduces the introduction to the ORM framework in Python, the sample code is based on the python2.x version, the need for friends can refer to the

With the DB module, it is convenient to manipulate the database to write SQL directly. However, we still lack ORM. If you have ORM, you can get the user object in a statement like this:

?

1 user = User.get (' 123 ')

Instead of writing SQL and then converting to a user object:

?

1 2 U = Db.select_one (' select * from users where id=? ', ' 123 ') user = user (**u)

So we started writing ORM modules: Transwarp.orm.

Design ORM Interface

Similar to the design of the DB module, the design ORM is also designed from the top caller's perspective.

Let's first consider how to define a user object and then associate the database table users with it.

?

1 2 3 4 5 6 From Transwarp.orm import Model, Stringfield, Integerfield class User (model): __table__ = ' users ' id = Integerfield (prim Ary_key=true) name = Stringfield ()

Note that the __table__, IDs, and name defined in the user class are properties of the class, not properties of the instance. Therefore, attributes defined at the class level are used to describe the mapping relationship between the user object and the table, and the instance properties must be initialized by the __init__ () method, so the two do not interfere with each other:

?

1 2 3 4 # Create instance: User = User (id=123, name= ' Michael ') # in database: User.insert ()

Implementing ORM Modules

With the definition, we can start to implement the ORM module.

The first thing to define is the base class model for all ORM mappings:

?

1 2 3 4 5 6 7 8 9 10 11 12 13-14 Class Model (dict): __metaclass__ = Modelmetaclass def __init__ (self, **kw): Super (Model, self). __init__ (**KW) def __ge Tattr__ (self, key): Try:return Self[key] except keyerror:raise attributeerror (r "' Dict ' object has no attribute '%s '"% K EY def __setattr__ (self, Key, value): self[key] = value

Model inherits from Dict, so it has all the dict features, and implements a special method __getattr__ () and __setattr__ (), so you can write as you would reference a normal field:

?

1 2 3 4 >>> user[' id '] 123 >>> user.id 123

Model is just a base class, how do you read the mapping information of a specific subclass such as user? The answer is through Metaclass:modelmetaclass:

?

1 2 3 4 5 6 7 8 9 10 Class Modelmetaclass (type): Def __new__ (CLS, name, bases, attrs): mapping = ... # Read the CLS's field fields Primary_key = ... # find prim Ary_key field __table__ = cls.__talbe__ # Read the CLS's __table__ field # Add some fields to the CLS: attrs[' __mapping__ '] = mapping attrs[' __primary_key __ '] = __primary_key__ attrs[' __table__ '] = __table__ return type.__new__ (CLS, name, bases, Attrs)

In this way, any class that inherits from model (such as user) automatically scans the relationship by Modelmetaclass and stores it in its own class.

Then we add the class method to the model class so that all subclasses can invoke the class method:

?

1 2 3 4 5 6 7 8 Class Model (dict): ... @classmethod def get (CLS, pk): D = Db.select_one (' select * from%s where%s=? '% (cls.__table__ , Cls.__primary_key__.name), PK) return CLS (**D) if D else None

The user class can implement a primary key lookup through a class method:

user = User.get (' 123 ')

Adding an instance method to the model class allows all subclasses to invoke the instance method:

?

1 2 3 4 5 6 7 8 9 10 Class Model (Dict):. def insert (self): params = {} for k, v. in Self.__mappings__.iteritems (): params[v.name] = GetAt TR (self, k) Db.insert (self.__table__, **params) return self

This allows a user instance to be stored in the database:

?

1 2 user = User (id=123, name= ' Michael ') User.insert ()

The final step is to refine ORM, and for lookups, we can implement the following methods:

?

1 2 3 4 5 Find_first () Find_all () find_by ()

For count, you can implement:

?

1 2 3 Count_all () count_by ()

and the update () and delete () methods.

Finally, how many lines of code do we have for the ORM module we implemented? Add comments and doctest just over 300 lines. Is it easy to write an orm in Python?

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.