472,809 Members | 3,823 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,809 software developers and data experts.

send cookie on request with urllib2

Hi,

I dont understand why this is so complicated, just to add one line of
cookie header on the GET request.

This is my unworking code:
import time
import Cookie
import cookielib, urllib2

c= cookielib.Cookie(1,"Name","Tom", 80,False, "itay", False, False,
"d:\\asddd",False, False,time.time()+1000,False,None,None,None)
cj = cookielib.CookieJar()
cj.set_cookie(c)
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(c j))
opener.open(r'http://itay/temp.html")

why this isn't working?
Itay is my computer name. it is an IIS server too.
the code is running, but i dont see any cookie that attached to the GET
request.

thanks alot!

Apr 20 '06 #1
7 18998
"itay_k" <it****@gmail.com> writes:
Hi,

I dont understand why this is so complicated, just to add one line of
cookie header on the GET request.
You haven't said what you're really trying to do.

http://www.catb.org/~esr/faqs/smart-questions.html#goal

This is my unworking code:
import time
import Cookie
import cookielib, urllib2

c= cookielib.Cookie(1,"Name","Tom", 80,False, "itay", False, False,
"d:\\asddd",False, False,time.time()+1000,False,None,None,None)
Constructing your own Cookie instances is rarely necessary or
sensible. If you do, I recommend getting the constructor arguments by
inspecting the Cookie object the server actually returns, rather than
using the values you *think* you know are correct.

cj = cookielib.CookieJar()
cj.set_cookie(c)
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(c j))
opener.open(r'http://itay/temp.html")

why this isn't working?


Please define "working".

If you want to handle cookies when opening URLs, just do this:

opener = urllib2.build_opener(urllib2.HTTPCookieProcessor() )
opener.open("http://itay/temp.html")
# more .open() calls go here...
Of course, on the first HTTP request, cookie handling cannot have any
effect at all unless you've somehow loaded some old cookies first.
Your .open() may only involve a single HTTP request (though
server-side software may detect the absence of a cookie on the first
request, and do a page refresh or redirect so it can see its cookie
returned to it again; vanilla urllib2 handles redirects but not
refreshes; package ClientCookie handles the latter, amongst other
things).

Regardless, turning on cookielib and httplib debug output will likely
be helpful if you're stuck (if only to post the output to this
newsgroup):

import logging, urllib2, sys

hh = urllib2.HTTPHandler()
hsh = urllib2.HTTPSHandler()
hh.set_http_debuglevel(1)
hsh.set_http_debuglevel(1)
opener = urllib2.build_opener(hh, hsh, urllib2.HTTPCookieProcessor())
logger = logging.getLogger("cookielib")
logger.addHandler(logging.StreamHandler(sys.stdout ))
logger.setLevel(logging.DEBUG)

response = opener.open("http://wwwsearch.sf.net/cgi-bin/cookietest.cgi")
John

Apr 20 '06 #2
itay_k wrote:
Hi,

I dont understand why this is so complicated, just to add one line of
cookie header on the GET request.

This is my unworking code:
import time
import Cookie
import cookielib, urllib2

c= cookielib.Cookie(1,"Name","Tom", 80,False, "itay", False, False,
"d:\\asddd",False, False,time.time()+1000,False,None,None,None)


^^^^ path is the server path to which the cookie applies. Try '/'.

Kent
Apr 20 '06 #3
Kent Johnson <ke**@kentsjohnson.com> writes:
itay_k wrote:
Hi,

I dont understand why this is so complicated, just to add one line of
cookie header on the GET request.

This is my unworking code:
import time
import Cookie
import cookielib, urllib2

c= cookielib.Cookie(1,"Name","Tom", 80,False, "itay", False, False,
"d:\\asddd",False, False,time.time()+1000,False,None,None,None)


^^^^ path is the server path to which the cookie applies. Try '/'.


"""
"No," scolded Yoda. "Do, or do not. There is no try."
"""

(there, a Star Wars quote -- I guess there's truly no hope of ever
erasing my geek status now!-)

Why guess? Why not log in (using Python) and see what the cookie
actually is? Once you've actually done that, there's nothing to stop
you storing it as a Cookie constructor call.

I know I certainly don't remember all the *truly horrendous* detail of
what *exactly* all those parameters mean :-) The Cookie object, as is
documented, is merely a struct object and it is easy to construct
incorrect and even self-inconsistent Cookie objects; CookieJar has all
the knowledge about constructing cookies -- and allows use of that
knowledge through .make_cookies() and .load()/.revert().
John

Apr 20 '06 #4
ok.
i will explain what exactly i wanna do.

i want to simulate the following client-side script with python:
<body>
<img name="Pic">

<script>
document.cookie="name=tom";
document.images["Pic"].src="temp2.html"
</script>

