Note that there are some explanatory texts on larger screens.

plurals
  1. POCGI script is not executable
    primarykey
    data
    text
    <p>In one of my homework practices, I must start a webserver and when I access webserver's root, it executes a CGI script.</p> <p>But when I open localhost:8080, this error message appears:</p> <pre><code>Error code 403. Message: CGI script is not executable ('/cgi-bin/todolist.cgi'). Error code explanation: 403 = Request forbidden -- authorization will not help. </code></pre> <p>My server code:</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import getopt import logging import BaseHTTPServer from CGIHTTPServer import CGIHTTPRequestHandler import json from DBBackend import TodoDao # CRUD to REST conventions # POST Create # GET Retrieve # PUT Update # DELETE Delete """ API REST del servidor. GET /todos - Recupera la lista de tareas (ToDos) DELETE /todos/id - Elimina la tarea con el id especificado POST /todos - Añade una nueva tarea con los valores especificados como parámetros PUT /todos/id - Actualiza los valores espcificados en los parámetros para la tarea con el id dado Tanto los parámetros (en el cuerpo de la petición) como las respuestas son en formato JSON. """ logging.basicConfig(level=logging.DEBUG) class RESTHTTPRequestHandler(CGIHTTPRequestHandler): dao = TodoDao() res_string = dao.tableName res_path = "/" + res_string def _GET(self): if self.path == self.res_path: tasks = self.dao.findTasks() return {'code': 'ok', 'data': tasks} else: _,res,id = self.path.split("/") int(id) assert(res==self.res_string) data = self.dao.retrieveTask(id) return {'code': 'ok', 'data': data} def _POST(self): assert(self.path == self.res_path) if 'Content-length' in self.headers: data = json.loads(self.rfile.read(int(self.headers['Content-length']))) else: data = json.load(self.rfile) self.dao.createTask(data) return {'code': 'ok'} def _PUT(self): _,res,id = self.path.split("/") int(id) assert(res==self.res_string) if 'Content-length' in self.headers: data = json.loads(self.rfile.read(int(self.headers['Content-length']))) else: data = json.load(self.rfile) self.dao.updateTask(id, data) return {'code': 'ok'} def _DELETE(self): _,res,id = self.path.split("/") int(id) assert(res==self.res_string) self.dao.deleteTask(id) return {'code': 'ok'} def _send(self, data): response = json.dumps(data) self.send_response(200) self.send_header("Content-type", "application/json") self.send_header("Content-Length", len(response)) self.end_headers() self.wfile.write(response) # El BaseHTTPRequestHandler no está pensado para ésto :( def do_POST(self): self._reroute() def do_PUT(self): self._reroute() def do_GET(self): self._reroute() def do_DELETE(self): self._reroute() def _reroute(self): try: if self.path.startswith(self.res_path): method_name = '_' + self.command method = getattr(self, method_name) try: self._send(method()) except (ValueError, AssertionError): self.send_error(400, "Invalid request") except: logging.exception("Database access error") self.send_error(500, "DDBB error") else: if self.path == "/" or self.path == "/index.html": self.path = "/cgi-bin/todolist.cgi" method_name = 'do_' + self.command method = getattr(CGIHTTPRequestHandler, method_name) method(self) except AttributeError: self.send_error(501, "Unsupported method (%r)" % self.command) #---- Defaults port = "8080" basedir = "www/" #---- #---------------------------------------- def usage(): print "Uso: " + os.path.basename(sys.argv[0]) + " -h -p port" print " -h Muestra este mensaje" print " -p port Sirve en el puerto indicado (def={0})".format(port) print " -d dirname Sirve el contenido del directorio indicado (def={0})".format(basedir) #---------------------------------------- try: opts, args = getopt.getopt(sys.argv[1:], "hp:d:", ["help", "port=", "dir="]) except getopt.GetoptError: usage() sys.exit(2) for o, a in opts: if o in ("-h", "--help"): usage() sys.exit() if o in ("-p", "--port"): port = a if o in ("-d", "--dir"): basedir = a if (port == None): usage() sys.exit() try: address = ('', int(port)) except ValueError: usage() sys.exit(2) httpd = BaseHTTPServer.HTTPServer(address, RESTHTTPRequestHandler) os.chdir(basedir) httpd.serve_forever() </code></pre> <p>And my todolist.cgi:</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- import cgi import sys import os import datetime import locale # TBD: Usar el locale del cliente locale.setlocale(locale.LC_TIME,'') date_format = locale.nl_langinfo(locale.D_FMT) sys.path.append(os.path.join(os.path.dirname(__file__), "../..")) import DBBackend print "Content-Type: text/html" print "" print """ &lt;!doctype html&gt; &lt;html lang="es"&gt; &lt;head&gt; &lt;meta charset="utf-8"/&gt; &lt;title&gt;[IPM] Lista de tareas&lt;/title&gt; &lt;meta name="author" content="David Cabrero"/&gt; &lt;meta name="HandheldFriendly" content="true"/&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1,maximun-scale=1,user-scalable=no"/&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=ecdge,chrome=1"&gt; &lt;!--[if lt IE 9]&gt; &lt;script src="//html5shiv.googlecode.com/svn/trunk/html5.js"&gt;&lt;/script&gt; &lt;script src="http://css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js"&gt;&lt;/script&gt; &lt;![endif]--&gt; &lt;link rel="stylesheet" type="text/css" href="css/default.css" /&gt; &lt;link rel="stylesheet" type="text/css" href="css/wide-screen.css" media="only screen and (min-width : 1024px)" /&gt; &lt;script src="js/todolist.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;header&gt; &lt;h1&gt;ToDo&lt;/h1&gt; &lt;/header&gt; &lt;ul&gt; """ fname = os.path.join(os.getcwd(), "../", DBBackend.DATABASEFILENAME) li = """ &lt;a href="#dialog"&gt;&lt;li data-task-id="{0}"&gt; &lt;p class="desc"&gt;{1}&lt;/p&gt; &lt;time datetime="{2}"&gt;{3}&lt;/time&gt; &lt;p class="done" data-task-done="{4}"&gt;{5}&lt;/p&gt; &lt;/li&gt;&lt;/a&gt; """ for task in DBBackend.TodoDao(fname).findTasks(): id = str(task['id']) desc = task['desc'].encode('utf-8') deadline = datetime.datetime.strptime(task['deadline'], "%Y-%m-%d") done = task['done'] == 1 print li.format(id, desc, deadline.strftime("%Y-%m-%d"), deadline.strftime(date_format), "yes" if done else "no", "Hecho" if done else "Sin hacer") print """ &lt;/ul&gt; &lt;div id="updateTask" class="dialog"&gt;&lt;div&gt; &lt;h1&gt;Actualizar tarea&lt;/h1&gt; &lt;form&gt; &lt;p&gt;&lt;input type="text" name="task_desc" placeholder="task description" autofocus="autofocus" /&gt;&lt;/p&gt; &lt;p&gt;&lt;input type="date" name="task_deadline" placeholder="deadline" /&gt;&lt;/p&gt; &lt;p&gt;&lt;input type="checkbox" name="task_done" /&gt;&lt;/p&gt; &lt;p class="okCancel"&gt; &lt;button name="ok"&gt;OK&lt;/button&gt; &lt;button name="cancel"&gt;Cancel&lt;/button&gt; &lt;/p&gt; &lt;/form&gt; &lt;/div&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; """ print """ """ </code></pre> <p>All the code was given by teachers (I have to do a web application), so I don't know how to start if I cannot manage to get the server working. I'm also running Windows 7 and Python for Windows (Version 2.7), hope it helps!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload