By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,222 Members | 2,416 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,222 IT Pros & Developers. It's quick & easy.

create a web service for python application

P: 5
Hi, I am very new to the python web applications. can some one help.
I have a python application with some functions in it.

1) The application reads an input file ( say, IN.txt).
the IN.txt file contains names of three other files( x.dat, y.txt, z.dat) that are
in the same directory.

2) then the application reads the data in the files x.dat, y.txt, z.dat and performs some calculations.

3) outputs the results in a file called out.txt

The application is running perfectly from command mode. I need to make it a web application so that it can be run in a browser from anywhere.
I tried with cherrypy and django tutorials, but could not succeed, as i am completely new to this field. can some one help with steps to proceed.

Your help is highly appreciated.
Thanks in advance!
Susanne
Jul 30 '09 #1
Share this Question
Share on Google+
13 Replies


kudos
Expert 100+
P: 126
It sound like what you need is a cgi-script. This is luckily quite simple.

here is a template:

Expand|Select|Wrap|Line Numbers
  1. #!/usr/bin/python
  2.  
  3. import os
  4. import cgi
  5.  
  6. print "Content-Type: text/plain\n\n"
  7.  
  8. # your script here...
  9. print "hi how are you!"
  10.  
Ofcourse there are some details:

1. the file should not have an .py extension, but rather a .cgi extension
2. the file should have the correct properties (i.e. chmod a+x <filename.cgi>)
3. it should be placed in a "cgi-bin" directory (under your www folder)
4. then you would access it like http://www.yourdomain.com/cgi-bin/yourpythonfile.cgi

(It sound like you were planning to do this in a unix enviroment)

There are multiple other options, but this one is quite simple.

-kudos
Jul 31 '09 #2

Frinavale
Expert Mod 5K+
P: 9,731
I'm just going to add a bit to Kudos's answer.

The output that your python script should produce should be HTML since it's going to be displayed in a web browser.

I would recommend keeping a clear separation between your current logic and the HTML or else it can get very messy to read.

Make a function that builds the HTML so that it's easier to understand what's going on.

For example:
Expand|Select|Wrap|Line Numbers
  1. #!/usr/bin/python
  2.  
  3. import os
  4. import cgi
  5.  
  6. def getfileoutput():
  7.   # This is where you grab the data from the files
  8.  
  9. def output(fileoutput = ""):
  10.    #This produces the HTML that is to be sent to the browser
  11.    htmlOutput = '<html>'
  12.    htmlOutput  += '   <head>'
  13.    htmlOutput  += '      <title></title>'
  14.    htmlOutput  += '   </head>'
  15.    htmlOutput  += '   <body>'
  16.    htmlOutput  += '      <div>'
  17.    htmlOutput  +=  fileoutput
  18.    htmlOutput  += '      </div>'
  19.    htmlOutput  += '   </body>'
  20.    htmlOutput += '</html>'
  21.    return htmlOutput
  22.  
  23. print output(getfileoutput())
Jul 31 '09 #3

kudos
Expert 100+
P: 126
That is very true! however do not forget this part:

Expand|Select|Wrap|Line Numbers
  1. print "Content-Type: text/plain\n\n"
  2.  
-kudos

@Frinavale
Jul 31 '09 #4

P: 5
Hi kudos and Frinavale,
Thanks a lot for your quick responses!
I did followed the steps as you suggested.

1) I inserted my complete python script in between line numbers 21 and 23 of Frinavale's code in the reply. after that i also inserted the "Content-Type" as Kudos suggested.

2) I renamed the file with .cgi extenstion.

3) I kept the .cgi file under the cgi-bin directory.
( Windows-XP/program files/apache 2.2/cgi-bin)

4) I copied the other files also to the same directory( In.txt, x.dat, y.txt, z.dat)
as the python script needed them.

when i executed the code in internet explorer or mozilla firefox

http://localhost/cgi-bin/hi.cgi
http://localhost:80/cgi-bin/hi.cgi

either I am getting
file not found error
OR
Internal Server Error: The server encountered an internal error or misconfiguration and was unable to complete your request.

When I check http://localhost:80 Then the server shows "It Is Working"

I am confused. Did I do some thing wrong with hte code. Or do I need to add anything else.

Please suggest me
Thanks
Susanne
Aug 1 '09 #5

kudos
Expert 100+
P: 126
Ok, I see there is an apache server on a windows platform. Then you would need to find out how (and if) it is configured for python and cgi. You would also need be sure that the various files (.cgi) and (cgi-bin) directory is have the correct access rights.

However, I have an alternative solution for you, python has a built in webserver!

Expand|Select|Wrap|Line Numbers
  1. from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
  2.  
  3. class myserver(BaseHTTPRequestHandler):
  4.  def do_GET(self):
  5.   self.send_response(200)
  6.   self.send_header("content-type","text/html")
  7.   self.end_headers()
  8.   self.wfile.write("your output as a html-string here...")
  9.   return
  10. try:
  11.  s = HTTPServer(('',2606),myserver)
  12.  s.serve_forever()
  13. except KeyboardInterrupt:
  14.  s.socket_close()
  15.  
Now, type http://localhost:2606 in your browser to see the webserver in action

-kudos


@susanne
Aug 1 '09 #6

P: 5
HI kudos, thanks a lot again for your help

I tried configuring apache server to be able to work with cgi as well.
And I tried with the built-in server script you have provided.

The server is running but i can see only
" your output as a html-string here..." in the browser.

