Python 十一、python网络编程

一、MySQLdb模块

python访问mariadb|mysql依赖于第三方模块MySQLdb,在pypi上下载下来

路径:https://pypi.python.org/pypi/MySQL-python/

MySQL-python依赖于easy_install那先安装setuptools,这里省略

[[email protected] ~]# unzip MySQL-python-1.2.5.zip

[[email protected] ~]# cd MySQL-python-1.2.5
[[email protected] MySQL-python-1.2.5]# ls
doc      MANIFEST.in   _mysql_exceptions.py   README.md        setup.py
GPL-2.0  metadata.cfg  MySQL_python.egg-info  setup.cfg        setup_windows.py
HISTORY  _mysql.c      PKG-INFO               setup_common.py  site.cfg
INSTALL  MySQLdb       pymemcompat.h          setup_posix.py   tests

[[email protected] MySQL-python-1.2.5]# python2.7 setup.py install
sh: mysql_config: command not found                            #没找到这个命令
Traceback (most recent call last):
  File "setup.py", line 17, in <module>
    metadata, options = get_config()
  File "/root/MySQL-python-1.2.5/setup_posix.py", line 43, in get_config
    libs = mysql_config("libs_r")
  File "/root/MySQL-python-1.2.5/setup_posix.py", line 25, in mysql_config
    raise EnvironmentError("%s not found" % (mysql_config.path,))
EnvironmentError: mysql_config not found

[[email protected] MySQL-python-1.2.5]# yum install mysql

[[email protected] MySQL-python-1.2.5]# rpm -ql mysql
/usr/bin/msql2mysql
/usr/bin/my_print_defaults
/usr/bin/mysql
/usr/bin/mysql_config                   #在这里
/usr/bin/mysql_find_rows
/usr/bin/mysql_waitpid
/usr/bin/mysqlaccess
/usr/bin/mysqladmin
/usr/bin/mysqlbinlog
/usr/bin/mysqlcheck
/usr/bin/mysqldump
/usr/bin/mysqlimport
/usr/bin/mysqlshow
/usr/bin/mysqlslap
/usr/lib64/mysql/mysql_config
/usr/lib64/mysql/mysqlbug
/usr/share/doc/mysql-5.1.73

[[email protected] MySQL-python-1.2.5]# python2.7 setup.py install

_mysql.c: In function ‘_mysql_ConnectionObject_getattr’:
_mysql.c:2666: error: ‘_mysql_ConnectionObject’ has no member named ‘open’
error: command ‘gcc‘ failed with exit status 1    #又遇到报错,google后是需要mysql-devel

[[email protected] MySQL-python-1.2.5]# yum install mysql-devel

[[email protected] MySQL-python-1.2.5]# python2.7 setup.py install

Adding MySQL-python 1.2.5 to easy-install.pth file

Installed /usr/local/python27/lib/python2.7/site-packages/MySQL_python-1.2.5-py2.7-linux-x86_64.egg
Processing dependencies for MySQL-python==1.2.5
Finished processing dependencies for MySQL-python==1.2.5      #安装成功

导入MySQLdb模块:

In [4]: import MySQLdb

