Trying to set a cookie within a python script

Í

Íßêïò

Hello fellow Python Coders!

I don't see the error in my attempt to set a a cookie in this test
script. Can you help please?! Thank you!

Code:
#!/usr/bin/python
# -*- coding: utf-8 -*-

import Cookie

print ( "Content-type: text/html\n" )

cookie = Cookie.SimpleCookie()

if cookie.has_key('visitor') == "nikos"      #if visitor cookie exist
   print ( "Äåí óå åéäá, äåí óå îåñù, äåí óå áêïõóá. Èá åéóáé ï
áïñáóôïò åðéóêåðôçò!!" )
   cookie['visitor'] = ( 'nikos', time() - 1 )      #this cookie will
expire now
else
   print ( "Áðï äù êáé óôï åîçò äåí èá áõîáíù ôïí ìåôñçôç äéêç óïõ
åðéóêåøç!!" )
   cookie['visitor'] = ( 'nikos', time() + 60*60*24*365 )      #this
cookie will expire in an year
 
S

Steven D'Aprano

Hello fellow Python Coders!

I don't see the error in my attempt to set a a cookie in this test
script.

Neither do I. What makes you think there is an error? What sort of error?
Do you get a core dump, an exception, or something else?

Please report what you get, and what you expect, and how they are
different.
 
Î

Îίκος

Neither do I. What makes you think there is an error? What sort of error?
Do you get a core dump, an exception, or something else?

Please report what you get, and what you expect, and how they are
different.

Hello Steven,

Here is the script when it tries to run from my remote web server:
http://www.webville.gr/cgi-bin/koukos.py

Its seems the error is in this line of code, somwthing with time.

19 cookie['visitor'] = ( 'nikos', time() +
60*60*24*365 ) #this cookie will expire in an year
 
Í

Íßêïò

Also my greek print appear in funny encoding although i do use # -*-
coding: utf-8 -*-
 
M

MRAB

Îίκος said:
Also my greek print appear in funny encoding although i do use # -*-
coding: utf-8 -*-

That line just tells Python what encoding the source file itself uses.
It doesn't affect what the program does or how it runs.
 
S

Steven D'Aprano

On 2 ΑÏγ, 03:52, Steven D'Aprano <[email protected]>
wrote:
Neither do I. What makes you think there is an error? What sort of
error? Do you get a core dump, an exception, or something else?

Please report what you get, and what you expect, and how they are
different.

Hello Steven,

Here is the script when it tries to run from my remote web server:
http://www.webville.gr/cgi-bin/koukos.py

Its seems the error is in this line of code, somwthing with time.

19 cookie['visitor'] = ( 'nikos', time() + 60*60*24*365 )
#this cookie will expire in an year


What error? Please copy and paste (do not retype) the entire error you
get.
 
Î

Îίκος

If you just click in my web page to see the script run in action due
to the cgitb module i use it will provide you both the source code
that the error appears and the error as well.

All you have to do is click here: http://www.webville.gr/cgi-bin/koukos.py

As for the encoding why when i print greek characters they dont appear
correctly in chrome in runtime?
 
S

Steven D'Aprano

If you just click in my web page to see the script run in action due to
the cgitb module i use it will provide you both the source code that the
error appears and the error as well.

All you have to do is click here:
http://www.webville.gr/cgi-bin/koukos.py

I'll do this just once, but next time, don't expect others to track down
the error message for you. We're volunteers, we don't owe you anything,
so if you want us to help, you make it easy for us. Some people have
access to email, but not web. If you can't be bothered to copy and paste
the error message into an email or news post, why should we be bothered
to help you?


The error you are getting is:

NameError: name 'time' is not defined

That tells you that you don't have a function called time() defined
anywhere. You need to import the time module first:

import time

and then use the fully qualified function name time.time(), or do:

from time import time

and then use the function alone time().
As for the encoding why when i print greek characters they dont appear
correctly in chrome in runtime?

What encoding does the web page claim to be?

You need to check the document encoding, and see that it matches the
document encoding you are actually using.
 
Î

Îίκος

Steven,

First of all thank you for your response. I cant beleive i neglected
to import the time module!

The only reason that i asked you guys to follow the link was for you
to see the actualt coding and error report as python produces it by
itself with all the relative characteristics. Of course it was not due
to boredom and there was no need to be aggresive with me as this
wasn't the case. I thouigh that by giving the URL was easier for you
guys.

Now the script runs but for some reason only the code block within the
'else' tun each time:

This:
else:
print "ΑΠΟ ΔΩ ΚΑΙ ΣΤΟ ΕΞΗΣ ΔΕΠΣΕ ΕΙΔΑ, ΔΕΠΣΕ ΞΕΡΩ, ΔΕΠΣΕ ΑΚΟΥΣΑ!
ΘΑ ΕΙΣΑΙ ΠΛΕΟΠΟ ΑΟΡΑΤΟΣ ΕΠΙΣΚΕΠΤΗΣ!!"
cookie['visitor'] = ( 'nikos', time() + 60*60*24*365 ) #this cookie
will expire in an year

The cookie is only get set and never expires

i changed the if with this

if os.environ.get('HTTP_COOKIE') and cookie.has_key('visitor') ==
'nikos': #if visitor cookie exist

but still no luck.

As for the encoding Notepad++, which is what i use for an editor say
its UTF-8 without BOM.

Isn't this what i'm supposed to use?

My Python scripts only containes english and greek letters, so i
though usign UTF-8 is the way to go. No?! Please if you explain to me
in greater detail!
 
T

Thomas Jollans

Also my greek print appear in funny encoding although i do use # -*-
coding: utf-8 -*-

That's because you never told the web browser which encoding you're using.

Content-Type: text/html; charset=UTF-8
 
T

Thomas Jollans

Hello, any ideas?!

That's no way to treat a friendly volunteer mailing list like this one!


As for the encoding Notepad++, which is what i use for an editor say
its UTF-8 without BOM.

Isn't this what i'm supposed to use?

My Python scripts only containes english and greek letters, so i
though usign UTF-8 is the way to go. No?! Please if you explain to me
in greater detail!

As I said, you have to tell the browser what you're up to.

Also, I just checked the link (shame on me), and you're not using UTF-8
at all. You're using some weird Windows-xyz or ISO-8859-xyz Greek
codepage from the previous millennium. (which obviously my browser
didn't know, it thought you were using ISO-8859-1, because that's what
my browser does, which you weren't)


So: tripple-check that

* your file is <insert encoding here (aka UTF-8)>
* Python knows that
* the web browser knows that
 
Î

Îίκος

So: tripple-check that

 * your file is <insert encoding here (aka UTF-8)>
 * Python knows that
 * the web browser knows that

Thank you! i used print ''' Content-Type: text/html; charset=UTF-8 /
n''' and it worked.
I'am still pretty confused about the encodings.

Please tell me the difference between 3 things.

a) Asking Notepad++(my editor) to save all my python scripts as UTF-8
without BOM.
b) Using this line '# -*- coding: utf-8 -*-' Isn't this line supposed
to tell browser that the contents of this python script as in UTF-8
and to handle it as such?
c) print ''' Content-Type: text/html; charset=UTF-8 /n'''