what that happen here, is when this page loading, the browser loads
"temp2.html" with HTTP header:
Cookie: name=tom;

this cookie does not come for the server, this is temporary cookie that
sending from the client to the server.
this cookie doesnt save on disk at all.

is it possible to implements this at python??

Apr 21 '06 #5
"itay_k" <it****@gmail.com> writes:
ok.
i will explain what exactly i wanna do.

i want to simulate the following client-side script with python:
<body>
<img name="Pic">

<script>
document.cookie="name=tom";
document.images["Pic"].src="temp2.html"
</script>


Ah! In which case what you're trying to do is a reasonable hack, but
better (UNTESTED):

import urllib2, cookielib
cj = cookielib.CookieJar
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(c j))
request = urllib2.Request(url)
response = opener.open(request)
response["Set-Cookie"] = "name=tom"
cj.extract_cookies(response, request)
If you have HTML-parsing code to extract these JS cookies that you
want to run on every request (e.g. so even cookies set by JS during
redirections get handled), you can make all this transparent very
easily by using a handler similar to HTTPCookieProcessor itself (using
a recent version of package ClientCookie here for (a recent version
of) the response_seek_wrapper class) UNTESTED:
import urllib2, cookielib

class JSHTTPCookieProcessor(urllib2.BaseHandler):
handler_order = 400 # before HTTPCookieProcessor
def process_response(self, request, response):
from ClientCookie import response_seek_wrapper
if not hasattr(response, "seek"):
response = response_seek_wrapper(response)
try:
name, value = get_js_cookie(response) # your ugly HTML parsing code here ;-)
finally:
response.seek(0)
response["Set-Cookie"] = "%s=%s" % (name, value)
return response

opener = urllib2.build_opener(urllib2.HTTPCookieProcessor() ,
JSHTTPCookieProcessor())
response = opener.open(url) # now we're handling JS cookies transparently!

John

Apr 21 '06 #6
In article <ma***************************************@python. org>,
jj*@pobox.com (John J. Lee) wrote:
"No," scolded Yoda. "Do, or do not. There is no try."


Convincing argument against exceptions, don't you think. :)
Apr 22 '06 #7
Thanks!

Apr 22 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Venkat | last post by:
Hi All, I have to send a request to JSP with some key value pairs which is executing in a Web server. Please help me in solving this problem. I tried with the following procedure but I am not...
5
by: Rafael T. Ugolini | last post by:
Im trying to add more than one cookie with urllib2 but im not getting much sucess. An example... >>> req = urllib2.Request('http://localhost','j_username=psyca&j_password=******',{...
2
by: Matt | last post by:
The JSP page needs to send XML request string to another JSP page when the user clicks submit button, I wonder how to get started because when user click submit button, it will send the form to...
1
by: DFS | last post by:
MS has made many, many $millions selling Access as part of Office Pro. There's no excuse for it not to have a better ER diagramming component, so that when you talk to clients or work with other IT...
1
by: Vimala Sri | last post by:
Hello all, Have a great day. I wish to made interaction from c program in unix to the java servlet. That is i want to send a request from the Unix c program to the servlet. ...
3
by: korque | last post by:
Hi I'm gathering information from web page, first I get headers and store recieved cookies then I get source with file()-function. Is there easy way to send cookie value back to host on each...
5
by: Jimmy | last post by:
How can I do that? Is it possible to send a server request (i.e. GET) without refreshing the web page? Using Javascript? Or Ajax (i.e. AjaxAnywhere)? Or if there's a way (i.e. using...
3
by: Dave | last post by:
string m_request = some_web_page; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(m_request ); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Which works...
0
by: Atul Goyal | last post by:
Hello I want to send Http request by using swing . Can you help me fot that. ?
0
by: erikbower65 | last post by:
Here's a concise step-by-step guide for manually installing IntelliJ IDEA: 1. Download: Visit the official JetBrains website and download the IntelliJ IDEA Community or Ultimate edition based on...
0
by: kcodez | last post by:
As a H5 game development enthusiast, I recently wrote a very interesting little game - Toy Claw ((http://claw.kjeek.com/))。Here I will summarize and share the development experience here, and hope it...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Sept 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Taofi | last post by:
I try to insert a new record but the error message says the number of query names and destination fields are not the same This are my field names ID, Budgeted, Actual, Status and Differences ...
14
DJRhino1175
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
0
by: Rina0 | last post by:
I am looking for a Python code to find the longest common subsequence of two strings. I found this blog post that describes the length of longest common subsequence problem and provides a solution in...
5
by: DJRhino | last post by:
Private Sub CboDrawingID_BeforeUpdate(Cancel As Integer) If = 310029923 Or 310030138 Or 310030152 Or 310030346 Or 310030348 Or _ 310030356 Or 310030359 Or 310030362 Or...
0
by: Mushico | last post by:
How to calculate date of retirement from date of birth
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.