In [5]: import MySQLdb.                #有众多方法和属性
MySQLdb.BINARY              MySQLdb.NULL                MySQLdb.connect
MySQLdb.Binary              MySQLdb.NUMBER              MySQLdb.connections
MySQLdb.Connect             MySQLdb.NotSupportedError   MySQLdb.constants
MySQLdb.Connection          MySQLdb.OperationalError    MySQLdb.converters
MySQLdb.DATE                MySQLdb.ProgrammingError    MySQLdb.cursors
MySQLdb.DBAPISet            MySQLdb.ROWID               MySQLdb.debug
MySQLdb.DataError           MySQLdb.STRING              MySQLdb.escape
MySQLdb.DatabaseError       MySQLdb.TIME                MySQLdb.escape_dict
MySQLdb.Date                MySQLdb.TIMESTAMP           MySQLdb.escape_sequence
MySQLdb.DateFromTicks       MySQLdb.Time                MySQLdb.escape_string
MySQLdb.Error               MySQLdb.TimeFromTicks       MySQLdb.get_client_info
MySQLdb.FIELD_TYPE          MySQLdb.Timestamp           MySQLdb.paramstyle
MySQLdb.IntegrityError      MySQLdb.TimestampFromTicks  MySQLdb.release
MySQLdb.InterfaceError      MySQLdb.Warning             MySQLdb.string_literal
MySQLdb.InternalError       MySQLdb._mysql              MySQLdb.threadsafety
MySQLdb.MySQLError          MySQLdb._mysql_exceptions   MySQLdb.times
MySQLdb.MySQLdb             MySQLdb.apilevel            MySQLdb.version_info

In [11]: help(MySQLdb)

Help on package MySQLdb:

NAME
    MySQLdb - MySQLdb - A DB API v2.0 compatible interface to MySQL.

FILE
    /usr/local/python27/lib/python2.7/site-packages/MySQL_python-1.2.5-py2.7-linux-x86_64.egg/MySQLdb/__init__.py

DESCRIPTION
    This package is a wrapper around _mysql, which mostly implements the
    MySQL C API.
    
    connect() -- connects to server
    
    See the C API specification and the MySQL documentation for more info
    on other items.
    
    For information on how MySQLdb handles type conversion, see the
    MySQLdb.converters module.

PACKAGE CONTENTS             #包内容|子模块
    connections              #连接mysql
    constants (package)      #
    converters               #将Python中的字符串转化成mysql可以处理的数据类型
    cursors                  #游标
    release
    times
    
    
In [24]: help(MySQLdb.connection)

Help on class connection in module _mysql:

class connection(__builtin__.object)
 |  Returns a MYSQL connection object. Exclusive use of
 |  keyword parameters strongly recommended. Consult the
 |  MySQL C API documentation for more details.
 |  
 |  host
 |    string, host to connect
 |  
 |  user
 |    string, user to connect as
 |  
 |  passwd
 |    string, password to use
 |  
 |  db
 |    string, database to use
 |  
 |  port
 |    integer, TCP/IP port to connect to
 |  
 |  unix_socket
 |    string, location of unix_socket (UNIX-ish only)
 |  
 |  conv
 |    mapping, maps MySQL FIELD_TYPE.* to Python functions which
 |    convert a string to the appropriate Python type
 |  
 |  connect_timeout
 |    number of seconds to wait before the connection
 |    attempt fails.
 |  
 |  compress
 |    if set, gzip compression is enabled

示例:

In [2]: import MySQLdb

In [7]: conn=MySQLdb.connect(host=‘127.0.0.1‘,user=‘root‘)   #创建连接使用conncet

In [10]: conn.
conn.DataError               conn.close                   conn.get_host_info           conn.set_character_set
conn.DatabaseError           conn.commit                  conn.get_proto_info          conn.set_server_option
conn.Error                   conn.converter               conn.get_server_info         conn.set_sql_mode
conn.IntegrityError          conn.cursor                  conn.info                    conn.show_warnings
conn.InterfaceError          conn.cursorclass             conn.insert_id               conn.shutdown
conn.InternalError           conn.default_cursor          conn.kill                    conn.sqlstate
conn.NotSupportedError       conn.dump_debug_info         conn.literal                 conn.stat
conn.OperationalError        conn.encoders                conn.messages                conn.store_result
conn.ProgrammingError        conn.errno                   conn.next_result             conn.string_decoder
conn.Warning                 conn.error                   conn.open                    conn.string_literal
conn.affected_rows           conn.errorhandler            conn.ping                    conn.thread_id
conn.autocommit              conn.escape                  conn.port                    conn.unicode_literal
conn.begin                   conn.escape_string           conn.query                   conn.use_result
conn.change_user             conn.field_count             conn.rollback                conn.warning_count
conn.character_set_name      conn.get_autocommit          conn.select_db               
conn.client_flag             conn.get_character_set_info  conn.server_capabilities   