Please explain to me as simple as you can because from the time with
php and perl encodings not only gave me a hard time but also caused my
program to produce internal server errors so i need to understand the
differences.

=========================
Also in the other problem with the cookie iam trying to set:
=========================
if os.environ.get('HTTP_COOKIE') and cookie.has_key('visitor') ==
'nikos': #if visitor cookie exist
print "Next time i will count you"
cookie['visitor'] = ( 'nikos', time() - 1 ) #this cookie will expire
now
else:
print "I wont be counting you any more"
cookie['visitor'] = ( 'nikos', time() + 60*60*24*365 ) #this cookie
will expire in an year
=========================

Why always the code block pertainign to 'else' get exectuted ane never
the code of 'if'
The idea is who ever runs 'koukos.py' to set/unset himself out of the
counter count so i need i way to set/unset the browser cookie!

Thanks you!
 
Î

Îίκος

So: tripple-check that

 * your file is <insert encoding here (aka UTF-8)>
 * Python knows that
 * the web browser knows that

Thank you! i used print ''' Content-Type: text/html; charset=UTF-8 /
n''' and it worked.
I'am still pretty confused about the encodings.

Please tell me the difference between 3 things.

a) Asking Notepad++(my editor) to save all my python scripts as UTF-8
without BOM.
b) Using this line '# -*- coding: utf-8 -*-' Isn't this line supposed
to tell browser that the contents of this python script as in UTF-8
and to handle it as such?
c) print ''' Content-Type: text/html; charset=UTF-8 /n'''

