sqlalchemy+postgreSQL(relationship)

來源:互聯網
上載者:User
 

1、串連資料庫

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"  //之前用localhost 報錯連結不上資料庫 注意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、定義資料表和類之間的映射關係

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、設定檔  

[db]db_host = 127.0.0.1db_type = postgresql+psycopg2db_name = luoyundb_user = luoyundb_password = luoyun

  4、初始化資料庫 python manage.py

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()

  

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.