Python之操作Redis、 RabbitMQ、SQLAlchemy、paramiko、mysql

一、Redis

Redis是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。
Redis是一个key-value存储系统。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set --有序集合)和hash(哈希类型)。这些数据类型都支持push/pop、add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的。在此基础上,redis支持各种不同方式的排序。与memcached一样,为了保证效率,数据都是缓存在内存中。区别的是redis会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文件,并且在此基础上实现了master-slave(主从)同步。
Redis 是一个高性能的key-value数据库。 redis的出现,很大程度补偿了memcached这类key/value存储的不足,在部分场合可以对关系数据库起到很好的补充作用。它提供了Java,C/C++,C#,PHP,JavaScript,Perl,Object-C,Python,Ruby,Erlang等客户端,使用很方便。
Redis支持主从同步。数据可以从主服务器向任意数量的从服务器上同步,从服务器可以是关联其他从服务器的主服务器。这使得Redis可执行单层树复制。存盘可以有意无意的对数据进行写操作。由于完全实现了发布/订阅机制,使得从数据库在任何地方同步树时,可订阅一个频道并接收主服务器完整的消息发布记录。同步对读取操作的可扩展性和数据冗余很有帮助。
1.Redis安装

$ wget http://download.redis.io/releases/redis-3.0.3.tar.gz
$ tar xzf redis-3.0.3.tar.gz
$ cd redis-3.0.3
$ make
$ src/redis-server
# 开启服务,默认端口号:6379

2.Package安装

$ sudo pip install redis
or
$ sudo easy_install redis
or from source
$ sudo python setup.py install
3.使用

>>> import redis
>>> r = redis.StrictRedis(host='localhost', port=6379, db=0)
>>> r.set('foo', 'bar')
True
>>> r.get('foo')
'bar'
管道(pipeline)是redis在提供单个请求中缓冲多条服务器命令的基类的子类。它通过减少服务器-客户端之间反复的TCP数据库包,从而大大提高了执行批量命令的功能。

>>> p.set('hello','redis').p.sadd('faz','baz').incr('num').execute()
当有大量类型文档的对象,文档的内容都不一样时,(即“表”没有固定的列),可以使用hash来表达。

复制代码
>>> r.hset('users:jdoe', 'name', "John Doe")
1L
>>> r.hset('users:jdoe', 'email', 'John@test.com')
1L
>>> r.hset('users:jdoe', 'phone', '1555313940')
1L
>>> r.hincrby('users:jdoe', 'visits', 1)
1L
>>> r.hgetall('users:jdoe')
{'phone': '1555313940', 'name': 'John Doe', 'visits': '1', 'email': 'John@test.com'}
>>> r.hkeys('users:jdoe')
['name', 'email', 'phone', 'visits']

二、RabbitMQ

RabbitMQ相当于一个消息代理,他完成接收和转发消息的功能,你可以把它想成一个邮局,起到中转作用。RabbitMQ会用到一些专业术语,如下:

>Producer:用来发送消息的程序被称为一个producer,我们用‘P’表示:

>Queue:队列,相当于邮箱的作用,他在创建后一直存活与RabbitMQ中,虽然消息可以在你的程序之间流动,但是在这中间的过程中,消息必须存在queue中,一下queue没有大小限制,你可以存无数的消息, (前提你必须预留1GB的硬盘空间) ,他就相当于一个没有限制的缓存。多个Producer可以发送消息到同一个queue,多个Consumer也可以从同一个queue中接收消息。一个queue可以用下面的图表示,图的上面是queue的名字。


>Consumer:一个用来接收消息的程序称之为Consumer,我们用下面的图表示:


注意,对于Producer和Consumer可以不在同一台host上面,后续博文会做介绍。

2.2两点传输“Hello World!”

需要两个程序,一个用来发送“Hello World!”,一个程序用来接收“Hello World!”并打印到屏幕上面。模型如下:


我们创建一个名字为hello的queue。Producer发送消息到hello的queue,Consumer从名为hello的queue中接收消息。

2.3sending(发送代码实现)

模型如下:


首先我们需要编写一个send.py程序,这个程序将向queue中发送一个消息,第一件事,我们要做的就是与rabbitmq-server建立连接,代码如下:

