3

I have never setup a server (let alone a python server) before and i am a bit lost. How do i utilize the following code? I have tried to put in in the cgi bin directory but that didnt work. It returned an internal server error. have a look at this here

#!/usr/bin/env python
#
# Funf: Open Sensing Framework
# Copyright (C) 2010-2011 Nadav Aharony, Wei Pan, Alex Pentland.
# Acknowledgments: Alan Gardner


from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from SocketServer import ThreadingMixIn
import sys
import cgi
import urlparse
import os.path
import shutil
import time

server_dir = os.path.dirname(__file__)

config_path = '/config'
config_file_path = os.path.join(server_dir, 'config.json')

upload_path = '/data'
upload_dir = os.path.join(server_dir, 'uploads')

def read_config():
    config = None
    try:
        with open(config_file_path) as config_file:
            config = config_file.read()
    except IOError:
        pass
    return config

def backup_file(filepath):
    shutil.move(filepath, filepath + '.' + str(int(time.time()*1000)) + '.bak')

def write_file(filename, file):
    if not os.path.exists(upload_dir):
        os.mkdir(upload_dir)
    filepath = os.path.join(upload_dir, filename)
    if os.path.exists(filepath):
        backup_file(filepath)
    with open(filepath, 'wb') as output_file:
        while True:
            chunk = file.read(1024)
            if not chunk:
                break
            output_file.write(chunk)

class RequestHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        parsed_url = urlparse.urlparse(self.path)
        if parsed_url.path == config_path:
            config = read_config()
            if config:
                self.send_response(200)
                self.end_headers()
                self.wfile.write(config)
            else:
                self.send_error(500)
        elif parsed_url.path == upload_path:
            self.send_error(405)
        else:
            self.send_error(404)

    def do_POST(self):
        parsed_url = urlparse.urlparse(self.path)
        path = parsed_url.path
        ctype, pdict = cgi.parse_header(self.headers['Content-Type']) 
        if path == upload_path:
            if ctype=='multipart/form-data':
                form = cgi.FieldStorage(self.rfile, self.headers, environ={'REQUEST_METHOD':'POST'})
                try:
                    fileitem = form["uploadedfile"]
                    if fileitem.file:
                        try:
                            write_file(fileitem.filename, fileitem.file)
                        except Exception as e:
                            print e
                            self.send_error(500)
                        else:
                            self.send_response(200)
                            self.end_headers()
                            self.wfile.write("OK")
                        return
                except KeyError:
                    pass
            # Bad request
            self.send_error(400)
        elif parsed_url.path == config_path:
            self.send_error(405)
        else:
            self.send_error(404)


class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    """Handle requests in a separate thread."""                


if __name__ == '__main__':
    if sys.argv[1:]:
        port = int(sys.argv[1])
    else:
        port = 8000
    server_address = ('', port)
    httpd = ThreadedHTTPServer(server_address, RequestHandler)

    sa = httpd.socket.getsockname()
    print "Serving HTTP on", sa[0], "port", sa[1], "..."
    print 'use <Ctrl-C> to stop'
    httpd.serve_forever()
2
  • 2
    You've got a long way to go, and this is not really a question. I would expect it to be closed shortly. Take a look at the funf docs. Take a look at python docs. Understand linux scripting.
    – brandeded
    Oct 28, 2011 at 12:41
  • 1
    In other words, jorrebor, you're asking how to drive a car, and showing us that you don't know what a car is. A CGI script generates output to standard out which is sent by your web server to you, as a web page. The above code creates a long lived daemon (server) process in python, and is not intended to be run in a CGI environment but rather as a standalone http server. CGI scripts do not contain an HTTP server service, but rather run inside another server (like Apache or IIS). I did not vote to close and do not recommend voting to close. I recommend trying to help this lost noob.
    – Warren P
    Oct 28, 2011 at 20:22

4 Answers 4

6

If you want to run a CGI on something like Apache (as opposed via custom server code like you pasted above), you can create a .py file like this in a (.py) CGI-enabled directory.

#!/usr/bin/env python
print "Content-Type: text/html"
print
print 'Hello World'

If you're using Apache, here's some info on how to set up CGI executables.

edit: (As Adrien P. says, the Python script should be made executable.)

1
  • This is a good answer showing a minimal hello world "cgi script" program. The sample code posted by the OP is not suitable for use as a CGI script. Step 1, set up your web server and make sure that Python is installed and available to CGI. See this link for some linux setup help: my.opera.com/NoteMe/blog/…
    – Warren P
    Oct 28, 2011 at 20:25
1

You do not have to place it into a cgi-bin directory.

If you are running windows, you can launch Idle from your start menu under the python entry. Paste the code in, and hit F5 to run the code.

If you are running *nix, look to Adrien's answer for the commands and copy what is output when you run ./your_script.py.

Are you attempting to program a website in Python? This is code to create a web server, not site, so navigating to the program in a web browser will yield no results.

-1
$ chmod +x your_script.py
$ ./your_script.py

A quick look a your code: it launch a simple http server who listen on port 8000

1
  • 1
    Ouch. So he wants to run a thing which is a daemon (service) as if it was a cgi page.
    – Warren P
    Oct 28, 2011 at 20:20
-1

Heroku is a good place to host and python scripts.

Pre-req

pythonscripts.py
procfile
requirements.txt

and After add, commit and push the scripts to heroku app. Just run the following command on terminal to run the scripts.

heroku run python your_scripts.py

More if you want to run this scripts on a schedule timing. then heroku provides lots of adds-on. just search it on heroku

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.