In [14]: conn.stat
Out[14]: <function stat>

In [15]: conn.stat()
Out[15]: ‘Uptime: 719  Threads: 1  Questions: 6  Slow queries: 0  Opens: 15  Flush tables: 1  Open tables: 8  Queries per second avg: 0.8‘

 

In [4]: s1=conn.cursor()                #创建游标   

In [5]: s1.
s1.DataError          s1.arraysize          s1.fetchone
s1.DatabaseError      s1.callproc           s1.lastrowid
s1.Error              s1.close              s1.messages
s1.IntegrityError     s1.connection         s1.nextset
s1.InterfaceError     s1.description        s1.rowcount
s1.InternalError      s1.description_flags  s1.rownumber
s1.MySQLError         s1.errorhandler       s1.scroll
s1.NotSupportedError  s1.execute            s1.setinputsizes
s1.OperationalError   s1.executemany        s1.setoutputsizes
s1.ProgrammingError   s1.fetchall           
s1.Warning            s1.fetchmany          

In [5]: s1.execute(‘SHOW DATABASES;‘)        #执行SQL语句     
Out[5]: 3L                                   #返回的结果

In [6]: s1.fe
s1.fetchall   s1.fetchmany  s1.fetchone   

In [6]: s1.fetchall()                       #详细查看返回的结果,此时游标已经指到了尾部
Out[6]: ((‘information_schema‘,), (‘mysql‘,), (‘test‘,))

In [7]: s1.fetchone()                     #这里没数据了,需要调整游标的位置

In [8]: s1.fetchmany
Out[8]: <bound method Cursor.fetchmany of <MySQLdb.cursors.Cursor object at 0x2db8e90>>

In [9]: s1.fetchmany()
Out[9]: ()

In [11]: s1.scroll(0,mode=‘absolute‘)      #移到首部

In [13]: s1.fetchone()                     #读取一行
Out[13]: (‘information_schema‘,)

In [14]: s1.fetchone()     
Out[14]: (‘mysql‘,)

In [15]: s1.fetchone()
Out[15]: (‘test‘,)

In [16]: s1.fetchone()

In [17]: s1.scroll(1,mode=‘absolute‘)

In [18]: s1.fetchone()
Out[18]: (‘mysql‘,)

In [19]: s1.fetchone()
Out[19]: (‘test‘,)

In [20]: s1.fetchone()

In [21]: s1.scroll(0,mode=‘absolute‘)

In [22]: s1.fetchmany()
Out[22]: ((‘information_schema‘,),)

In [23]: s1.fetchmany()
Out[23]: ((‘mysql‘,),)

In [24]: s1.fetchmany()
Out[24]: ((‘test‘,),)

In [25]: s1.fetchmany()
Out[25]: ()

In [26]: s1.scroll(0,mode=‘absolute‘)

In [32]: s1.fetchmany(3)                                  #可以指定一次读取几行
Out[32]: ((‘information_schema‘,), (‘mysql‘,), (‘test‘,))

In [33]: s1.fetchmany(2)
Out[33]: ()

In [34]: s1.scroll(0,mode=‘absolute‘)

In [35]: s1.fetchmany(2)
Out[35]: ((‘information_schema‘,), (‘mysql‘,))

In [36]: s1.close()     #关闭游标

In [37]: conn.close()  #关闭连接

二、socket模块

1、编写服务器端程序

1)创建socket

socket.socket(family,type)

family

AF_INET:

AF_UNIX:

type

SOCK_STREAM:tcp

SOCK_DGRAM:udp

示例:

tcpconn=scoket.socket(socket.AF_INET,sockot.SOCK_STREAM)

