473,729 Members | 2,340 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

create a web service for python application

5 New Member
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
13 3561
kudos
127 Recognized Expert New Member
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
9,735 Recognized Expert Moderator Expert
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
127 Recognized Expert New Member
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
susanne
5 New Member
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 misconfiguratio n 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
127 Recognized Expert New Member
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
susanne
5 New Member
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
127 Recognized Expert New Member
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
martinscott
1 New Member
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
127 Recognized Expert New Member
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

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

Similar topics

3
1309
by: google account | last post by:
Not really being a programmer, but thinking that there must be a better way than to do it by hand and havign a friend who likes to tell me that python is the answer to everything I am hoping. I have two NT4 domains, and I need to create instances of all the account names from one in the other. All accounts need to have identical group memberships to each other, and different passwords.
3
5216
by: David Fraser | last post by:
Hi We are trying to debug a problem with services created using py2exe. It seems that these problems have arisen after services were installed and removed a few times. OK, first the actual problem we're seeing. After compiling a service with py2exe, running "service -install" and attempting to start it from the Services dialog, it pops up the message "Windows could not start the Service on Local Computer. For more information,...
0
1512
by: Fritz Bosch | last post by:
We are in the process of refactoring our GUI-based test application for radio equipment and are rewriting a significant part in Python. The new architecture will substantially be based on the model-view-controller pattern, as follows: User Input | v +-------------+ service request service request +-------------+
11
1928
by: Mr. B | last post by:
I've an application in which I use to check out the date/time stamp of a data base... and if I find that it has been updated, my application runs and does a particular update. Currently I fire off my application hourly useing the built in XP Scheduler. What I am going to do is to have my application check every minute while it is running as I don't want to have to wait up to a hour for my particular update to happen....
6
3428
by: Laszlo Zsolt Nagy | last post by:
Sorry, I realized that the import zlib was not executed from my (working) service. So here is the question: why can't I use zlib from a win32 service? Is there any way to make it working? >------------- >Python could not import the service's module > File "T:\Python\Projects\NamedConnector\Service.py", line 17, in ? > from Processor import * > File "c:\Python\Projects\NamedConnector\Processor.py", line 35, in ?
3
14941
by: Amjad | last post by:
Hi, I just wrote a test Windows Service that creates a text file on startup (please see my code below). The file is never created. Protected Overrides Sub OnStart(ByVal args() As String) Dim swLog As StreamWriter = File.CreateText("C:\myLog.txt") swLog.WriteLine("My Windows Service has just started.") swLog.Close() : swLog.Flush() End Sub
7
2660
by: Laszlo Nagy | last post by:
Hello, I have a win32 service written in Python that starts a plain application, written in Python. The win32 service tries to launch the application in a while loop and logs the return value of the os.system call. That's all. The application is a simple Python program that connects to an https xml/rpc server, and works with the data retrieved from that server. It
2
2513
by: Peter | last post by:
Firstly let me be very clear about this, I do not want to create a web service proxy nor do I want to do anything with web services. Basically, I have a shrink wrapped desktop application which downloads data from a web site. Unfortunately the application has a fixed timeout and the web server regularly exceeds this, causing the application to shut the connection and subsequently not receive any data. The desktop application also uploads...
6
2805
by: Michael Tissington | last post by:
Using Visual Studio 2008 can someone point me to an example to create a cgi web service in C# ? Thanks.
0
9427
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9284
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9202
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9148
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8151
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4528
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4796
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3238
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2683
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.