import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
如果我们想与不同的host建立连接,只需将‘localhost’换成IP地址。

接下来,我们需要确定接纳消息的queue的存在,如果我们把消息发送给不存在的queue,那么rabbitmq自动将消息丢弃,让我们创建一个消息队列queue,命名为‘hello’

channel.queue_declare(queue='hello')
在Rabbitmq中,一个消息不能直接发送给queue, 需要经过一个exchange,后续博文会讲到 ,现在我们只需将exchange设置为空字符串。

exchange很特别,他会识别我们的消息要发送给哪个消息队列queue,queue的名字需要用routing_key来标识,exchange通过routing_key确定消息发送至哪个消息队列queue。代码如下:

channel.basic_publish(exchange='',routing_key='hello',body='Hello World!')
print "[X] Sent 'Hello World!'"
在退出程序之前,我们需要清理缓存,并且确定我们的消息“Hello World!”真的发送给RabbitMQ了,我们可以通过关闭连接来完成,代码如下:

connection.close()
完整的send.py的代码如下:

import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
channel.basic_publish(exchange='',
routing_key='hello',
body='Hello World!')
print " [x] Sent 'Hello World!'"
connection.close()
2.4Receiving(接收代码实现)

模型如下所示:


我们的接收程序receive.py将接收消息,并将它打印在屏幕上。

同样首先,我们需要与rabbitmq-server建立连接,代码和send.py基本一致,代码如下:

import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel=connection.channel()
接下来,和前面一样,要确定去队列queue的存在,用queue_declare()创建队列,对于这个命令我们可以运行很多次,但只有一个名字为hello的queue存在。代码如下:

channel.queue_declare(queue='hello')
或许你会问,为什么我们要再次创建名字为hello的queue,前面我们已经建立了啊,当然,如果我们确定队列queue已经存在了,我们可以不加这段代码。例如,如果send.py程序在之前已经运行过了,但是我们不确定哪个程序时先运行的,这时候,我们在两个程序中同时声明queue就是必须的。

对于receive.py,我们要定义一个callback函数,在我们接受到消息的时候,pika库会调用callback函数,在我们的程序里,callback函数就是将接收到的消息打印在屏幕上。函数代码如下:

def callback(ch,method,properties,body):
print"[x] Received %r" %(body)
接下来我们需要告诉Rabbitmq,这个特殊的函数callback()的功能,就是从hello的queue中接收消息,代码如下:

channel.basic_consume(callback,queue='hello',no_ack=True)
对于代码中的 no_ack,后续的博客会提到。

最后,我们开启一个永不停止的线程来等待消息,在需要的时候运行callback()函数。代码如下:

print '[*] Waiting for message. To exit press CTRL+C'
channel.start_consuming()
完整的receive.py的代码如下:

import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
print ' [*] Waiting for messages. To exit press CTRL+C'
def callback(ch, method, properties, body):
print " [x] Received %r" % (body,)
channel.basic_consume(callback,
queue='hello',
no_ack=True)
channel.start_consuming()
2.5代码测试

首先打开一个命令行窗口,运行send.py代码,运行及结果如下:

$ :python send.py
[x] Sent 'Hello World!'
send.py每次运行完就停止,接下来让我们运行接收的代码receive.py,运行及结果如下:

$: python receive.py
[*] Waiting for messages. To exit press CTRL+C
[x] Received 'Hello World!'
你会看到,received.py运行起来后,不会停止,一直在那等待消息的传入,如果想停止,CTRL+C。

在一个新命令行窗口中继续运行send.py,运行receive.py的命令行窗口会继续输出相应信息。

2.6部分rabbitmq-server的命令行操作命令

1)查看各个queue的名称以及queue中的消息数

$: sudo rabbitmqctl list_queues
例如

$: sudo rabbitmqctl list_queues
Listing queues ...
hello 0
...done.
2)查看各exchange的名称

$: sudo rabbitmqctl list_exchanges

三、paramiko

1、SSHClient

用于连接远程服务器并执行基本命令

基于用户名密码连接:

import paramiko

# 创建SSH对象
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname='c1.salt.com', port=22, username='wupeiqi', password='123')