Please explain to me as simple as you can because from the time with
php and perl encodings not only gave me a hard time but also caused my
program to produce internal server errors so i need to understand the
differences.

=========================
Also in the other problem with the cookie iam trying to set:
=========================
if os.environ.get('HTTP_COOKIE') and cookie.has_key('visitor') ==
'nikos': #if visitor cookie exist
print "Next time i will count you"
cookie['visitor'] = ( 'nikos', time() - 1 ) #this cookie will expire
now
else:
print "I wont be counting you any more"
cookie['visitor'] = ( 'nikos', time() + 60*60*24*365 ) #this cookie
will expire in an year
=========================

Why always the code block pertainign to 'else' get exectuted ane never
the code of 'if'
The idea is who ever runs 'koukos.py' to set/unset himself out of the
counter count so i need i way to set/unset the browser cookie!

Thanks you!
 
C

Chris Rebert

2010/8/2 Îίκος said:
Thank you! i used print ''' Content-Type: text/html; charset=UTF-8 /
n''' and it worked.
I'am still pretty confused about the encodings.

Please tell me the difference between 3 things.

a) Asking Notepad++(my editor) to save all my python scripts as UTF-8
without BOM.

That affects what encoding the text file comprising the source code
itself is in.
b) Using this line '# -*- coding: utf-8 -*-' Isn't this line supposed
to tell browser that the contents of this python script as in UTF-8
and to handle it as such?

This tells Python what encoding the text file comprising the source
code itself is in.
c) print ''' Content-Type: text/html; charset=UTF-8 /n'''

This tells the web browser what encoding the HTML you're sending it is
in. Said HTML is output by your Python script and must match the
encoding you specify in (c).

Unless you have Unicode string literals in the source code itself, (a)
and (b) don't matter much. (c) is quite crucial.

Cheers,
Chris
 
D

Dave Angel

��������������������������������� said:
Thank you! i used print ''' Content-Type: text/html; charset=F-8 /
n''' and it worked.
I'am still pretty confused about the encodings.

Please tell me the difference between 3 things.

a) Asking Notepad++(my editor) to save all my python scripts as UTF-8
without BOM.
b) Using this line '# -*- coding: utf-8 -*-' Isn't this line supposed
to tell browser that the contents of this python script as in UTF-8
and to handle it as such?
c) print ''' Content-Type: text/html; charset=F-8 /n'''

Please explain to me as simple as you can because from the time with
php and perl encodings not only gave me a hard time but also caused my
program to produce internal server errors so i need to understand the
differences.

<snip>
There actually should be more than 3 things here. To understand the
distinctions you have to see who handles which data, and how.

a) a text editor takes keystrokes and cut/paste info and other data, and
produces a stream of (unicode) characters. It then encodes each of
those character into one or more bytes and saves it to a file. You have
to tell Notepad++ how to do that encoding. Note that unless it's saving
a BOM, there's no clue in the file what encoding it used.

b) The python compiler has to interpret the bytes it finds (spec. within
string literals and comments), and decode them into unicode for its own
work. It uses the 'coding:' comment to decide how to do this. But once
the file has been compiled, that comment is totally irrelevant, and ignored.

c1) Your python code has to decide how to encode its information when
writing to stdout. There are several ways to accomplish that.

c2) The browser sees only what was sent to stdout, starting with the
"Content-Type..." line. It uses that line to decide how to decode the
rest of the stream. Let me reemphasize, the browser does not see any of
the python code, or comments.

DaveA
 
N

Nik Gr

Στις 3/8/2010 10:39 πμ, ο/η Chris Rebert έγÏαψε:
That affects what encoding the text file comprising the source code
itself is in.

What does this practically mean? Perhaps you mean that it affects the
way this file will be stored in the hard disk?

For example is it different to say to Notapad++ to save it as 'Asci'i
and different to save it as 'UTF-8 without BOM'?

What should i use? My script only containes python code(english) and
greek chars inside print statemetns.
This tells Python what encoding the text file comprising the source
code itself is in.
What practically does this mean?

What difference does it have with (a) ?
This tells the web browser what encoding the HTML you're sending it is
in. Said HTML is output by your Python script and must match the
encoding you specify in (c).
When a python script runs it produces html output or only after the
python's output to the Web Server the html output is produced?
 
Î

Îίκος

