1. Connect to the database
Import OS, sysproject_root = OS. path. dirname (OS. path. realpath (_ file _) sys. path. insert (0, OS. path. join (project_root, 'lib ') config_path = OS. path. join (project_root, 'config. CFG ') from sqlalchemy import create_enginefrom sqlalchemy. ext. declarative import declarative_baseimport configparsercf = configparser. configparser () Cf. read (config_path) print cf. get ("DB", "db_host") if cf. get ("DB", "db_host"): db_host = cf. get ("DB", "db_host") else: db_host = "127.0.0.1" // The error code returned when localhost is used. If cf. get ("DB", "db_type"): db_type = cf. get ("DB", "db_type") else: db_type = "PostgreSQL + psycopg2" If cf. get ("DB", "db_name"): db_name = cf. get ("DB", "db_name") else: db_name = "luoyun" If cf. get ("DB", "db_user"): db_user = cf. get ("DB", "db_user") else: db_user = "luoyun" If cf. get ("DB", "db_password"): db_password = cf. get ("DB", "db_password") else: db_password = "luoyun" str = "% s: // % s: % s @ % S/% s "% (db_type, db_user, db_password, db_host, db_name) # dbengine = create_engine ('postgresql + psycopg2: // luoyun: luoyun@127.0.0.1/luoyun ', echo = true, client_encoding = 'utf8') dbengine = create_engine (STR, Echo = true, client_encoding = 'utf8') from sqlalchemy import create_enginefrom sqlalchemy. ext. declarative import declarative_baseormbase = declarative_base () from sqlalchemy. orm import sessionmakersession = sessionmaker (BIND = dbengine) dbsession = SESSION () dB = dbsession
2. Define the ing between data tables and Classes
import lyormfrom sqlalchemy import Column, Integer, String, ForeignKeyfrom sqlalchemy.orm import relationship, backreffrom lyorm import ORMBaseclass User(ORMBase): __tablename__='users' id = Column(Integer,primary_key=True) name = Column(String) fullname = Column(String) password = Column(String) def __init__(self, name, fullname, password): self.name = name self.fullname = fullname self.password = password def __repr__(self): return "<User('%s','%s','%s')>" % (self.name,self.fullname,self.password)class Address(ORMBase): __tablename__= 'address' id = Column(Integer, primary_key=True) email_address = Column(String, nullable=False) user_id = Column(Integer, ForeignKey('users.id')) user = relationship("User", backref = backref('addresses',order_by=id)) def __init__(self,email_address): self.email_address = email_address def __repr__(self): return "<Address('%s')>" % self.email_address
3. Configuration File
[db]db_host = 127.0.0.1db_type = postgresql+psycopg2db_name = luoyundb_user = luoyundb_password = luoyun
4. initialize the python manage. py database.
import modelsfrom lyorm import ORMBase, dbengine,dbsessionORMBase.metadata.create_all(dbengine)from models import Userdef init(): jack = User('jack','Jack Bean', '801310') dbsession.add(jack) dbsession.commit()if __name__=='__main__': init()