django中SQL alchemy的使用

settings配置:

DATABASES = {     'default': {         'ENGINE': 'django.db.backends.mysql',         'NAME':  'sqlalchemy_test',         'USER': 'root',         'PASSWORD': '******',         'HOST': '127.0.0.1',         'PORT': '3306'     } }

创建数据库:

# coding: utf-8  from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.orm import sessionmaker, scoped_session  engine = create_engine('mysql+mysqldb://root:password@localhost:3306/sqlalchemy_test?charset=utf8mb4') # 在同一个线程中,有 scoped_session 的时候,返回的是同一个 Session 对象。 # 在多线程下,即使通过  scoped_session 创建Session,每个线程下的 Session 都是不一样的,每个线程都有一个属于自己的 Session 对象,这个对象只在本线程下共享。 db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base = declarative_base() Base.query = db_session.query_property()   class User(Base):     __tablename__ = 'user'      id = Column(Integer, primary_key=True, autoincrement=True)     name = Column(String(20))   def init_db():     Base.metadata.create_all(engine)

MySQL 使用 mysql-python 作为默认 DBAPI。有许多 MySQL DBAPI 可用,mysqlclient 是一个原生驱动,推荐选择它。

# default engine = create_engine('mysql://scott:tiger@localhost/foo')  # mysqlclient (a maintained fork of MySQL-Python) engine = create_engine('mysql+mysqldb://scott:tiger@localhost/foo')  # PyMySQL engine = create_engine('mysql+pymysql://scott:tiger@localhost/foo')