I tried even this simple cgi script (hi.cgi) to execute
(http://localhost:2606/hi.cgi )
but i see only the same message as above.

#!/usr/bin/python
import os
import cgi
print "Content-Type: text/plain\n\n"
print "hello!"
Aug 1 '09 #7

kudos
Expert 100+
P: 126
Hi,
what you should do is the following:

place your program between :

Expand|Select|Wrap|Line Numbers
  1. self.end_headers()
  2. -- your program here ---
  3. return
  4.  
then use the following to output from your program:

Expand|Select|Wrap|Line Numbers
  1. self.wfile.write("your output as a html-string here...")
  2.  
I have created a simple example, that does something, and later puts it to the webbrowser

Expand|Select|Wrap|Line Numbers
  1. from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
  2.  
  3. class myserver(BaseHTTPRequestHandler):
  4.  def do_GET(self):
  5.   self.send_response(200)
  6.   self.send_header("content-type","text/html")
  7.   self.end_headers()
  8.  
  9.   # this code do 'something'
  10.  
  11.   html=""
  12.   for i in range(32):
  13.    html+="<tr>"
  14.    for j in range(32):
  15.     html+="<td bgcolor=\""+hex(int(((j^i) / 64.0)*256))+"\"></td>&nbsp;</td>"
  16.   html+="</tr>" 
  17.  
  18.   # writes all to string called html
  19.  
  20.   html = "<html></body><table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"100%\" height=\"100%\">" +html+"</table></body></html>" 
  21.  
  22.   # writes to the screen/webclient
  23.  
  24.   self.wfile.write(html)
  25.   return
  26.  
  27. try:
  28.  s = HTTPServer(('',2606),myserver)
  29.  s.serve_forever()
  30. except KeyboardInterrupt:
  31.  s.socket_close()
  32.  
Please note, this webserver doesn't have the features of a normal webserver, but is more intended to do the following:

1. do some kind of calculations (read files, add numbers etc, etc)
2. display it to a webbrowser (as a webserver)

(PS. to set ut apache for cgi-script, if I remeber correctly you would need to change something called scriptalias)

-kudos



@susanne
Aug 1 '09 #8

P: 1
I am reading in bytes from a hdd image (dd). I want to look for the header of a JPEG (FFD8 4a 46 49 46) and replace all the bytes before the footer (FFD9) with 0. My questions is: How can I make a change to the original file stream?
Aug 3 '09 #9

kudos
Expert 100+
P: 126
First, I happen to have done some jpeg work earlier, are you sure that your header is correct? (I thought it was a bit longer) anyway, here is some code to get you started:

Expand|Select|Wrap|Line Numbers
  1. import os
  2. import stat
  3. f = file('yourimage.jpg', 'rb')
  4.  
  5. pat = [0xFF,0xD8,0xff,0xe0,0x0,0x10,0x4a,0x46,0x49,0x46] # i thought that this was the pattern...
  6. pati = 0
  7.  
  8. s = os.stat('yourimage')
  9. size = s[stat.ST_SIZE]
  10. for i in range(size):
  11.  v = f.read(1)
  12.  if(pati > len(pat)):
  13.   if(v == pat[pati]):
  14.    pati+=1
  15.   else:
  16.    pati=0
  17.  else:
  18.   if(i < size - 2):
  19.    # write the 0's here or simillar (then you would need to write 'ab' instead above
  20.    pass
  21. f.close()
  22.  
-kudos


@martinscott
Aug 3 '09 #10

P: 5
hi Kudos,
I sorted out the problem with my apache server on windows. Finally the apache server is running with test cgi script. But my actual python application( now, cgi application) is still not running. Actually in the original application the input file is passed as an argument in the command line (c:/ python application.py input).
Is it the problem when i run cgi script in the browser without passing the argument??
Thank you.
Susanne
Aug 6 '09 #11

kudos
Expert 100+
P: 126
Yes, you would need give the script an argument. To do this, there are multiple options, I will show the cgi-variant. This mean that you would give the input as an argument from the webbrowser

For instance, normally you would do something like this:
Expand|Select|Wrap|Line Numbers
  1. c:/ python application.py input
  2.  
(right?)

what you want to do now is the following, is to type in the following into your webbrowser:

Expand|Select|Wrap|Line Numbers
  1. http://localhost/cgi-bin/application.cgi?myinput=input
  2.  
To read the input to this webservice (which by the way is myinput=input) you would need to add the following:

Expand|Select|Wrap|Line Numbers
  1. import cgi
  2. form = cgi.FieldStorage()
  3. input = form["myinput"]
  4.  
Ok?

-kudos





@susanne
Aug 7 '09 #12

P: 5
Hi Kudos,
Thanks a lot for all your help so far. I think the problem was with my .cgi file so far. So, I configured the apache so that it directly excuetes my python script(.py) from the brwoser.
http://localhost/cgi-bin/Main.py?myinput=input

however, the input (argument) is not read by the python script when i supplied the input file as shown in URL above. Probably because it is again cgi specific.
I placed this code inside my main python script
***********************
import cgi
form = cgi.FieldStorage()
input = form["myinput"]
*************************
any hint pls? thanks
Aug 11 '09 #13

kudos
Expert 100+
P: 126
The problem is :

Expand|Select|Wrap|Line Numbers
  1. input = form["myinput"] 
  2.  
it should rather be:

Expand|Select|Wrap|Line Numbers
  1. input = form["myinput"].value 
  2.  
-kudos


@susanne
Aug 12 '09 #14

Post your reply

Sign in to post your reply or Sign up for a free account.