我正在研究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从DB:http:///ZiHWiiwr中提取数据
请帮忙 ! 解决方法: 您正在使用length = int(env.get(‘CONTENT_LENGTH’,0))(forum.py:68)查询WSGI环境.我刚刚运行了一个示例WSGI服务器(取自python docs的示例代码),它根据请求输出所有可用的环境变量:
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.get(‘CONTENT_LENGTH’,0)查询env-dictionary,实际上找到了CONTENT_LENGTH-key,但它的值是一个空字符串 – 这就是get()方法返回”而不是指定的原因默认值0.
由于空字符串无法转换为int,因此您将获得ValueError.
尝试捕获异常,您的代码应该工作:
try:
length = int(env.get("CONTENT_LENGTH", 0))
except ValueError:
length = 0
来源:http://www./content-1-203701.html
|