5

我正在从事Udacity的在线项目。我正在使用vagrant他们配置的来运行包含数据库的服务器。不幸的是,当我试图让代码持久化时,服务器每次都返回一个错误。我是python新手,所以请原谅任何明显的错误。

这是错误:

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

这是我在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 - 此文件呈现从数据库中获取数据的 html:http: //pastebin.com/ZiHWiiwr

请帮忙 !

4

2 回答 2

2

由于该行,您当前的错误正在发生

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

在forum.py中。基本上密钥CONTENT_LENGTH存在并且它是一个空字符串并且空字符串不能转换为int。将该行更改为

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

由于您是 Python 新手,因此您应该了解修改后的行首先它被称为条件表达式,Python 中的第二个空字符串具有布尔值 False 所以当

  • env.get('CONTENT_LENGTH') 返回一个空字符串,然后将长度分配为 0
  • env.get('CONTENT_LENGTH') 返回一个非空字符串或一个整数,然后int将该值转换为它的整数表示
  • env.get('CONTENT_LENGTH') 返回一个 0(其布尔值为 false),然后分配 0
于 2016-01-11T18:49:13.837 回答
2

您正在使用length = int(env.get('CONTENT_LENGTH', 0))(forum.py:68) 查询 WSGI 环境。我刚刚运行了一个示例 WSGI 服务器(示例代码取自 python 文档),它根据请求输出所有可用的环境变量:

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()

我在查询测试服务器时得到的输出是(在许多其他变量中):

SERVER_PORT: 8000
CONTENT_LENGTH: 
GLADE_CATALOG_PATH: :

您会看到 CONTENT_LENGTH 变量为空。在您的应用程序中似乎也是如此。

如果现在使用 查询 env-dictionary env.get('CONTENT_LENGTH', 0)CONTENT_LENGTH-key则实际找到了,但它的值是一个空字符串 - 这就是 get() 方法返回 '' 而不是您指定的默认值 0 的原因。

由于无法将空字符串转换为 int,因此您将收到 ValueError。

尝试捕获异常,您的代码应该可以工作:

try:
    length = int(env.get("CONTENT_LENGTH", 0))
except ValueError:
    length = 0
于 2016-01-11T18:58:19.840 回答