在Python中使用Web Socket打开连接请求添加标头和cookie

时间:2015-03-06 01:17:23

标签: python websocket

要对自己进行身份验证,我需要在打开与Web套接字服务器的连接时添加身份验证Cookie以及一些标头字段和值。我已经探索了很多,但找不到任何简单明了的Python库来帮助我做到这一点。

3 个答案:

答案 0 :(得分:0)

您可以使用请求库:docs.python-requests.org

答案 1 :(得分:0)

AutobahnPython支持在WebSocket打开握手期间检查和设置HTTP标头。请参阅herehere

答案 2 :(得分:0)

如果符合您的需求,您可以查看urlliburllib2库。他们是更高级别的库,可以让你轻松地完成这类工作。例如,发送带有某些标题字段的请求将如下所示:

import urllib2
import urllib

#POST data you might want to send. If you don't want to send post data, just set this as None or blank, e.g. data = {}
data = urllib.urlencode({"username":uname, "passwd":yourpass, "submit":"Submit"})
#add as many header fields as you like
headers = {"Cookie":"<<your cookies go here>>", "Referer":"blahblah"} 

request = urllib2.Request("yourwebserver.com", data, headers)
#here you get your response back
response = urllib2.urlopen(request).read()

希望这对你有所帮助!干杯:!)