0

现在我有这个表格:

<form action="/store_stl_data" method="post" accept-charset="utf-8"
      enctype="multipart/form-data">

    <label for="stl">STL</label>
    <input id="stl" name="stl" type="file" value="" />

    <input type="submit" value="submit" />
</form>

然后在我的views.py我有

@view_config(route_name='store_stl_data', renderer='templates/edit')

def store_stl_data(request):
    input_file=request.POST['stl'].file
    i1, i2 = itertools.tee(input_file)
    vertices = [map(float, line.split()[1:4])
                for line in i1
                if line.lstrip().startswith('vertex')]

    normals = [map(float, line.split()[2:5])
                for line in i2
                if line.lstrip().startswith('facet')]

        ...(parsing data)...
    return data

下面的三行def store_stl_data(request):是我最不确定的。我从本教程中得到了它们。

我想要这样当人们上传文件时,整个store_stl_data函数运行并处理输入文件。

现在它给了我一个错误:

KeyError: "No key 'stl': Not a form request"

这也是我的路线,在__init__.py

from pyramid.config import Configurator
from sqlalchemy import engine_from_config

from .models import (
    DBSession,
    Base,
    )


def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.bind = engine
    config = Configurator(settings=settings)
    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_route('view_wiki', '/')
    config.add_route('view_page', '/{pagename}')
    config.add_route('add_page', '/add_page/{pagename}')
    config.add_route('edit_page', '/{pagename}/edit_page')
    config.scan()
    return config.make_wsgi_app()
4

1 回答 1

1

.file您从请求中获得的对象已经是一个打开的文件(类似)对象。

如果您仔细查看链接到的文档中的示例,它会使用上传的文件名创建一个文件,并使用上传的文件将数据写入该新文件。input_file永远不会在该代码中打开,只有output_file是(注意那里的不同变量名称)。

您也不需要关闭文件对象,因此with不需要。您的代码可以简化为:

def store_stl_data(request):
    input_file=request.POST['stl'].file
    i1, i2 = itertools.tee(input_file)
    vertices = [map(float, line.split()[1:4])
                for line in i1
                if line.lstrip().startswith('vertex')]

    normals = [map(float, line.split()[2:5])
                for line in i2
                if line.lstrip().startswith('facet')]

不过,我个人不会为此使用,您在构建顶点时itertools.tee将整个文件读入缓冲区。tee

相反,我会使用一个循环:

def store_stl_data(request):
    input_file=request.POST['stl'].file
    vertices, normals = [], []
    for line in input_file
        parts = line.split()
        if parts[0] == 'vertex':
            vertices.append(map(float, parts[1:4]))
        elif parts[0] == 'facet':
            normals.append(map(float, parts[2:5]))

现在一次只在内存中保存一行(加上顶点和法线结构)。

注意:如果您收到KeyError: No key '...': Not a form request错误消息,则视图没有收到HTTPPOST请求。请仔细检查您的表单方法设置为"POST"(大小写无关紧要)。

于 2013-01-17T15:11:55.783 回答