a) a text editor takes keystrokes and cut/paste info and other data, and
produces a stream of (unicode) characters.  It then encodes each of  
those character into one or more bytes and saves it to a file.  You have
to tell Notepad++ how to do that encoding.  Note that unless it's saving
a BOM, there's no clue in the file what encoding it used.

So actually when i'm selecting an encoding from Notepad++'s options
iam basically telling the editor the way the it's suppose to store
those streams of characters to the hard disk drive.

Different encodings equals different ways of storting the data to the
media, correct?

b) The python compiler has to interpret the bytes it finds (spec. within
string literals and comments), and decode them into unicode for its own
work.  It uses the 'coding:' comment to decide how to do this.  But once
the file has been compiled, that comment is totally irrelevant, and ignored.

What is a "String Literal" ?

Basically if i understood you right, this line of code tells Python
the opposite thign from (a).
(a) told the editor how to store data to the media, while (b) tells
the python compiler how to retrive these data from the media(how to
read it, that is!) Right?

c1) Your python code has to decide how to encode its information when
writing to stdout.  There are several ways to accomplish that.

what other ways except the prin '''Content-Type blah blah... ''' ?

c2) The browser sees only what was sent to stdout, starting with the
"Content-Type..." line.  It uses that line to decide how to decode the
rest of the stream.  Let me reemphasize, the browser does not see any of
the python code, or comments.

I was under the impression the the stdout of a cgi python script was
the web server itself since this is the one app that awaits for the
data to be displayed.

When a python script runs it produces html output that time or only
after the
python's output to the Web Server the html output is produced?


And something else please.
My cgi python scripts contains english and greek letters, hence this
is an indication of tellign the editor to save the file to disk as
utf-8 right?

Well i told Notepad++ to save ti as Ascii and also removed the '# -*-
coding: utf-8 -*-' line.

and only used print ''' Content-Type: text/html; charset=UTF-8 /n'''

So, how the editor managed to save the file as ascii although my file
coaniens characters that are beyond the usual 7-bit ascci set?

and how could the python compiler 'read them and executed them' ?

I shoulds have saved in utf-8 and have inside the script the line so
the compiler knew to open it as utf-8. How come it dit work as ascii
both in stroing and retreiving!!
 
D

Dave Angel

¯º¿Â said:
So actually when i'm selecting an encoding from Notepad++'s options
iam basically telling the editor the way the it's suppose to store
those streams of characters to the hard disk drive.

Different encodings equals different ways of storting the data to the
media, correct?
Exactly. The file is a stream of bytes, and Unicode has more than 256
possible characters. Further, even the subset of characters that *do*
take one byte are different for different encodings. So you need to tell
the editor what encoding you want to use.
What is a "String Literal" ?
In python, a string literal is enclosed by single quotes, double quotes,
or triples.
myvar = u"tell me more"
myvar = u'hello world'
The u prefix is used in python 2.x to convert to Unicode; it's not
needed in 3.x and I forget which one you're using.

these are affected by the coding comment, but
myvar = myfile.readline()
is not.
Basically if i understood you right, this line of code tells Python
the opposite thign from (a).
(a) told the editor how to store data to the media, while (b) tells
the python compiler how to retrive these data from the media(how to
read it, that is!) Right?




what other ways except the prin '''Content-Type blah blah... ''' ?
You can use the write() method of sys.stdout, or various equivalents,
such as the one produced by io.open(). You can probably also use
fdopen(1, "w")

But probably the easiest is to do something like:
sys.stdout = codecs.getwriter('utf8')(sys.stdout)

and then print to stdout will use the utf8 encoding for its output.
I was under the impression the the stdout of a cgi python script was
the web server itself since this is the one app that awaits for the
data to be displayed.

When a python script runs it produces html output that time or only
after the
python's output to the Web Server the html output is produced?
I don't understand your wording. Certainly the server launches the
python script, and captures stdout. It then sends that stream of bytes
out over tcp/ip to the waiting browser. You ask when does it become html
? I don't think the question has meaning.
And something else please.
My cgi python scripts contains english and greek letters, hence this
is an indication of tellign the editor to save the file to disk as
utf-8 right?

Well i told Notepad++ to save ti as Ascii and also removed the '# -*-
coding: utf-8 -*-' line.

and only used print ''' Content-Type: text/html; charset=UTF-8 /n'''

