472,125 Members | 1,523 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

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

CGI Proplem displaying image

Hi,
Maybe someone of you can help me.

I'm trying to display an image in memory(open file) with an cgi script
- but it want work proberly:

I'm running an Cgi webserver (CgiServerGui.py).

both files are in the /cgi/ folder

#################
#my CGISRIPT: test.py

#! /usr/bin/env python

print ("Content-type: image/jpeg");
print # End of headers!

filename="cgi-bin//dog.jpg"
infile = open(filename, 'rb')
doginmemory=infile.read()
print doginmemory

##################

#################
#my html page with the image tag

<html>
<head>
</head>
<body>
<img type="image" src="/cgi-bin/test.py" height="25" width="111">
</body>
</html>

################
I can't figure out whats the problem.

funny: if I use a form with an method='post' I can get the picture
show up in a whole webpage ( method='get' will not work)

###########
<html>
<head>
</head>
<body>
<form name="test" method="post" action="/cgi-bin/test.py">
<input type="submit" value="go">
</body>
</html>
############
Any suggestion: (by the way: in the end the whole pictures should be
stored in an sqlite database and also retrieved from it to be
displayed within an html page.
Thanks Matthias
Jul 18 '05 #1
9 9294
Hello,

The HTTP header needs two newlines: one is provided by the "print"
statement but the other one shall be given by the string. Without the
second newline, the server returns an error 500 "Internal Error".

Karl

matthiasjanes wrote:
Hi,
Maybe someone of you can help me.

I'm trying to display an image in memory(open file) with an cgi script
- but it want work proberly:

I'm running an Cgi webserver (CgiServerGui.py).

both files are in the /cgi/ folder

#################
#my CGISRIPT: test.py

#! /usr/bin/env python

print ("Content-type: image/jpeg");
print # End of headers!

filename="cgi-bin//dog.jpg"
infile = open(filename, 'rb')
doginmemory=infile.read()
print doginmemory

##################

#################
#my html page with the image tag

<html>
<head>
</head>
<body>
<img type="image" src="/cgi-bin/test.py" height="25" width="111">
</body>
</html>

################
I can't figure out whats the problem.

funny: if I use a form with an method='post' I can get the picture
show up in a whole webpage ( method='get' will not work)

###########
<html>
<head>
</head>
<body>
<form name="test" method="post" action="/cgi-bin/test.py">
<input type="submit" value="go">
</body>
</html>
############
Any suggestion: (by the way: in the end the whole pictures should be
stored in an sqlite database and also retrieved from it to be
displayed within an html page.
Thanks Matthias

Jul 18 '05 #2
ma***********@gmx.net (matthiasjanes) wrote in message news:<d5*************************@posting.google.c om>...
Hi,
Maybe someone of you can help me.

I'm trying to display an image in memory(open file) with an cgi script
- but it want work proberly:

I'm running an Cgi webserver (CgiServerGui.py).

both files are in the /cgi/ folder

#################
#my CGISRIPT: test.py

#! /usr/bin/env python

print ("Content-type: image/jpeg");
print # End of headers!

filename="cgi-bin//dog.jpg"
infile = open(filename, 'rb')
doginmemory=infile.read()
print doginmemory

##################


Use sys.stdout for output in CGI scripts.
Escpecially with binary files.
Try this and see if the problem goes away

#################
#my CGISRIPT: test.py

#! /usr/bin/env python

import sys
sys.stdout("Content-type: image/jpeg\n\n")

filename="cgi-bin/dog.jpg"
img = open(filename, 'rb').read()
sys.stdout.write(img)

##################

Remember Google is your friend
http://starship.python.net/crew/davem/cgifaq/faqw.cgi

waldek
Jul 18 '05 #3
>
Use sys.stdout for output in CGI scripts.
Escpecially with binary files.
Try this and see if the problem goes away

#################
#my CGISRIPT: test.py

#! /usr/bin/env python

import sys
sys.stdout("Content-type: image/jpeg\n\n")

filename="cgi-bin/dog.jpg"
img = open(filename, 'rb').read()
sys.stdout.write(img)

##################

Remember Google is your friend
http://starship.python.net/crew/davem/cgifaq/faqw.cgi

waldek

Thanks to both of you,

Maybe my question was not clear enough: It is for me not a problem to
print the Image to screen. (As I said in the beginning) if I use a
form with methodes=post

example:

____THIS WORKS FINE AND DISPLAYS ON ONE PAGE THE IMAGE AND ONLY THE
IMAGE_______

#################
#my CGISRIPT: test.py

#! /usr/bin/env python

print ("Content-type: image/jpeg");
print # End of headers!

filename="cgi-bin//dog.jpg"
infile = open(filename, 'rb')
doginmemory=infile.read()
print doginmemory

##################

#################
#my html page with the image tag

<html>
<head>
</head>
<body>
<form name="test" method="post" action="/cgi-bin/test.py"
target="_blank">
<input type="submit" name="GO"> </form>
</body>
</html>
################
____THIS WORKS FINE AND DISPLAYS ON ONE PAGE THE IMAGE AND ONLY THE
IMAGE_______

BUT What I want is that I display the image on an HTML page with text
together.
tables and .......

something like that

#################
#my html page with the image tag

<html>
<head>
</head>
<body>

Some Text
<img type="image" src="/cgi-bin/test.py" height="25" width="111">

some Text
</body>
</html>

################
A working example code - even very small one would be appreciated

Matthias Janes
Jul 18 '05 #4
ma***********@gmx.net (matthiasjanes) wrote in message news:<d5**************************@posting.google. com>...

Use sys.stdout for output in CGI scripts.
Escpecially with binary files.
Try this and see if the problem goes away

#################
#my CGISRIPT: test.py

#! /usr/bin/env python

import sys
sys.stdout("Content-type: image/jpeg\n\n")

filename="cgi-bin/dog.jpg"
img = open(filename, 'rb').read()
sys.stdout.write(img)

##################

Remember Google is your friend
http://starship.python.net/crew/davem/cgifaq/faqw.cgi

waldek


Maybe my question was not clear enough: It is for me not a problem to
print the Image to screen. (As I said in the beginning) if I use a
form with method='post'

example:

____THIS WORKS FINE AND DISPLAYS ON ONE PAGE THE IMAGE AND ONLY THE IMAGE_______

#################
#my CGISRIPT: test.py

#! /usr/bin/env python

print ("Content-type: image/jpeg");
print # End of headers!

filename="cgi-bin//dog.jpg"
infile = open(filename, 'rb')
doginmemory=infile.read()
print doginmemory

##################

#################
#my html page with the image tag

<html>
<head>
</head>
<body>
<form name="test" method="post" action="/cgi-bin/test.py" target="_blank">
<input type="submit" name="GO"> </form>
</body>
</html>
################
____THIS WORKS FINE AND DISPLAYS ON ONE PAGE THE IMAGE AND ONLY THE IMAGE_______

BUT What I want is that I display the image on an HTML page with text
together.
tables and .......

something like that

#################
#my html page with the image tag

<html>
<head>
</head>
<body>

Some Text
<img type="image" src="/cgi-bin/test.py" height="25" width="111">

some Text
</body>
</html>

################
A working example code - even very small one would be appreciated

Matthias Janes
Jul 18 '05 #5
ma***********@gmx.net (matthiasjanes) wrote in
news:d5**************************@posting.google.c om:
Some Text
<img type="image" src="/cgi-bin/test.py" height="25" width="111">


You are trying to mix HTML and the output of a Python script. That
won't work.
You'll have to use SSI (server side includes) to do this. With SSI you
could run a script from within a HTML page and print the output of the
script in that page.
Another solution: use a CGI-script and let that script generate the
whole HTML page.
Perhaps this would help to get you starting:
http://www.python.org/topics/web/

Matthias
Jul 18 '05 #6
"matthiasjanes" <ma***********@gmx.net> wrote in message news:d5**************************@posting.google.c om...
ma***********@gmx.net (matthiasjanes) wrote in message
news:<d5**************************@posting.google. com>...

BUT What I want is that I display the image on an HTML page with text
together.

You should have a script (if you don't want to have two different scripts),
which would return an image or a page depending on its parameters,
something like http://your.site.net/cgi-bin/witty_page.py?action=page to return
"""
....... Content-type: plain/text\n\n
.......<img src="witty_page.py?action=image">
.......
"""
and http://your.site.net/cgi-bin/witty_page.py?action=image to return a picture.

As an example, please have my counter script. It can return either a picture,
or a page: a 1x1 pix. picture when counting pages (...?site=999&actn=incr)
or an html page with the visitors list (...?site=999&actn=list).

Regards, Georgy

#!C:\Apps\Python\python.exe

import sys, os

def read_counter( file_name ):
counter = "0"
if os.access( file_name, os.R_OK|os.W_OK ):
f = open( file_name, "rt" )
if f:
counter = f.read().strip()
if counter == '': counter = "0"
f.close()
return counter

def write_counter( file_name, counter ):
f = open( file_name, "wt" )
if f:
f.write( counter )
f.close()

file_cnt = "counter/c_nn_%04d.dat" # i.e. in cgi-bin/counter/
file_ips = "counter/c_ip_%04d.dat"
file_dsc = "counter/c_descr.dat"

def show_list( site, name ):
file_cnt_name = file_cnt % site
file_ips_name = file_ips % site

counter = read_counter( file_cnt_name )

f = open( file_ips_name, "rt" )
if not f:
raise ValueError

lines = f.readlines()
f.close()

style = "<style>td { padding: 1px 6px 1px 6px; text-align: left; }</style>"
title = "<title>Visits to %s</title>" % name

sys.stdout.write( "Content-type: text/html\n\n" ) # yield html

sys.stdout.write( "<html><head>%s%s</head>" % (style,title) )
sys.stdout.write( "<body>%s visits to <b>%s</b>"
"<p><table border=1 cellspacing=0>\n" % (counter,name) )
sys.stdout.write( "<tr bgcolor='#C0FFFF'><td>%s</td><td>%s</td><td>%s</td></tr>\n"
% ('Date','Time','IP') )
try:
gray = False
for ln in lines:
ln = ln.strip()
if not ln:
continue
dt,tm,ip = ln.split()
if ip == '217.77.77.77': ip = 'my friend 1'
elif ip == '218.88.88.88': ip = 'my friend 2'
if gray: bg = "#E0E0E0"
else: bg = "#FFFFFF"
gray = not gray
sys.stdout.write( "<tr bgcolor='%s'><td>%s</td><td>%s</td><td>%s</td></tr>\n"
% ( bg,dt,tm,ip ) )
except Exception,e:
sys.stdout.write( "<font color=red>%s</font>" % e )

sys.stdout.write( "</body></html>" )
sys.stdout.close()

def do_count( site ): # returns image

file_cnt_name = file_cnt % site
file_ips_name = file_ips % site

counter = read_counter( file_cnt_name )

counter = str(int(counter)+1)
write_counter( file_cnt_name, counter )

import datetime
dt = str(datetime.datetime.now())[:-7]

ip = os.environ.get("REMOTE_ADDR",'?')

f = open( file_ips_name, "at" )
if f:
f.write( "%s %s\n" % (dt,ip) )
f.close()

return_image()

def return_image():
# 1x1 black pixel
data = ('GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00'
'\xFF\xFF\xFF\x21\xF9\x04\x00\x00\x00\x00\x00'
'\x2C\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x03\ x44\x01\x00\x3B')

sys.stdout.write( "Content-type: image/gif\n\n" )
sys.stdout.write( data )
sys.stdout.close()

def read_descriptions( filename ):
dict = {}
for line in file( filename ):
if not line or line[0]=='#': # ignore empty and comment lines
continue
fields = line.split()
if len(fields) < 2:
continue
num, title = fields[:2]
dict[int(num)] = title
return dict

sites = read_descriptions( file_dsc )

# now we accept:
# site=sitenumber (all digits)
# actn=list|incr

# How to insert a counter into your page:
# <img src="http://my.site.org/cgi-bin/counter.py?site=99&actn=incr"
# border=0 width=1 height=1 alt=''>

def processing():
try:
if os.environ.has_key('QUERY_STRING'):
query = os.environ['QUERY_STRING']
import parsequery
query = parsequery.parsequery( query ) # get dictionary
if 'site' in query and 'actn' in query:
site = query['site']
actn = query['actn']
site = int(site)
if site in sites:
if actn == 'list':
show_list( site, sites[site] )
return
if actn == 'incr':
do_count( site )
return
except:
pass
# all bad cases -- just return a picture
return_image()

processing() # used to allow return from the middle

# EOF
Jul 18 '05 #7
> >
BUT What I want is that I display the image on an HTML page with text
together.

You should have a script (if you don't want to have two different scripts),
which would return an image or a page depending on its parameters,
something like http://your.site.net/cgi-bin/witty_page.py?action=page to return
"""
...... Content-type: plain/text\n\n
......<img src="witty_page.py?action=image">
......
"""
and http://your.site.net/cgi-bin/witty_page.py?action=image to return a picture.


sys.stdout.write( "Content-type: text/html\n\n" ) # yield html

sys.stdout.write( "<html><head>%s%s</head>" % (style,title) )
sys.stdout.write( "<body>%s visits to <b>%s</b>"
"<p><table border=1 cellspacing=0>\n" % (counter,name) )
sys.stdout.write( "<tr bgcolor='#C0FFFF'><td>%s</td><td>%s</td><td>%s</td></tr>\n"
% ('Date','Time','IP') )


Thanks:

does anyone knows if the CGIHTTPServer.py module can handle this kind of requests.

Do I have to use the 'sys.stdout.write( something )'

or is it also good enough to use 'print (something)'

regards

Matthias Janes
Jul 18 '05 #8

"matthiasjanes" <ma***********@gmx.net> wrote in message news:d5**************************@posting.google.c om...

| Do I have to use the 'sys.stdout.write( something )'
|
| or is it also good enough to use 'print (something)'

Yes, "print something" will be quite safe here, although 'print' adds a newline mark
or a blank (if you end 'print' with a comma) to the output and sometimes it can show
on the generated pages. But if you used 'print' for making binary files e.g. images,
that could ruin the output, so it's usually easier to use sys.stdout.write and not to
think about this problem. Please note also, that on Windows, both of the ways can
translate '\n' into '\r\n' so it may be necessary to switch stdout to binary mode, with
this code, for example:
try:
import msvcrt,os
msvcrt.setmode( 1, os.O_BINARY ) # 1 = stdout; use 0 for stdin
except ImportError:
pass

Georgy
Jul 18 '05 #9
"Georgy" <no*****@available.net> wrote in message news:<Ny********************@twister.southeast.rr. com>...
"matthiasjanes" <ma***********@gmx.net> wrote in message news:d5**************************@posting.google.c om...

| Do I have to use the 'sys.stdout.write( something )'
|
| or is it also good enough to use 'print (something)'

Yes, "print something" will be quite safe here, although 'print' adds a newline mark
or a blank (if you end 'print' with a comma) to the output and sometimes it can show
on the generated pages. But if you used 'print' for making binary files e.g. images,
that could ruin the output, so it's usually easier to use sys.stdout.write and not to
think about this problem. Please note also, that on Windows, both of the ways can
translate '\n' into '\r\n' so it may be necessary to switch stdout to binary mode, with
this code, for example:
try:
import msvcrt,os
msvcrt.setmode( 1, os.O_BINARY ) # 1 = stdout; use 0 for stdin
except ImportError:
pass

Georgy

thanks to everyone so far.

Matthias Janes
Jul 18 '05 #10

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

4 posts views Thread by Gregory | last post: by
5 posts views Thread by ljuljacka | last post: by
4 posts views Thread by redpears007 | last post: by

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.