# 执行命令
stdin, stdout, stderr = ssh.exec_command('df')
# 获取命令结果
result = stdout.read()

# 关闭连接
ssh.close()

复制代码
import paramiko

transport = paramiko.Transport(('hostname', 22))
transport.connect(username='wupeiqi', password='123')

ssh = paramiko.SSHClient()
ssh._transport = transport

stdin, stdout, stderr = ssh.exec_command('df')
print stdout.read()

transport.close()
复制代码
基于公钥密钥连接:
示例
import paramiko

private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa')

# 创建SSH对象
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname='c1.salt.com', port=22, username='wupeiqi', key=private_key)

# 执行命令
stdin, stdout, stderr = ssh.exec_command('df')
# 获取命令结果
result = stdout.read()

# 关闭连接
ssh.close()

示例
import paramiko

private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa')

transport = paramiko.Transport(('hostname', 22))
transport.connect(username='wupeiqi', pkey=private_key)

ssh = paramiko.SSHClient()
ssh._transport = transport

stdin, stdout, stderr = ssh.exec_command('df')

transport.close()


2.SFTPClient

用于连接远程服务器并执行上传下载

基于用户名密码上传下载

import paramiko

transport = paramiko.Transport(('hostname',22))
transport.connect(username='wupeiqi',password='123')

sftp = paramiko.SFTPClient.from_transport(transport)
# 将location.py 上传至服务器 /tmp/test.py
sftp.put('/tmp/location.py', '/tmp/test.py')
# 将remove_path 下载到本地 local_path
sftp.get('remove_path', 'local_path')

transport.close()
基于公钥密钥上传下载


import paramiko

private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa')

transport = paramiko.Transport(('hostname', 22))
transport.connect(username='wupeiqi', pkey=private_key )

sftp = paramiko.SFTPClient.from_transport(transport)
# 将location.py 上传至服务器 /tmp/test.py
sftp.put('/tmp/location.py', '/tmp/test.py')
# 将remove_path 下载到本地 local_path
sftp.get('remove_path', 'local_path')

transport.close()

 

 

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import paramiko
import uuid

class Haproxy(object):

def __init__(self):
self.host = '172.16.103.191'
self.port = 22
self.username = 'wupeiqi'
self.pwd = '123'
self.__k = None

def create_file(self):
file_name = str(uuid.uuid4())
with open(file_name,'w') as f:
f.write('sb')
return file_name

def run(self):
self.connect()
self.upload()
self.rename()
self.close()

def connect(self):
transport = paramiko.Transport((self.host,self.port))
transport.connect(username=self.username,password=self.pwd)
self.__transport = transport

def close(self):

self.__transport.close()

def upload(self):
# 连接,上传
file_name = self.create_file()

sftp = paramiko.SFTPClient.from_transport(self.__transport)
# 将location.py 上传至服务器 /tmp/test.py
sftp.put(file_name, '/home/wupeiqi/tttttttttttt.py')

def rename(self):

ssh = paramiko.SSHClient()
ssh._transport = self.__transport
# 执行命令
stdin, stdout, stderr = ssh.exec_command('mv /home/wupeiqi/tttttttttttt.py /home/wupeiqi/ooooooooo.py')
# 获取命令结果
result = stdout.read()


ha = Haproxy()
ha.run()

四、mysql数据库的基本操作

1、数据库操作

show databases;
use [databasename];
create database [name];

2、数据表操作

show tables;

create table students
(
id int not null auto_increment primary key,
name char(8) not null,
sex char(4) not null,
age tinyint unsigned not null,
tel char(13) null default "-"
);

CREATE TABLE `wb_blog` (
`id` smallint(8) unsigned NOT NULL,
`catid` smallint(5) unsigned NOT NULL DEFAULT '0',
`title` varchar(80) NOT NULL DEFAULT '',
`content` text NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `catename` (`catid`)
) ;


3、数据操作

insert into students(name,sex,age,tel) values('alex','man',18,'151515151')

delete from students where id =2;

update students set name = 'sb' where id =1;

select * from students

4、其他

主键
外键
左右连接

 

 
posted @ 2016-07-30 06:41  puxiaobing  阅读(453)  评论(0编辑  收藏  举报