So, how the editor managed to save the file as ascii although my file
coaniens characters that are beyond the usual 7-bit ascci set?
I don't know Notepad++, so I don't know how it handles a character
outside the legal ASCII range. So I'd only be guessing. But I'm guessing
it ignored the ASCII restriction, and just wrote the bottom 8 bits of
each character. That'll work for some of the non-ASCII characters.
and how could the python compiler 'read them and executed them' ?
I'd only be speculating, since I've seen only a few lines of your
source. Perhaps you're using Python 2.x, and not specifying u"" for
those literals, which is unreasonable, but does tend to work for *some*
of the second 128 characters.
I shoulds have saved in utf-8 and have inside the script the line so
the compiler knew to open it as utf-8. How come it dit work as ascii
both in stroing and retreiving!!

Since you have the setup that shows this effect, why not take a look at
the file, and see whether there are any non-ASCII characters (codes
above hex 7f) in it ? And whether there's a BOM. Then you can examine
the unicode characters produced. by changing your source code.

The more I think about it, the more I suspect your confusion comes
because maybe you're not using the u-prefix on your literals. That can
lead to some very subtle bugs, and code that works for a while, then
fails in inexplicable ways.

DaveA
 
Î

Îίκος

Exactly. The file is a stream of bytes, and Unicode has more than 256
possible characters. Further, even the subset of characters that *do*
take one byte are different for different encodings. So you need to tell
the editor what encoding you want to use.

For example an 'a' char in iso-8859-1 is stored different than an 'a'
char in iso-8859-7 and an 'a' char of utf-8 ?

In python, a string literal is enclosed by single quotes, double quotes,
or triples.
myvar = u"tell me more"
myvar = u'hello world'
The u prefix is used in python 2.x to convert to Unicode; it's not
needed in 3.x and I forget which one you're using.

I use Python 2.4 and never used the u prefix.

i Still don't understand the difference between a 'string' and a
'string literal'

If i save a file as iso-8859-1 but in some of my variabels i use greek
characters instead of telling the browser to change encoding and save
the file as utf-8 i can just use the u prefix like your examples to
save the variables as iso-8859-1 ?
I don't understand your wording. Certainly the server launches the
python script, and captures stdout. It then sends that stream of bytes
out over tcp/ip to the waiting browser. You ask when does it become html
? I don't think the question has meaning.

http cliens send request to http server(apache) , apache call python
interpreter python call mysql to handle SQL queries right?

My question is what is the difference of the python's script output
and the web server's output to the http client?

Who is producing the html code? the python output or the apache web
server after it receive the python's output?

The more I think about it, the more I suspect your confusion comes
because maybe you're not using the u-prefix on your literals. That can
lead to some very subtle bugs, and code that works for a while, then
fails in inexplicable ways.

I'm not sure whatr exaclty the do just yet.

For example if i say mymessage = "καλημέÏα" and the i say mymessage =
u"καλημέÏα" then the 1st one is a greek encoding variable while the
2nd its a utf-8 one?

So one script can be in some encoding and some parts of the script
like th2 2nd varible can be in another?

==============================
Also can you please help me in my cookie problem as to why only the
else block executed each time and never the if?

here is the code:

Code:
if os.environ.get('HTTP_COOKIE') and cookie.has_key('visitor') ==
'nikos':		#if visitor cookie exist
	print "ΑΠΟ ΤΗΠΕΠΟΜΕÎΗ ΕΠΙΣΚΕΨΗ ΣΟΥ ΘΑ ΣΕ ΥΠΟΛΟΓΙΖΩ ΩΣ ΕΠΙΣΚΕΠΤΗ
ΑΥΞΑÎΟÎΤΑΣ ΤΟΠΜΕΤΡΗΤΗ!"
	cookie['visitor'] = ( 'nikos', time() - 1 )		#this cookie will expire
now
else:
	print "ΑΠΟ ΔΩ ΚΑΙ ΣΤΟ ΕΞΗΣ ΔΕΠΣΕ ΕΙΔΑ, ΔΕΠΣΕ ΞΕΡΩ, ΔΕΠΣΕ ΑΚΟΥΣΑ!
ΘΑ ΕΙΣΑΙ ΠΛΕΟΠΟ ΑΟΡΑΤΟΣ ΕΠΙΣΚΕΠΤΗΣ!!"
	cookie['visitor'] = ( 'nikos', time() + 60*60*24*365 )		#this cookie
will expire in an year

How do i check if the cookie is set and why if set never gets unset?!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,007
Latest member
obedient dusk

Latest Threads

Top