首页 > 代码库 > python学习--创建模块

python学习--创建模块

   昨天做了python客户端和服务器端通信,并把接收到的信息写到数据库,因为对数据库进行操作是个经常调用的行为,所以我想把调用数据库的操作写成一个module来给其它python程序调用,所以将昨天的服务器端程序拆分为两个文件:

1、主程序python.py

#!/usr/bin/env  python
import socket
import json
import connmysql
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM,0)
host = ‘‘
port = 1234
s.bind((host,port))
s.listen(3)
while True:
        client,ipaddr = s.accept()
        print "Got a connect from %s" %str(ipaddr)
        data=http://www.mamicode.com/client.recv(1024)"echo:"+data)
                        client.close()
                except:
                        client.send("Database ERROR")
                        client.close
        except:
                client.send("Data ERROR")
                client.close()


2、是数据库操作的module:

"""
this is a connect mysql module
"""
import socket
import MySQLdb
def mysql_Newhost(ip,hostname):
        conn = MySQLdb.connect(host="localhost",user="root",passwd="123456",db="python",unix_socket="/tmp/mysql.sock")
        cursor=conn.cursor()
        sql = "insert into python values(%s,%s)"
        print sql
        param = (ip,hostname)
        cursor.execute(sql,param)
        conn.commit()
        cursor.close()
        conn.close()
__version__ = ‘0.1‘


本文出自 “空の心” 博客,请务必保留此出处http://songknight.blog.51cto.com/2599480/1411986