gpt4 book ai didi

python - 将文件信息从 html 文件选择器输入传递给 python 和 bokeh

转载 作者:太空宇宙 更新时间:2023-11-04 14:29:48 25 4
gpt4 key购买 nike

我正在尝试创建一个简单的 Bokeh 服务器应用程序,允许用户从 <input type="file"> 加载文件文件选择按钮。然后,该应用程序将从用户选择的文件中绘制数据。下面的代码非常简单,我根本不知道如何将文件信息从文件选择器传递给python。我需要使用 python 来处理文件 I/O 而不是 html 或 javascript。

当我运行 bokeh serve --show example.py path/to/input_file 时,我可以让它正常工作在命令行,但我不希望用户每次都指定它。我需要他们能够单击按钮来“上传”文件。此应用程序在本地运行,因此不会上传到服务器或类似的东西。

有没有比<input type="file">更好的方法?

from bokeh.plotting import figure
from bokeh.layouts import layout
from bokeh.models import ColumnDataSource, Div
from bokeh.io import curdoc

desc = Div(text="""
<h1>A simple example</h1>
<input type="file">
<br />""", width=800)

# Create Column Data Source that will be used by the plot
source = ColumnDataSource(data=dict(x=[], y=[]))

p = figure(plot_height=550, plot_width=800, title="", toolbar_location='above')
p.line(x="x", y="y", source=source)

def update():
x_data,y_data = read_file_data(input_file_name) # function to read specific file type
source.data = dict(
x=x_data,
y=y_data,
)

sizing_mode = 'fixed' # 'scale_width' also looks nice with this example
l = layout([
[desc],
[p],
], sizing_mode=sizing_mode)

update()
curdoc().add_root(l)
curdoc().title = "Sample"

最佳答案

维护者说明:CoffeeScript 支持在 Bokeh 中已弃用,并将在 Bokeh 2.0 中完全删除。这个例子需要用 JavaScript 或 TypeScript 重写

截至 Bokeh 0.12.4 ,没有内置的文件选择器输入小部件。但是有可能 create new extensions to Bokeh与将 JS 事件连接到 Python 的内置小部件一样无缝工作。

下面的代码是一个非常粗略的模型实现,它包装了一个 <input type="file">将它连接到 Python 代码。此代码应与 Bokeh 一起使用 0.12.4和更新。

from bokeh.core.properties import String
from bokeh.io import curdoc
from bokeh.layouts import column
from bokeh.models import Button, LayoutDOM

IMPL = """
import * as p from "core/properties"
import {LayoutDOM, LayoutDOMView} from "models/layouts/layout_dom"

export class FileInputView extends LayoutDOMView
initialize: (options) ->
super(options)
input = document.createElement("input")
input.type = "file"
input.onchange = () =>
@model.value = input.value
@el.appendChild(input)

export class FileInput extends LayoutDOM
default_view: FileInputView
type: "FileInput"
@define {
value: [ p.String ]
}
"""

class FileInput(LayoutDOM):
__implementation__ = IMPL
value = String()

input = FileInput()

def upload():
print(input.value)
button = Button(label="Upload")
button.on_click(upload)

curdoc().add_root(column(input, button))

这将产生以下输出:

enter image description here

几乎肯定可以对此进行改进。 SO 并不是迭代和协作讨论的好地方,所以如果您对改进它有疑问,我建议 project Discourse list作为继续的最佳地点。

关于python - 将文件信息从 html 文件选择器输入传递给 python 和 bokeh,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39206400/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com