日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python连接服务器代码_python服务器端收发请求的实现代码

發布時間:2025/3/19 python 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python连接服务器代码_python服务器端收发请求的实现代码 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

最近學習了python的一些服務器端編程,記錄在此。

發送get/post請求

# coding:utf-8

import httplib,urllib #加載模塊

#urllib可以打開網站去拿

#res = urllib.urlopen('http://baidu.com');

#print res.headers

#定義需要進行發送的數據

params = urllib.urlencode({'param':'6'});

#定義一些文件頭

headers = {"Content-Type":"application/x-www-form-urlencoded",

"Connection":"Keep-Alive",'Content-length':'200'};

#與網站構建一個連接

conn = httplib.HTTPConnection("localhost:8765");

#開始進行數據提交 同時也可以使用get進行

conn.request(method="POST",url="/",body=params,headers=headers);

#返回處理后的數據

response = conn.getresponse();

print response.read()

#判斷是否提交成功

if response.status == 200:

print "發布成功!^_^!";

else:

print "發布失敗\^0^/";

#關閉連接

conn.close();

利用urllib模塊可以方便的實現發送http請求.urllib的參考手冊

http://docs.python.org/2/library/urllib.html

建立http服務器,處理get,post請求

# coding:utf-8

from BaseHTTPServer import HTTPServer,BaseHTTPRequestHandler

class RequestHandler(BaseHTTPRequestHandler):

def _writeheaders(self):

print self.path

print self.headers

self.send_response(200);

self.send_header('Content-type','text/html');

self.end_headers()

def do_Head(self):

self._writeheaders()

def do_GET(self):

self._writeheaders()

self.wfile.write("""

this is get!

"""+str(self.headers))

def do_POST(self):

self._writeheaders()

length = self.headers.getheader('content-length');

nbytes = int(length)

data = self.rfile.read(nbytes)

self.wfile.write("""

this is put!

"""+str(self.headers)+str(self.command)+str(self.headers.dict)+data)

addr = ('',8765)

server = HTTPServer(addr,RequestHandler)

server.serve_forever()

注意這里,python把response的消息體記錄在了rfile中。BaseHpptServer沒有實現do_POST方法,需要自己重寫。之后我們新建類RequestHandler,繼承自 baseHTTPServer 重寫do_POST方法,讀出rfile的內容即可。

但是要注意,發送端必須指定content-length.若不指定,程序就會卡在rfile.read()上,不知道讀取多少。

參考手冊 http://docs.python.org/2/library/basehttpserver.html

本文標題: python服務器端收發請求的實現代碼

本文地址: http://www.cppcns.com/jiaoben/python/114375.html

總結

以上是生活随笔為你收集整理的python连接服务器代码_python服务器端收发请求的实现代码的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。