2016-01-06 17 views
5

Sto lavorando a un progetto online Udacity. Sto usando vagrant configurato da loro, per eseguire il server che contiene il Database. Sfortunatamente quando ho provato a dare la persistenza del codice, il server restituisce un errore ogni volta. Sono nuovo di Python quindi per favore perdona qualsiasi errore evidente.DB Pyscopg - Errore di aggiunta di persistenza al codice

Ecco l'errore:

Serving HTTP on port 8000... 
Traceback (most recent call last): 
    File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run 
    self.result = application(self.environ, self.start_response) 
    File "forum.py", line 95, in Dispatcher 
    return DISPATCH[page](env, resp) 
    File "forum.py", line 68, in Post 
    length = int(env.get('CONTENT_LENGTH', 0)) 
ValueError: invalid literal for int() with base 10: '' 
10.0.2.2 - - [06/Jan/2016 04:44:16] "GET /post HTTP/1.1" 500 59 
10.0.2.2 - - [06/Jan/2016 04:44:16] "GET /favicon.ico HTTP/1.1" 404 22 

E questo è il codice che ho cambiato in forumdb.py:

# 
# Database access functions for the web forum. 
# 

import psycopg2 

## Database connection 

def GetAllPosts(): 
    DB = psycopg2.connect("dbname=forum") 
    c = DB.cursor() 
    c.execute("SELECT time, content FROM posts ORDER BY time DESC") 
    posts = ({'content': str(row[1]), 'time': str(row[0])} 
      for row in c.fetchall()) 

    # This returns a dictionary -- returning just c.fetchall() will return a list of tuples 

    DB.close() 
    return posts 

def AddPost(content): 
    DB = psycopg2.connect("dbname=forum") 
    c = DB.cursor() 
    c.execute("INSERT INTO posts (content) values ('%s')" % content) 
    DB.commit() 
    DB.close() 

forum.py - questo file rende l'html portando i dati dal DB: http://pastebin.com/ZiHWiiwr

Si prega di aiuto!

risposta

2

Stai interrogare l'ambiente WSGI con length = int(env.get('CONTENT_LENGTH', 0)) (forum.py:68). Ho appena eseguito un server di esempio WSGI (codice esempio tratto dalla documentazione Python), il quale emette tutti l'ambiente-variabili disponibili su richiesta:

from wsgiref.util import setup_testing_defaults 
from wsgiref.simple_server import make_server 

# A relatively simple WSGI application. It's going to print out the 
# environment dictionary after being updated by setup_testing_defaults 
def simple_app(environ, start_response): 
    setup_testing_defaults(environ) 

    status = '200 OK' 
    headers = [('Content-type', 'text/plain')] 

    start_response(status, headers) 

    ret = ["%s: %s\n" % (key, value) 
      for key, value in environ.iteritems()] 
    return ret 

httpd = make_server('', 8000, simple_app) 
print "Serving on port 8000..." 
httpd.serve_forever() 

L'uscita sto ottenendo quando interrogare il test-server è (tra molte altre variabili):

SERVER_PORT: 8000 
CONTENT_LENGTH: 
GLADE_CATALOG_PATH: : 

La variabile CONTENT_LENGTH è vuota. Questo sembra essere il caso anche nella tua applicazione.

Se l'ENV-dizionario è ora interrogato con env.get('CONTENT_LENGTH', 0), Il CONTENT_LENGTH-key è effettivamente trovato, ma il suo valore è una stringa vuota - è per questo che il metodo get() restituisce '' e non il tuo valore predefinito specificato 0.

Poiché una stringa vuota non può essere convertita in un int, si ottiene l'errore ValueError.

Prova cattura l'eccezione e il codice dovrebbe funzionare:

try: 
    length = int(env.get("CONTENT_LENGTH", 0)) 
except ValueError: 
    length = 0 
+0

Grazie per la spiegazione! Errore amatoriale .. Ma grazie ancora una volta! –

2

vostro errore corrente sta accadendo a causa della linea

length = int(env.get('CONTENT_LENGTH', 0)) 

in forum.py. Fondamentalmente esiste la chiave CONTENT_LENGTH ed è una stringa vuota e una stringa vuota non può essere convertita in una int. Modificare questa linea di

length = int(env.get('CONTENT_LENGTH')) if env.get('CONTENT_LENGTH') else 0 

Dal momento che siete nuovi a Python ci sono un paio di cose che dovreste sapere sulla linea modificata In primo luogo è conosciuto come un conditional expression, secondo stringhe vuote in Python sono hanno un valore booleano di False così quando

  • env.get ('CONTENT_LENGTH') restituisce una stringa vuota poi la lunghezza è assegnato 0
  • env.get ('CONTENT_LENGTH') restituisce una stringa non vuota oppure un numero intero allora int converte tale valore per è la rappresentazione intera
  • env.get ('CONTENT_LENGTH') restituisce un 0 (che ha un valore booleano false), allora viene assegnato 0