Pyscopg DB - 错误为代码添加持久性

Abh*_*osh 5 python psycopg2 python-db-api

我正在研究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
Run Code Online (Sandbox Code Playgroud)

这是我在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()
Run Code Online (Sandbox Code Playgroud)

forum.py - 此文件呈现html从数据库中提取数据:http://pastebin.com/ZiHWiiwr

请帮忙 !

and*_*ann 2

您正在使用 (forum.py:68) 查询 WSGI 环境length = int(env.get('CONTENT_LENGTH', 0))。我刚刚运行了一个示例 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()
Run Code Online (Sandbox Code Playgroud)

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

SERVER_PORT: 8000
CONTENT_LENGTH: 
GLADE_CATALOG_PATH: :
Run Code Online (Sandbox Code Playgroud)

您会看到 CONTENT_LENGTH 变量为空。您的应用程序中似乎也是这种情况。

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

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

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

try:
    length = int(env.get("CONTENT_LENGTH", 0))
except ValueError:
    length = 0
Run Code Online (Sandbox Code Playgroud)