In [44]: import socket

In [45]: tcpconn=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

In [46]: tcpconn.
tcpconn.accept         tcpconn.getsockname    tcpconn.recvfrom_into
tcpconn.bind           tcpconn.getsockopt     tcpconn.send
tcpconn.close          tcpconn.gettimeout     tcpconn.sendall
tcpconn.connect        tcpconn.listen         tcpconn.sendto
tcpconn.connect_ex     tcpconn.makefile       tcpconn.setblocking
tcpconn.dup            tcpconn.proto          tcpconn.setsockopt
tcpconn.family         tcpconn.recv           tcpconn.settimeout
tcpconn.fileno         tcpconn.recv_into      tcpconn.shutdown
tcpconn.getpeername    tcpconn.recvfrom       tcpconn.type

2)绑定地址

使用套接字对象bind方法绑定于某地址和端口

tcpconn.bind((‘ip‘,port))

In [47]: help(tcpconn.bind)

Help on method bind:

bind(...) method of socket._socketobject instance
    bind(address)
    
    Bind the socket to a local address.  For IP sockets, the address is a
    pair (host, port); the host must refer to the local host. For raw packet
    sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])
(END) 

In [48]: tcpconn.bind("192.168.10.3",8023)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-48-a9abfbcc4351> in <module>()
----> 1 tcpconn.bind("192.168.10.3",8023)

/usr/local/python27/lib/python2.7/socket.pyc in meth(name, self, *args)
    222 
    223 def meth(name,self,*args):
--> 224     return getattr(self._sock,name)(*args)
    225 
    226 for _m in _socketmethods:

TypeError: bind() takes exactly one argument (2 given)

In [49]: tcpconn.bind(("192.168.10.3",8023)


 3)使用listen方法进行监听状态

tcpconn.listen(backlog)             #backlog  等待队列的长度

tcpconn.listen(100)

In [50]: tcpconn.listen(30)

[[email protected] ~]# ss -nlt
State       Recv-Q Send-Q                       Local Address:Port                         Peer Address:Port 
LISTEN      0      128                                      *:7500                                    *:*     
LISTEN      0      128                                      *:7501                                    *:*     
LISTEN      0      100                                      *:9422                                    *:*     
LISTEN      0      128                                     :::22                                     :::*     
LISTEN      0      128                                      *:22                                      *:*     
LISTEN      0      30                            192.168.10.3:8023                                    *:*     
LISTEN      0      100                                    ::1:25                                     :::*     
LISTEN      0      100                              127.0.0.1:25                                      *:*     
LISTEN      0      128                              127.0.0.1:6010                                    *:*     
LISTEN      0      128                                    ::1:6010                                   :::*     
LISTEN      0      128                              127.0.0.1:6011                                    *:*     
LISTEN      0      128                                    ::1:6011                                   :::*     
LISTEN      0      50                                       *:3306                                    *:*

 4)循环监听状态

使用套接字对象的accept方法接收用户请求

In [51]: help(tcpconn.accept)     #返回(客户端Ip地址,端口)
       
Help on method accept in module socket:

accept(self) method of socket._socketobject instance
    accept() -> (socket object, address info)
    
    Wait for an incoming connection.  Return a new socket representing the
    connection, and the address of the client.  For IP sockets, the address
    info is a pair (hostaddr, port).
    
    
 In [52]: ci,cp=tcpconn.accept()      #此时服务端阻塞

2、编写客户端程序

 1)创建一个socket对象,以连接服务器端

clientsock=socket.socket(socket.AF_INET,sock.SOCK_STREAM)

In [6]: import socket

In [7]: clientsock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

2)连接至服务器

clientscok.connect((‘server_ip‘,server_port))

In [8]: clientsock.connect((‘192.168.10.3‘,8023))

此时再观察服务器端:

In [55]: ci,cp=tcpconn.accept()         #服务器端收到数据,结束阻塞

