Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to HTTP 'Keep-Alive' in Python3.2 with urllib

I try to keep a HTTP Connection with urllib.request in Python 3.2.3 alive with this code:

handler = urllib.request.HTTPHandler()
opener = urllib.request.build_opener(handler)
opener.addheaders = [("connection", "keep-alive"), ("Cookie", cookie_value)]
r = opener.open(url)

But if I listen to the connection with Wireshark I get an Header with "Connection: closed" but set Cookie.

Host: url
Cookie: cookie-value
Connection: close

What do I have to do to set Headerinfo to Connection: keep-alive?

like image 700
haidaner Avatar asked Nov 03 '13 21:11

haidaner


2 Answers

If you need something more automatic than plain http.client, this might help, though it's not threadsafe.

from http.client import HTTPConnection, HTTPSConnection
import select
connections = {}


def request(method, url, body=None, headers={}, **kwargs):
    scheme, _, host, path = url.split('/', 3)
    h = connections.get((scheme, host))
    if h and select.select([h.sock], [], [], 0)[0]:
        h.close()
        h = None
    if not h:
        Connection = HTTPConnection if scheme == 'http:' else HTTPSConnection
        h = connections[(scheme, host)] = Connection(host, **kwargs)
    h.request(method, '/' + path, body, headers)
    return h.getresponse()


def urlopen(url, data=None, *args, **kwargs):
    resp = request('POST' if data else 'GET', url, data, *args, **kwargs)
    assert resp.status < 400, (resp.status, resp.reason, resp.read())
    return resp
like image 80
Collin Anderson Avatar answered Sep 24 '22 01:09

Collin Anderson


I keep connection alive by use http-client

import http.client
conn = http.client.HTTPConnection(host, port)
conn.request(method, url, body, headers)

the headers just give dict and body still can use urllib.parse.urlencode. so, you can make Cookie header by http client.

reference:
official reference

like image 38
FreedomKnight Avatar answered Sep 23 '22 01:09

FreedomKnight