1. 程式人生 > >python 基礎之 socket介面與web介面

python 基礎之 socket介面與web介面

python 網路程式設計 主要有socket模組、BaseHTTPServer模組。socket屬於更底層次,方便在日常運維工作中使用, http web介面更適合開放給外部人員使用,畢竟大多數語言都很方便支援http請求。

首先看最基本socket客戶端與服務端例項:

#!/usr/bin/python
#coding=utf-8
import socket
host = 'xx'
socketport = '1009'
flag = 'xxxx'

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, int(socketport)))
sock.send(flag)
recv = sock.recv(1024)
print "接收終端返回碼:"+recv
sock.close()
#!/usr/bin/python
#coding=utf-8
import os
import sys
import commands
import traceback
import socket
reload(sys)
sys.setdefaultencoding('utf8')

def oscmd(buf):
    cmdtype = buf.strip()
    ##業務邏輯程式碼、處理完畢返回給客端#
    connection.send('sucess')

# Step1: 建立socket物件
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 讓socket支援地址複用 預設是不支援的
sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
# Step2: 配置socket  繫結IP和埠  
sock.bind(('0.0.0.0', 1009))
# 設定最大允許連線數,各連線和server的通訊遵循FIFO原則 
sock.listen(1)

# Step3: 迴圈輪詢socket狀態,等待訪問 
while 1:
    try:
        #獲取連線
        connection,address = sock.accept()
        buf = connection.recv(10240)
        src_ip = address[0]
        src_port = str(address[1])
        print "接收提交請求:["+ buf +"] 傳送源:["+ src_ip +":"+ src_port+"]"
        # Step4:處理請求資料,驗證更新key,錄入更新任務,返回處理結果
        oscmd(buf)
    except (KeyboardInterrupt, SystemExit):
        print "連結錯誤,請檢查!"
        raise Exception

 

socket多執行緒,同時併發處理多個請求。加入了python多執行緒而已

def handle_connection(conn,addr)


def main():
    # socket.AF_INET    用於伺服器與伺服器之間的網路通訊
    # socket.SOCK_STREAM    基於TCP的流式socket通訊
    serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 設定埠可複用,保證我們每次Ctrl C之後,快速再次重啟
    serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    serversocket.bind(('192.168.2.221', 10089))
    # 可參考:https://stackoverflow.com/questions/2444459/python-sock-listen
    serversocket.listen(5)
    try:
        while True:
            conn,addr = serversocket.accept()
            t = threading.Thread(target=handle_connection, args=(conn,addr))
            t.start()
    finally:
        serversocket.close()

 

web介面客戶端與服務端例項、服務端支援GET與POST請求

get請求
curl 192.168.11.xx:1009/api
post請求(json格式)
curl localhost:9999/api/daizhige/article -X POST -H "Content-Type:application/json" -d '"title":"comewords","content":"articleContent"'
#!/usr/bin/python
#encoding=utf-8
'''
基於BaseHTTPServer的http server實現,包括get,post方法,get引數接收,post引數接收。
'''
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import io,shutil
import urllib
import os, sys
import commands

class MyRequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        mpath,margs=urllib.splitquery(self.path) 
        self.do_action(mpath,margs)
    def do_POST(self):
        mpath,margs=urllib.splitquery(self.path)
        datas = self.rfile.read(int(self.headers['content-length']))
        self.do_action(mpath, datas)

    def do_action(self,args):
            self.outputtxt( args )

    def outputtxt(self, content):
        #指定返回編碼
        enc = "UTF-8"
        content = content.encode(enc)
        f = io.BytesIO()
        f.write(content)
        f.seek(0)
        self.send_response(200)
        self.send_header("Content-type", "text/html; charset=%s" % enc)
        self.send_header("Content-Length", str(len(content)))
        self.end_headers()
        shutil.copyfileobj(f,self.wfile)

def main():
    try:
        server = HTTPServer(('192.168.xx.219',1009),MyRequestHandler)
        print 'welcome to websocket'
        server.serve_forever()
    except KeyboardInterrupt:
        print 'shutting down server'
        server.socket.close()
if __name__ == '__main__':
    main()