In [56]: ci
Out[56]: <socket._socketobject at 0x2f16590>

In [57]: ci()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-57-3d2081a2327e> in <module>()
----> 1 ci()

TypeError: ‘_socketobject‘ object is not callable

In [58]: ci,cp             #返回2各对象,ci是一个socket对象,cp是一个元祖对象
Out[58]: (<socket._socketobject at 0x2f16590>, (‘192.168.10.3‘, 34873))

3)发送请求

clientscok.send()

In [9]: clientsock.send(‘hello server‘) 
Out[9]: 11

但这么操作当客户端连接进服务器端后,连接就断开了,我们应该写脚本来实现服务器处于循环监听状态

脚本文件:

[[email protected] ~]# cat server.py                #服务器端
#!/usr/local/bin/python2.7
#
import socket
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sa=("192.168.10.3",8030)
s.bind(sa)
s.listen(20)
while True:
    cinfo,caddr=s.accept()
    print "Got a connection from %s" %caddr[0]
    data=cinfo.recv(1024)
    print "Receive data:%s" %data
    cinfo.send("echo: " + data)
    cinfo.close()

[[email protected] ~]# cat client.py                   #客户端
#!/usr/local/bin/python2.7
#
import socket
c=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
saddr=("192.168.10.3",8030)
c.connect(saddr)
c.send("Hello Server")
data=c.recv(1024)
print "Reply from server %s" %data

执行脚本:

[[email protected] ~]# python2.7 server.py     #执行服务器端脚本
                                        #阻塞状态
[[email protected] ~]# python2.7  client.py    #执行客户端脚本
Reply from server echo: Hello Server

再看服务器端:

[[email protected] ~]# python2.7 server.py 
Got a connection from 192.168.10.3
Receive data:Hello Server
                                         #仍阻塞状态

修改下客户端脚本再执行一次:

[[email protected] ~]# vi client.py 
[[email protected] ~]# python2.7  client.py 
Reply from server echo: Hello SB

服务器端:

[[email protected] ~]# python2.7 server.py 
Got a connection from 192.168.10.3
Receive data:Hello Server
Got a connection from 192.168.10.3
Receive data:Hello SB
时间: 2024-08-10 17:03:12

Python 十一、python网络编程的相关文章

python高级之网络编程

