0

我正在尝试将 ezdxf 实现到 Flask Web-App 中,我试图在其中呈现文件并将其作为下载提供。

没有数据库可以吗?(如果没有,我怎样才能将 saveas 函数的文件目录更改为 Web 数据库?)

谢谢简

4

2 回答 2

0

您可以通过write方法将 DXF 文件写入文本流,因此可以使用StringIO对象将其写入字符串。StringIO.getvalue()返回一个 unicode 字符串,如果您的应用需要二进制编码的数据,则必须使用正确的编码将其编码为二进制字符串。

DXF R2007 (AC1021) 及更高版本的文本编码始终'utf8'为 ,对于较旧的 DXF 版本,所需的编码存储在Drawing.encoding.

import io
import ezdxf

def to_binary_data(doc):
    stream = io.StringIO()
    doc.write(stream)
    dxf_data = stream.getvalue()
    stream.close()
    enc = 'utf-8' if doc.dxfversion >= 'AC1021' else doc.encoding
    return dxf_data.encode(enc)

doc = ezdxf.new()
binary_data = to_binary_data(doc)
于 2019-12-17T06:05:00.793 回答
0

您的代码的一些更多信息和示例将有所帮助。您可以使用 html A 元素使用户能够从浏览器下载文件。您必须将 A 元素的“href”属性链接为 dxf 文件的内容。

以下是如何使用 ezdxf 信息执行此操作的示例,同样基于上述 Mozman 的信息:

# Export file as string data so it can be transfered to the browser html A element href:
# Create a string io object: An in-memory stream for text I/O
stream_obj = io.StringIO()
# write the doc (ie the dxf file) to the doc stream object
doc.write(stream_obj)
# get the stream object values which returns a string
dxf_text_string = stream_obj.getvalue()
# close stream object as required by good practice
stream_obj.close()

file_data = "data:text/csv;charset=utf-8," + dxf_text_string

然后将“file_data”分配给 href 属性。我使用 Dash - Plotly 回调,如果你愿意,我可以为你提供如何做到这一点的代码。

或者您也可以在烧瓶路由中使用 flask.send_file 函数。这要求数据为二进制格式。

# The following code is within a flask routing 
# Create a BytesIO object
 mem = io.BytesIO()
 # Get the stringIO values as string, encode it to utf-8 and write it to the bytes object
# Create a string io object: An in-memory stream for text I/O
stream_obj = io.StringIO()
# write the doc (ie the dxf file) to the doc stream object
doc.write(stream_obj)
# The bytes object file type object is what is required for the flask.send_file method to work
 mem.write(stream_obj.getvalue().encode('utf-8'))
 mem.seek(0)
 # Close StringIO object
 stream_obj.close()

 return flask.send_file(
     mem,
     mimetype='text/csv',
     attachment_filename='drawing.dxf',
     as_attachment=True,
     cache_timeout=0
 )

如果您愿意,我可以为您提供更多信息,但您可能需要提供一些代码结构,以了解您是如何编码和传递数据的。谢谢JF

于 2020-01-30T02:49:53.697 回答