1

Is there any way to get a twisted webserver to execute a python file like cgi on a conventional webserver? So, when i navigated to a directory, i could execute python within a seperate file?

I have created a basic webserver, but it only returns static content like text or HTML files:

from twisted.web.server import Site
from twisted.web.static import File
from twisted.internet import reactor

resource = File('/root')
factory = Site(resource)
reactor.listenTCP(80, factory)
reactor.run()

I understand why it may not be possible, but i couldn't find any documentation. Thanks

EDIT: I found a solution. Instead of going through the hassle of directories, i'm simply parsing GET requests and treating them like fake files. The CGI is executed within the main file.

THanks

2 Answers2

2

Found this example that might do what you want.

Take a look Twisted Web Docs for some more info. Search the page for CGI.

from twisted.internet import reactor
from twisted.web import static, server, twcgi

root = static.File("/root")
root.putChild("cgi-bin", twcgi.CGIDirectory("/var/www/cgi-bin"))
reactor.listenTCP(80, server.Site(root))
reactor.run()
Alex
  • 1,993
  • 1
  • 15
  • 25
  • This works, though it's probably not the best idea (you'd have to run it as root to bind to port 80 and on Linux, and a number of other Unix like systems, such as FreeBSD, you'd be serving up the */root/* (the 'root' user's home) directory. – Jim Dennis Apr 26 '13 at 05:51
  • This worked for me. The import part of this solution is the root.putChild("cgi-bin", twcgi.CGIDirectory("/var/www/cgi-bin")) line. The rest of it might need tweaking, and you might want to use alternate directory names / paths.The concept is spot on though. – BuvinJ Oct 09 '15 at 21:05
  • The link is broken – Sonu Mishra Aug 23 '16 at 23:09
  • @SonuMishra fixed the link – Alex Sep 20 '16 at 19:24
0

You would typically use the Twisted WSGI server for that.

http://twistedmatrix.com/documents/12.3.0/web/howto/web-in-60/wsgi.html

It doesn't exactly execute the Python file, but calls an "application". But that's better since it doesn't have to start a new Python process.

You can also use the twisted CGI support, which will execute the file, but using Twisted to run Python scripts with CGI is a bit like using a sports car as a tractor.

Lennart Regebro
  • 167,292
  • 41
  • 224
  • 251