python高级之网络编程 本节内容 网络通信概念 socket编程 socket模块一些方法 聊天socket实现 远程执行命令及上传文件 socketserver及其源码分析 1.网络通信概念 说到网络通信,那就不得不说TCP/IP协议簇的OSI七层模型了,这个东西当初在学校都学烂了...(PS:毕竟本人是网络工程专业出身...) 简单介绍下七层模型从底层到上层的顺序:物理层(定义物理设备的各项标准),数据链路层(mac地址等其他东西的封装),网络层(IP包头的的封装),传输层(TCP/UD

Python四大主流网络编程框架

目前Python的网络编程框架已经多达几十个,逐个学习它们显然不现实.但这些框架在系统架构和运行环境中有很多共通之处,本文带领读者学习基于Python网络框架开发的常用知识,及目前的4种主流Python网络框架:Django.Tornado.Flask.Twisted. 网络框架及MVC架构 所谓网络框架是指这样的一组Python包,它能够使开发者专注于网站应用业务逻辑的开发,而无须处理网络应用底层的协议.线程.进程等方面.这样能大大提高开发者的工作效率,同时提高网络应用程序的质量. 在目前Py

[CSAPP笔记][第十一章网络编程]

第十一章 网络编程 我们需要理解基本的客户端-服务端编程模型,以及如何编写使用因特网提供的服务的客户端-服务端程序. 最后,我们将把所有这些概念结合起来,开发一个小的但功能齐全的Web服务器,能够为真实的Web浏览器提供静态的和动态的文本和图形内容. 11.1 客户端 - 服务器编程模型 每个网络应用程序都是基于客户端 - 服务器模型的 采用这种模型,一个应用是由一个服务器进程 和一个或多个客户端进程组成. 服务器管理某种资源,并且通过操作这种资源为它的客户端提供某种服务. WEB服务器,代表客

Python TCP通信网络编程

最近在看廖雪峰老师的基础教程(http://www.liaoxuefeng.com/),今天实现了一下简单Python的Socket的网络编程. 1. Socket网络编程 Socket是网络编程的一个抽象概念.通常我们用一个Socket表示“打开了一个网络链接”,而打开一个Socket需要知道目标计算机的IP地址和端口号,再指定协议类型即可. 2. 客户端 大多数连接都是可靠的TCP连接.创建TCP连接时,主动发起连接的叫客户端,被动响应连接的叫服务器.举个例子,当我们在浏览器中访问新浪时,我

Python实践之网络编程1-简单的网络请求程序

在了解python基础的语法基础上,就可以自由的去组合出自己需要各类高级功能. 由于python语言的特性,各类功能的实现都会非常快捷的. 网络变成就是python具备的高级特性之一. 需要进行网络编程首先需要了解几个模块urllib和urllib2 1.简单的访问请求 import sys,urllib,urllib2 url=input("please input the url:") url = "http://mail.126.com" #发起请求 req

python之路 -- 网络编程

1.软件开发的架构 - C/S架构(需要安装应用程序使用的软件) c client 客户端 s server 服务端 - B/S架构(可以通过浏览器使用的) b broser 浏览器 s server 服务端 不需要额外的安装客户端了,只需要一个网址就可以访问 轻量级,使用成本低 2.tcp协议/udp协议 tcp协议 全双工的通信协议 建立了专门穿送数据的通道(连接),是一个长连接 面向流的传输 传输速率比udp协议慢 数据安全不容易丢失 大文件算法自己拆包编号发送 建立连接的 三次握手 断开

python学习之网络编程基础

引入场景:客户与银行关系 银行职员负责给客户提供取钱服务,客户通过账户密码跟银行职员建立合作关系.此时银行职员就可以作为服务器,当用户A取完钱后他需要等待下一个用户的接入,用户的账号密码就是建立合作关系的凭据.------简单的客户端/服务器架构模型. 客户端/服务器网络编程过程 一:创建套接字(通信端点) AF_XXX解释:地址家族名称,AF:Address Family 基于文件套接字 AF_UNIX 基于网络套接字 AF_INET 代表ipv4  (python网络编程中常用的套接字)  

『Python』socket网络编程

Python3网络编程 '''无论是str2bytes或者是bytes2str其编码方式都是utf-8 str( ,encoding='utf-8') bytes( ,encoding='utf-8') 而在使用.encode('utf-8')时,虽然type类型是byte,但常常报错''' Socket又称"套接字",应用程序通常通过"套接字"向网络发出请求或者应答网络请求,使主机间或者一台计算机上的进程间可以通讯. socket起源于UNIX,在Unix一切皆文

Python进阶之网络编程

网络通信 使用网络的目的 把多方链接在一起,进行数据传递: 网络编程就是,让不同电脑上的软件进行数据传递,即进程间通信: ip地址 ip地址概念和作用 IP地址是什么:比如192.168.1.1 这样的一些数字: ip地址的作用:用来在电脑中 标识唯一一台电脑,比如192.168.1.1:在本地局域网是唯一的. 网卡信息 查看网卡信息 Linux:ifconfig windows:ipconfig ensxx:用来与外部进行通信的网卡: lo:环回网卡,用来进行本地通信的: linux关闭/开启

python语法基础-网络编程-长期维护

###############    网络编程    ############## ###############    网络编程    ############## ###############    网络编程    ############## ###############    网络编程    ############## ###############    网络编程    ############## 原文地址:https://www.cnblogs.com/andy0816/p/