• Python之路_Day12


    Python之路_Day12_课堂笔记

    上节回顾

    一、线程
    线程
    基本线程使用

    队列-消息队列

    线程池
    进程
    基本使用
    进程数据共享
    进程池
    协程
    更适用IO操作


    二、Memcache、Redis
    Memcache
    集群:
    (C1,1)
    (C2,2)
    (C3,1)
    [C1,C2,C2,C3]
    gets/cas

    Redis
    一、
    默认支持连接池
    支持事务
    发布和订阅
    二、Redis基本操作
    三、自定义
    Redis列表类型
    默认全部取
    根据索引取值




    本节预告

    一、线程池

    二、redis,发布订阅

    三、rabbitMQ

    四、MySQL

    五、python pymysql

    六、Python ORM >SQLAchemy

    七、Paramiko

    八、堡垒机、跳板机



    MySQL:http://www.cnblogs.com/wupeiqi/articles/5699254.html

    Redis:http://www.cnblogs.com/wupeiqi/articles/5132791.html

    线程池:http://www.cnblogs.com/wupeiqi/articles/4839959.html



    一、线程池

    1、上下文管理

    线程自动关闭示例:

    1. #!/usr/bin/env python
    2. # -.- coding: utf-8 -.-
    3. # By sandler
    4. import contextlib
    5. @contextlib.contextmanager
    6. def work_state(state_list, worker_thread):
    7.    state_list.append(work_state)
    8.    try:
    9.        yield
    10.    finally:
    11.        state_list.remove(work_state)
    12. free_list = []
    13. current_thread = 'sandler'
    14. with work_state(free_list, current_thread):
    15.    print(123)
    16.    print(456)

    socket自动关闭示例:

    1. #!/usr/bin/env python
    2. # -.- coding: utf-8 -.-
    3. # By sandler
    4. import contextlib
    5. import socket
    6. @contextlib.contextmanager
    7. def context_socket(host, port):
    8.    sk = socket.socket()
    9.    sk.bind((host, port))
    10.    sk.listen(5)
    11.    try:
    12.        yield sk
    13.    finally:
    14.        sk.close()
    15. with context_socket('127.0.0.1', 8888) as sock:
    16.    print(sock)

    2、终止线程池操作





    二、redis,发布订阅

    1、连接池

    2、自定义列表操作

    3、事务的操作-原子性操作

    4、发布订阅

    redis服务端
    1. #!/usr/bin/env python
    2. # -.- coding: utf-8 -.-
    3. # By sandler
    4. import redis
    5. class RedisHelper:
    6.    def __init__(self):
    7.        self.__conn = redis.Redis(host='192.168.11.87')
    8.    def public(self, msg, chan):
    9.        self.__conn.publish(chan, msg)
    10.        return True
    11.    def subscribe(self, chan):
    12.        pub = self.__conn.pubsub()
    13.        pub.subscribe(chan)
    14.        pub.parse_response()
    15.        return pub

    redis发布端

    1. #!/usr/bin/env python
    2. # -.- coding: utf-8 -.-
    3. # By sandler
    4. import s3
    5. obj = s3.RedisHelper()
    6. obj.public('alex db', 'fm111.7')

    redis订阅端

    1. #!/usr/bin/env python
    2. # -.- coding: utf-8 -.-
    3. # By sandler
    4. import s3
    5. obj = s3.RedisHelper()
    6. data = obj.subscribe('fm111.7')
    7. print(data.parse_response())





    三、rabbitMQ

    RabbitMQ是一个在AMQP基础上完整的,可复用的企业消息系统。他遵循Mozilla Public License开源协议。

    MQ全称为Message Queue, 消息队列(MQ)是一种应用程序对应用程序的通信方法。应用程序通过读写出入队列的消息(针对应用程序的数据)来通信,而无需专用连接来链接它们。消 息传递指的是程序之间通过在消息中发送数据进行通信,而不是通过直接调用彼此来通信,直接调用通常是用于诸如远程过程调用的技术。排队指的是应用程序通过 队列来通信。队列的使用除去了接收和发送应用程序同时执行的要求。


    Python需要安装的模块pika


    生产者消费者示例:

    生产者:

    1. #!/usr/bin/env python
    2. # -.- coding: utf-8 -.-
    3. # By sandler
    4. import pika
    5. ##############生产者###################
    6. connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.11.87'))
    7. channel = connection.channel()
    8. channel.queue_declare(queue='hello1')
    9. channel.basic_publish(exchange='', routing_key='hello1', body='Hello World!')
    10. print(" [X] Sent 'Hello World!'")
    11. connection.close()

    消费者:

    1. #!/usr/bin/env python
    2. # -.- coding: utf-8 -.-
    3. # By sandler
    4. import pika
    5. ###############消费者####################
    6. connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.11.87'))
    7. channel = connection.channel()
    8. channel.queue_declare(queue='hello1')
    9. def callback(ch, method, properties, body):
    10.    print('[x] Received %r' % body)
    11. channel.basic_consume(callback, queue='hello1', no_ack=True)
    12. print(' [*] Waiting for messages. To exit press CTRL+C')
    13. channel.start_consuming()


    发布订阅:

    发布者exchange示例:

    1. #!/usr/bin/env python
    2. # -.- coding: utf-8 -.-
    3. # By sandler
    4. import pika
    5. import sys
    6. #############发布端######################
    7. connection = pika.BlockingConnection(pika.ConnectionParameters(
    8.        host='192.168.11.87'))
    9. channel = connection.channel()
    10. channel.exchange_declare(exchange='logs_fanout',
    11.                         type='fanout')
    12. # message = ' '.join(sys.argv[1:]) or "info: Hello World!"
    13. message = 'test'
    14. channel.basic_publish(exchange='logs_fanout',
    15.                      routing_key='',
    16.                      body=message)
    17. print(" [x] Sent %r" % message)
    18. connection.close()


    订阅者exchange示例:

    1. #!/usr/bin/env python
    2. # -.- coding: utf-8 -.-
    3. # By sandler
    4. import pika
    5. ##################订阅者#####################
    6. connection = pika.BlockingConnection(pika.ConnectionParameters(
    7.        host='192.168.11.87'))
    8. channel = connection.channel()
    9. channel.exchange_declare(exchange='logs_fanout',
    10.                         type='fanout')
    11. result = channel.queue_declare(exclusive=True)
    12. queue_name = result.method.queue
    13. channel.queue_bind(exchange='logs_fanout',
    14.                   queue=queue_name)
    15. print(' [*] Waiting for logs. To exit press CTRL+C')
    16. def callback(ch, method, properties, body):
    17.    print(" [x] %r" % body)
    18. channel.basic_consume(callback,
    19.                      queue=queue_name,
    20.                      no_ack=True)
    21. channel.start_consuming()


    关键字方式示例:

    生产者:

    1. #!/usr/bin/env python
    2. # -.- coding: utf-8 -.-
    3. # By sandler
    4. import pika
    5. import sys
    6. #############生产者##############
    7. connection = pika.BlockingConnection(pika.ConnectionParameters(
    8.        host='192.168.11.87'))
    9. channel = connection.channel()
    10. channel.exchange_declare(exchange='direct_logs',
    11.                         type='direct')
    12. # severity = sys.argv[1] if len(sys.argv) > 1 else 'info'
    13. # message = ' '.join(sys.argv[2:]) or 'Hello World!'
    14. severity = 'info'
    15. message = '123'
    16. channel.basic_publish(exchange='direct_logs',
    17.                      routing_key=severity,
    18.                      body=message)
    19. print(" [x] Sent %r:%r" % (severity, message))
    20. connection.close()


    消费者1:

    1. #!/usr/bin/env python
    2. # -.- coding: utf-8 -.-
    3. # By sandler
    4. import pika
    5. import sys
    6. ################消费者######################
    7. connection = pika.BlockingConnection(pika.ConnectionParameters(
    8.        host='192.168.11.87'))
    9. channel = connection.channel()
    10. channel.exchange_declare(exchange='direct_logs',
    11.                         type='direct')
    12. result = channel.queue_declare(exclusive=True)
    13. queue_name = result.method.queue
    14. # severities = sys.argv[1:]
    15. # if not severities:
    16. #     sys.stderr.write("Usage: %s [info] [warning] [error] " % sys.argv[0])
    17. #     sys.exit(1)
    18. severities = ['error', 'info', 'warning']
    19. for severity in severities:
    20.    channel.queue_bind(exchange='direct_logs',
    21.                       queue=queue_name,
    22.                       routing_key=severity)
    23. print(' [*] Waiting for logs. To exit press CTRL+C')
    24. def callback(ch, method, properties, body):
    25.    print(" [x] %r:%r" % (method.routing_key, body))
    26. channel.basic_consume(callback,
    27.                      queue=queue_name,
    28.                      no_ack=True)
    29. channel.start_consuming()


    消费者2:

    1. #!/usr/bin/env python
    2. # -.- coding: utf-8 -.-
    3. # By sandler
    4. import pika
    5. import sys
    6. ################消费者######################
    7. connection = pika.BlockingConnection(pika.ConnectionParameters(
    8.        host='192.168.11.87'))
    9. channel = connection.channel()
    10. channel.exchange_declare(exchange='direct_logs',
    11.                         type='direct')
    12. result = channel.queue_declare(exclusive=True)
    13. queue_name = result.method.queue
    14. # severities = sys.argv[1:]
    15. # if not severities:
    16. #     sys.stderr.write("Usage: %s [info] [warning] [error] " % sys.argv[0])
    17. #     sys.exit(1)
    18. severities = ['error',]
    19. for severity in severities:
    20.    channel.queue_bind(exchange='direct_logs',
    21.                       queue=queue_name,
    22.                       routing_key=severity)
    23. print(' [*] Waiting for logs. To exit press CTRL+C')
    24. def callback(ch, method, properties, body):
    25.    print(" [x] %r:%r" % (method.routing_key, body))
    26. channel.basic_consume(callback,
    27.                      queue=queue_name,
    28.                      no_ack=True)
    29. channel.start_consuming()






    四、MySQL

    权限管理

    1、创建文件夹和文件:

    数据库、

    2、文件内部数据

    表内部的数据






    Navicat for MySQL图形化管理MySQL工具



    五、python pymysql

    安装模块:pip3 install pymysql

    http://www.cnblogs.com/wupeiqi/articles/5699254.html


    pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同。

    1、下载安装pymysql模块

    1. pip3 install pymysql

    2、使用操作

    执行SQL语句:

    1. #!/usr/bin/env python
    2. # -*- coding:utf-8 -*-
    3. import pymysql
    4.  
    5. # 创建连接
    6. conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')
    7. # 创建游标
    8. cursor = conn.cursor()
    9.  
    10. # 执行SQL,并返回收影响行数
    11. effect_row = cursor.execute("update hosts set host = '1.1.1.2'")
    12.  
    13. # 执行SQL,并返回受影响行数
    14. #effect_row = cursor.execute("update hosts set host = '1.1.1.2' where nid > %s", (1,))
    15.  
    16. # 执行SQL,并返回受影响行数
    17. #effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])
    18.  
    19.  
    20. # 提交,不然无法保存新建或者修改的数据
    21. conn.commit()
    22.  
    23. # 关闭游标
    24. cursor.close()
    25. # 关闭连接
    26. conn.close()

    获取新创建数据自增ID:

    1. #!/usr/bin/env python
    2. # -*- coding:utf-8 -*-
    3. import pymysql
    4.  
    5. conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')
    6. cursor = conn.cursor()
    7. cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])
    8. conn.commit()
    9. cursor.close()
    10. conn.close()
    11.  
    12. # 获取最新自增ID
    13. new_id = cursor.lastrowid

    获取查询数据:

    1. #!/usr/bin/env python
    2. # -*- coding:utf-8 -*-
    3. import pymysql
    4.  
    5. conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')
    6. cursor = conn.cursor()
    7. cursor.execute("select * from hosts")
    8.  
    9. # 获取第一行数据
    10. row_1 = cursor.fetchone()
    11.  
    12. # 获取前n行数据
    13. # row_2 = cursor.fetchmany(3)
    14. # 获取所有数据
    15. # row_3 = cursor.fetchall()
    16.  
    17. conn.commit()
    18. cursor.close()
    19. conn.close()

    注:在fetch数据时按照顺序进行,可以使用cursor.scroll(num,mode)来移动游标位置,如:

    1. cursor.scroll(1,mode='relative')  # 相对当前位置移动
    2. cursor.scroll(2,mode='absolute') # 相对绝对位置移动

    fetch数据类型

    1. #!/usr/bin/env python
    2. # -*- coding:utf-8 -*-
    3. import pymysql
    4.  
    5. conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')
    6.  
    7. # 游标设置为字典类型
    8. cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    9. r = cursor.execute("call p1()")
    10.  
    11. result = cursor.fetchone()
    12.  
    13. conn.commit()
    14. cursor.close()
    15. conn.close()



    六、Python ORM >SQLAchemy

    SQLAlchemy是Python编程语言下的一款ORM框架,该框架建立在数据库API之上,使用关系对象映射进行数据库操作,简言之便是:将对象转换成SQL,然后使用数据API执行SQL并获取执行结果。

    安装:

    1. pip3 install SQLAlchemy

    SQLAlchemy本身无法操作数据库,其必须以来pymsql等第三方插件,Dialect用于和数据API进行交流,根据配置文件的不同调用不同的数据库API,从而实现对数据库的操作,如:

    1. MySQL-Python
    2.    mysql+mysqldb://<user>:<password>@<host>[:<port>]/<dbname>
    3.  
    4. pymysql
    5.    mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]
    6.  
    7. MySQL-Connector
    8.    mysql+mysqlconnector://<user>:<password>@<host>[:<port>]/<dbname>
    9.  
    10. cx_Oracle
    11.    oracle+cx_oracle://user:pass@host:port/dbname[?key=value&key=value...]
    12.  
    13. 更多详见:http://docs.sqlalchemy.org/en/latest/dialects/index.html

    1、内部处理

    使用 Engine/ConnectionPooling/Dialect 进行数据库操作,Engine使用ConnectionPooling连接数据库,然后再通过Dialect执行SQL语句。

    1. #!/usr/bin/env python
    2. # -*- coding:utf-8 -*-
    3. from sqlalchemy import create_engine
    4.  
    5.  
    6. engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/t1", max_overflow=5)
    7.  
    8. # 执行SQL
    9. # cur = engine.execute(
    10. #     "INSERT INTO hosts (host, color_id) VALUES ('1.1.1.22', 3)"
    11. # )
    12.  
    13. # 新插入行自增ID
    14. # cur.lastrowid
    15.  
    16. # 执行SQL
    17. # cur = engine.execute(
    18. #     "INSERT INTO hosts (host, color_id) VALUES(%s, %s)",[('1.1.1.22', 3),('1.1.1.221', 3),]
    19. # )
    20.  
    21.  
    22. # 执行SQL
    23. # cur = engine.execute(
    24. #     "INSERT INTO hosts (host, color_id) VALUES (%(host)s, %(color_id)s)",
    25. #     host='1.1.1.99', color_id=3
    26. # )
    27.  
    28. # 执行SQL
    29. # cur = engine.execute('select * from hosts')
    30. # 获取第一行数据
    31. # cur.fetchone()
    32. # 获取第n行数据
    33. # cur.fetchmany(3)
    34. # 获取所有数据
    35. # cur.fetchall()

    2、ORM功能使用

    使用 ORM/Schema Type/SQL Expression Language/Engine/ConnectionPooling/Dialect 所有组件对数据进行操作。根据类创建对象,对象转换成SQL,执行SQL。

    创建表:

    1. #!/usr/bin/env python
    2. # -*- coding:utf-8 -*-
    3. from sqlalchemy.ext.declarative import declarative_base
    4. from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
    5. from sqlalchemy.orm import sessionmaker, relationship
    6. from sqlalchemy import create_engine
    7. engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/t1", max_overflow=5)
    8. Base = declarative_base()
    9. # 创建单表
    10. class Users(Base):
    11.    __tablename__ = 'users'
    12.    id = Column(Integer, primary_key=True)
    13.    name = Column(String(32))
    14.    extra = Column(String(16))
    15.    __table_args__ = (
    16.    UniqueConstraint('id', 'name', name='uix_id_name'),
    17.        Index('ix_id_name', 'name', 'extra'),
    18.    )
    19. # 一对多
    20. class Favor(Base):
    21.    __tablename__ = 'favor'
    22.    nid = Column(Integer, primary_key=True)
    23.    caption = Column(String(50), default='red', unique=True)
    24. class Person(Base):
    25.    __tablename__ = 'person'
    26.    nid = Column(Integer, primary_key=True)
    27.    name = Column(String(32), index=True, nullable=True)
    28.    favor_id = Column(Integer, ForeignKey("favor.nid"))
    29. # 多对多
    30. class Group(Base):
    31.    __tablename__ = 'group'
    32.    id = Column(Integer, primary_key=True)
    33.    name = Column(String(64), unique=True, nullable=False)
    34.    port = Column(Integer, default=22)
    35. class Server(Base):
    36.    __tablename__ = 'server'
    37.    id = Column(Integer, primary_key=True, autoincrement=True)
    38.    hostname = Column(String(64), unique=True, nullable=False)
    39. class ServerToGroup(Base):
    40.    __tablename__ = 'servertogroup'
    41.    nid = Column(Integer, primary_key=True, autoincrement=True)
    42.    server_id = Column(Integer, ForeignKey('server.id'))
    43.    group_id = Column(Integer, ForeignKey('group.id'))
    44. def init_db():
    45.    Base.metadata.create_all(engine)
    46. def drop_db():
    47.    Base.metadata.drop_all(engine)
    注:设置外检的另一种方式 ForeignKeyConstraint(['other_id'], ['othertable.other_id'])


    操作表:

    表结构 + 数据库连接

    1. #!/usr/bin/env python
    2. # -*- coding:utf-8 -*-
    3. from sqlalchemy.ext.declarative import declarative_base
    4. from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
    5. from sqlalchemy.orm import sessionmaker, relationship
    6. from sqlalchemy import create_engine
    7. engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/t1", max_overflow=5)
    8. Base = declarative_base()
    9. # 创建单表
    10. class Users(Base):
    11.    __tablename__ = 'users'
    12.    id = Column(Integer, primary_key=True)
    13.    name = Column(String(32))
    14.    extra = Column(String(16))
    15.    __table_args__ = (
    16.    UniqueConstraint('id', 'name', name='uix_id_name'),
    17.        Index('ix_id_name', 'name', 'extra'),
    18.    )
    19.    def __repr__(self):
    20.        return "%s-%s" %(self.id, self.name)
    21. # 一对多
    22. class Favor(Base):
    23.    __tablename__ = 'favor'
    24.    nid = Column(Integer, primary_key=True)
    25.    caption = Column(String(50), default='red', unique=True)
    26.    def __repr__(self):
    27.        return "%s-%s" %(self.nid, self.caption)
    28. class Person(Base):
    29.    __tablename__ = 'person'
    30.    nid = Column(Integer, primary_key=True)
    31.    name = Column(String(32), index=True, nullable=True)
    32.    favor_id = Column(Integer, ForeignKey("favor.nid"))
    33.    # 与生成表结构无关,仅用于查询方便
    34.    favor = relationship("Favor", backref='pers')
    35. # 多对多
    36. class ServerToGroup(Base):
    37.    __tablename__ = 'servertogroup'
    38.    nid = Column(Integer, primary_key=True, autoincrement=True)
    39.    server_id = Column(Integer, ForeignKey('server.id'))
    40.    group_id = Column(Integer, ForeignKey('group.id'))
    41.    group = relationship("Group", backref='s2g')
    42.    server = relationship("Server", backref='s2g')
    43. class Group(Base):
    44.    __tablename__ = 'group'
    45.    id = Column(Integer, primary_key=True)
    46.    name = Column(String(64), unique=True, nullable=False)
    47.    port = Column(Integer, default=22)
    48.    # group = relationship('Group',secondary=ServerToGroup,backref='host_list')
    49. class Server(Base):
    50.    __tablename__ = 'server'
    51.    id = Column(Integer, primary_key=True, autoincrement=True)
    52.    hostname = Column(String(64), unique=True, nullable=False)
    53. def init_db():
    54.    Base.metadata.create_all(engine)
    55. def drop_db():
    56.    Base.metadata.drop_all(engine)
    57. Session = sessionmaker(bind=engine)
    58. session = Session()

    增加

    1. obj = Users(name="alex0", extra='sb')
    2. session.add(obj)
    3. session.add_all([
    4.    Users(name="alex1", extra='sb'),
    5.    Users(name="alex2", extra='sb'),
    6. ])
    7. session.commit()

    删除

    1. session.query(Users).filter(Users.id > 2).delete()
    2. session.commit()

    修改

    1. session.query(Users).filter(Users.id > 2).update({"name" : "099"})
    2. session.query(Users).filter(Users.id > 2).update({Users.name: Users.name + "099"}, synchronize_session=False)
    3. session.query(Users).filter(Users.id > 2).update({"num": Users.num + 1}, synchronize_session="evaluate")
    4. session.commit()

    查找

    1. ret = session.query(Users).all()
    2. ret = session.query(Users.name, Users.extra).all()
    3. ret = session.query(Users).filter_by(name='alex').all()
    4. ret = session.query(Users).filter_by(name='alex').first()

    其他

    1. # 条件
    2. ret = session.query(Users).filter_by(name='alex').all()
    3. ret = session.query(Users).filter(Users.id > 1, Users.name == 'eric').all()
    4. ret = session.query(Users).filter(Users.id.between(1, 3), Users.name == 'eric').all()
    5. ret = session.query(Users).filter(Users.id.in_([1,3,4])).all()
    6. ret = session.query(Users).filter(~Users.id.in_([1,3,4])).all()
    7. ret = session.query(Users).filter(Users.id.in_(session.query(Users.id).filter_by(name='eric'))).all()
    8. from sqlalchemy import and_, or_
    9. ret = session.query(Users).filter(and_(Users.id > 3, Users.name == 'eric')).all()
    10. ret = session.query(Users).filter(or_(Users.id < 2, Users.name == 'eric')).all()
    11. ret = session.query(Users).filter(
    12.    or_(
    13.        Users.id < 2,
    14.        and_(Users.name == 'eric', Users.id > 3),
    15.        Users.extra != ""
    16.    )).all()
    17. # 通配符
    18. ret = session.query(Users).filter(Users.name.like('e%')).all()
    19. ret = session.query(Users).filter(~Users.name.like('e%')).all()
    20. # 限制
    21. ret = session.query(Users)[1:2]
    22. # 排序
    23. ret = session.query(Users).order_by(Users.name.desc()).all()
    24. ret = session.query(Users).order_by(Users.name.desc(), Users.id.asc()).all()
    25. # 分组
    26. from sqlalchemy.sql import func
    27. ret = session.query(Users).group_by(Users.extra).all()
    28. ret = session.query(
    29.    func.max(Users.id),
    30.    func.sum(Users.id),
    31.    func.min(Users.id)).group_by(Users.name).all()
    32. ret = session.query(
    33.    func.max(Users.id),
    34.    func.sum(Users.id),
    35.    func.min(Users.id)).group_by(Users.name).having(func.min(Users.id) >2).all()
    36. # 连表
    37. ret = session.query(Users, Favor).filter(Users.id == Favor.nid).all()
    38. ret = session.query(Person).join(Favor).all()
    39. ret = session.query(Person).join(Favor, isouter=True).all()
    40. # 组合
    41. q1 = session.query(Users.name).filter(Users.id > 2)
    42. q2 = session.query(Favor.caption).filter(Favor.nid < 2)
    43. ret = q1.union(q2).all()
    44. q1 = session.query(Users.name).filter(Users.id > 2)
    45. q2 = session.query(Favor.caption).filter(Favor.nid < 2)
    46. ret = q1.union_all(q2).all()


    3、示例:


    1. #!/usr/bin/env python
    2. # -.- coding: utf-8 -.-
    3. # By sandler
    4. from sqlalchemy.ext.declarative import declarative_base
    5. from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
    6. from sqlalchemy.orm import sessionmaker, relationship
    7. from sqlalchemy import create_engine
    8. engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/s13", max_overflow=5)
    9. Base = declarative_base()
    10. # 创建单表
    11. class Users(Base):
    12.    __tablename__ = 'users'
    13.    id = Column(Integer, primary_key=True)
    14.    name = Column(String(32))
    15.    extra = Column(String(16))
    16.    __table_args__ = (
    17.    UniqueConstraint('id', 'name', name='uix_id_name'),
    18.        Index('ix_id_name', 'name', 'extra'),
    19.    )
    20. # 一对多
    21. class Favor(Base):
    22.    __tablename__ = 'favor'
    23.    nid = Column(Integer, primary_key=True)
    24.    caption = Column(String(50), default='red', unique=True)
    25. class Person(Base):
    26.    __tablename__ = 'person'
    27.    nid = Column(Integer, primary_key=True)
    28.    name = Column(String(32), index=True, nullable=True)
    29.    favor_id = Column(Integer, ForeignKey("favor.nid"))
    30. # 多对多
    31. class ServerToGroup(Base):
    32.    __tablename__ = 'servertogroup'
    33.    nid = Column(Integer, primary_key=True, autoincrement=True)
    34.    server_id = Column(Integer, ForeignKey('server.id'))
    35.    group_id = Column(Integer, ForeignKey('group.id'))
    36. class Group(Base):
    37.    __tablename__ = 'group'
    38.    id = Column(Integer, primary_key=True)
    39.    name = Column(String(64), unique=True, nullable=False)
    40. class Server(Base):
    41.    __tablename__ = 'server'
    42.    id = Column(Integer, primary_key=True, autoincrement=True)
    43.    hostname = Column(String(64), unique=True, nullable=False)
    44.    port = Column(Integer, default=22)
    45. # Base.metadata.create_all(engine)  # 创建所有
    46. # Base.metadata.drop_all(engine)    # 删除所有







    七、Paramiko






    八、堡垒机、跳板机





















  • 相关阅读:
    2020-2021-2 网络对抗技术 20181318 Exp8 Web综合
    2020-2021-2 网络对抗技术 20181318 Exp7 网络欺诈防范
    2020-2021-2 网络对抗技术 20181318 Exp6 MSF应用基础
    实验一:密码引擎-加密API研究
    2020-2021-2 网络对抗技术 20181318 Exp5 信息搜集与漏洞扫描
    2020-2021-2 网络对抗技术 20181318 Exp4 恶意代码分析
    2020-2021-2 网络对抗技术 2018318 Exp3 免杀原理与实践
    2020-2021-2 网络对抗技术 20181318 Exp2 后门原理与实践
    2020-2021-2 网络对抗技术 20181318 Exp1 PC平台逆向破解
    makefile及其相关知识介绍
  • 原文地址:https://www.cnblogs.com/sandler613/p/5720000.html
Copyright © 2020-2023  润新知