我有一个pyramid / python应用程序,可以调用以下视图:
@view_config(route_name='home_page', renderer='templates/edit.pt')
def home_page(request):
if 'form.submitted' in request.params:
name= request.params['name']
input_file=request.POST['stl'].file
vertices, normals = [],[]
if input_file.read(5) == b'solid':
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]))
ordering=[]
N=len(normals)
for i in range(0,N):
ordering.append([3*i,3*i+1,3*i+2])
data=[vertices,ordering]
else:
f=input_file
points=[]
triangles=[]
normals=[]
def unpack (f, sig, l):
s = f.read (l)
fb.append(s)
return struct.unpack(sig, s)
def read_triangle(f):
n = unpack(f,"<3f", 12)
p1 = unpack(f,"<3f", 12)
p2 = unpack(f,"<3f", 12)
p3 = unpack(f,"<3f", 12)
b = unpack(f,"<h", 2)
normals.append(n)
l = len(points)
points.append(p1)
points.append(p2)
points.append(p3)
triangles.append((l, l+1, l+2))
#bytecount.append(b[0])
def read_length(f):
length = struct.unpack("@i", f.read(4))
return length[0]
def read_header(f):
f.seek(f.tell()+80)
read_header(f)
l = read_length(f)
try:
while True:
read_triangle(f)
#except Exception, e:
#print "Exception",e[0]
#write_as_ascii(outfilename)
data=[points,triangles]
jsdata=json.dumps(data)
renderer_dict = dict(name=name,data=jsdata)
path=shortuuid.uuid()
html_string = render('tutorial:templates/view.pt', renderer_dict, request=request)
s3=boto.connect_s3(aws_access_key_id = 'AKIAIJB6L7Q', aws_secret_access_key = 'sId01dYCMhl0wX' )
bucket=s3.get_bucket('cubes.supercuber.com')
k=Key(bucket)
k.key='%(path)s' % {'path':path}
k.set_contents_from_string(html_string, headers={'Content-Type': 'text/html'})
k.set_acl('public-read')
return HTTPFound(location="http://cubes.supercuber.com/%(path)s" % {'path':path})
return {}
如您所见,代码检查上载的stl文件是否为ascii(如果以“solid”开头)或二进制文件。如果它的ascii,一切正常,数据变量填充顶点和排序。但是,如果它不是以solid开头并且是二进制stl文件,则数据变量永远不会被填充。这是为什么?
答案 0 :(得分:1)
您读取前5个字节以检查文件类型,但从不将文件位置重置为开头。
致电.seek(0)
:
f=input_file
f.seek(0)
您可以随时寻求相对而无需致电f.tell()
:
f.seek(80, 1) # relative seek, you can use `os.SEEK_CUR` as well.