昨天做了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=client.recv(1024) print data metadata=json.loads(data) try: ip = metadata[0][‘ip‘] hostname = metadata[1][‘hostname‘] try: connmysql.ip = ip connmysql.hostname = hostname connmysql.mysql_Newhost(ip,hostname) client.send("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‘
时间: 2024-10-21 11:17:59