licenses
sequencelengths 1
3
| version
stringclasses 677
values | tree_hash
stringlengths 40
40
| path
stringclasses 1
value | type
stringclasses 2
values | size
stringlengths 2
8
| text
stringlengths 25
67.1M
| package_name
stringlengths 2
41
| repo
stringlengths 33
86
|
---|---|---|---|---|---|---|---|---|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 448 | function process_reload_hash(request::HTTP.Request, state::HandlerState)
reload_tuple = (
reloadHash = state.reload.hash,
hard = state.reload.hard,
packages = keys(state.cache.resources.files),
files = state.reload.changed_assets
)
state.reload.hard = false
state.reload.changed_assets = []
return HTTP.Response(200, ["Content-Type" => "application/json"], body = JSON3.write(reload_tuple))
end
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 1427 | function process_resource(request::HTTP.Request, state::HandlerState; namespace::AbstractString, path::AbstractString)
(relative_path, is_fp) = parse_fingerprint_path(path)
registered_files = state.cache.resources.files
if !haskey(registered_files, namespace)
#TODO Exception like in python
return HTTP.Response(404)
end
namespace_files = registered_files[namespace]
if !in(relative_path, namespace_files.files)
#TODO Exception like in python
return HTTP.Response(404)
end
filepath = joinpath(namespace_files.base_path, relative_path)
try
headers = Pair{String,String}[]
file_contents = read(joinpath(namespace_files.base_path, relative_path))
mimetype = mime_by_path(relative_path)
!isnothing(mimetype) && push!(headers, "Content-Type" => mimetype)
if is_fp
push!(headers,
"Cache-Control" => "public, max-age=31536000" # 1 year
)
else
etag = bytes2hex(MD5.md5(file_contents))
push!(headers, "ETag" => etag)
request_etag = HTTP.header(request, "If-None-Match", "")
request_etag == etag && return HTTP.Response(304)
end
return HTTP.Response(200, headers; body = file_contents)
catch e
!(e isa SystemError) && rethrow(e)
#TODO print to log
return HTTP.Response(404)
end
end
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 2085 | function generate_component!(block, module_name, prefix, meta)
args = isempty(meta["args"]) ? Symbol[] : Symbol.(meta["args"])
wild_args = isempty(meta["wild_args"]) ? Symbol[] : Symbol.(meta["wild_args"])
fname = string(prefix, "_", lowercase(meta["name"]))
fsymbol = Symbol(fname)
append!(block.args,
(quote
export $fsymbol
function $(fsymbol)(;kwargs...)
available_props = $args
wild_props = $wild_args
return Component($fname, $(meta["name"]), $module_name, available_props, wild_props; kwargs...)
end
end).args
)
signatures = String[string(repeat(" ", 4), fname, "(;kwargs...)")]
if in(:children, args)
append!(block.args,
(quote
$(fsymbol)(children::Any; kwargs...) = $(fsymbol)(;kwargs..., children = children)
$(fsymbol)(children_maker::Function; kwargs...) = $(fsymbol)(children_maker();kwargs...)
end).args
)
push!(signatures,
string(repeat(" ", 4), fname, "(children::Any, kwargs...)")
)
push!(signatures,
string(repeat(" ", 4), fname, "(children_maker::Function, kwargs...)")
)
end
docstr = string(
join(signatures, "\n"),
"\n\n",
meta["docstr"]
)
push!(block.args, :(@doc $docstr $fsymbol))
end
function generate_components_package(meta)
result = Expr(:block)
name = meta["name"]
prefix = meta["prefix"]
for cmeta in meta["components"]
generate_component!(result, name, prefix, cmeta)
end
return result
end
function generate_embeded_components()
dash_meta = load_meta("dash")
packages = dash_meta["embedded_components"]
result = Expr(:block)
for p in packages
append!(result.args,
generate_components_package(load_meta(p)).args
)
end
return result
end
macro place_embedded_components()
return esc(
generate_embeded_components()
)
end
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 2634 | using YAML
load_meta(name) = YAML.load_file(
joinpath(artifact"dash_resources", "$(name).yaml")
)
deps_path(name) = joinpath(artifact"dash_resources", "$(name)_deps")
dash_dependency_resource(meta) = Resource(
relative_package_path = meta["relative_package_path"],
external_url = meta["external_url"]
)
nothing_if_empty(v) = isempty(v) ? nothing : v
dash_module_resource(meta) = Resource(
relative_package_path = nothing_if_empty(get(meta, "relative_package_path", "")),
external_url = nothing_if_empty(get(meta, "external_url", "")),
dev_package_path = nothing_if_empty(get(meta, "dev_package_path", "")),
dynamic = get(meta, "dynamic", nothing),
type = Symbol(meta["type"]),
async = haskey(meta, "async") ? string(meta["async"]) : nothing
)
function setup_renderer_resources()
renderer_meta = _metadata.dash_renderer
renderer_resource_path = joinpath(artifact"dash_resources", "dash_renderer_deps")
renderer_version = renderer_meta["version"]
DashBase.main_registry().dash_dependency = (
dev = ResourcePkg(
"dash_renderer",
renderer_resource_path, version = renderer_version,
dash_dependency_resource.(renderer_meta["js_dist_dependencies"]["dev"])
),
prod = ResourcePkg(
"dash_renderer",
renderer_resource_path, version = renderer_version,
dash_dependency_resource.(renderer_meta["js_dist_dependencies"]["prod"])
)
)
renderer_renderer_meta = renderer_meta["deps"][1]
DashBase.main_registry().dash_renderer = ResourcePkg(
"dash_renderer",
renderer_resource_path, version = renderer_version,
dash_module_resource.(renderer_renderer_meta["resources"])
)
end
function load_all_metadata()
dash_meta = load_meta("dash")
renderer_meta = load_meta("dash_renderer")
components = Dict{Symbol, Any}()
for comp in dash_meta["embedded_components"]
components[Symbol(comp)] = filter(v->v.first!="components", load_meta(comp))
end
return (
dash = dash_meta,
dash_renderer = renderer_meta,
embedded_components = (;components...)
)
end
function setup_dash_resources()
meta = _metadata.dash
path = deps_path("dash")
version = meta["version"]
for dep in meta["deps"]
DashBase.register_package(
ResourcePkg(
dep["namespace"],
path,
version = version,
dash_module_resource.(dep["resources"])
)
)
end
end
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 6784 | abstract type AppResource end
struct AppRelativeResource <: AppResource
namespace ::String
relative_path ::String
version ::String
ts ::Int64
end
struct AppExternalResource <: AppResource
url ::String
end
struct AppCustomResource <: AppResource
params ::Dict{String, String}
end
struct AppAssetResource <: AppResource
path ::String
ts ::Int64
end
struct NamespaceFiles
base_path ::String
files ::Set{String}
NamespaceFiles(base_path) = new(base_path, Set{String}())
end
struct ApplicationResources
files ::Dict{String, NamespaceFiles}
css ::Vector{AppResource}
js ::Vector{AppResource}
favicon ::Union{Nothing, AppAssetResource}
ApplicationResources(files, css, js, favicon) = new(files, css, js, favicon)
end
function ApplicationResources(app::DashApp, registry::ResourcesRegistry)
css = AppResource[]
js = AppResource[]
favicon::Union{Nothing, AppResource} = nothing
files = Dict{String, NamespaceFiles}()
serve_locally = get_setting(app, :serve_locally)
assets_external_path = get_setting(app, :assets_external_path)
dev = get_devsetting(app, :serve_dev_bundles)
eager_loading = get_setting(app, :eager_loading)
append_pkg = function(pkg)
append!(css,
_convert_resource_pkg(pkg, :css, dev = dev, serve_locally = serve_locally, eager_loading = eager_loading)
)
append!(js,
_convert_resource_pkg(pkg, :js, dev = dev, serve_locally = serve_locally, eager_loading = eager_loading)
)
end
asset_resource = serve_locally || isnothing(assets_external_path) ?
(url, modified) -> AppAssetResource(url, modified) :
(url, modified) -> AppExternalResource(assets_external_path*url)
append_pkg(get_dash_dependencies(registry, get_devsetting(app, :props_check)))
append!(css,
_convert_external.(get_setting(app, :external_stylesheets))
)
append!(js,
_convert_external.(get_setting(app, :external_scripts))
)
if get_setting(app, :include_assets_files)
walk_assets(app) do type, url, path, modified
if type == :js
push!(js, asset_resource(url, modified))
elseif type == :css
push!(css, asset_resource(url, modified))
elseif type == :favicon
favicon = AppAssetResource(url, modified)
end
end
end
append_pkg.(get_componens_pkgs(registry))
append_pkg(get_dash_renderer_pkg(registry))
fill_files(files, get_dash_dependencies(registry, get_devsetting(app, :props_check)), dev = dev, serve_locally = serve_locally)
fill_files.(Ref(files), get_componens_pkgs(registry), dev = dev, serve_locally = serve_locally)
fill_files(files, get_dash_renderer_pkg(registry), dev = dev, serve_locally = serve_locally)
ApplicationResources(files, css, js, favicon)
end
function fill_files(dest::Dict{String, NamespaceFiles}, pkg::ResourcePkg; dev, serve_locally)
!serve_locally && return
if !haskey(dest, pkg.namespace)
dest[pkg.namespace] = NamespaceFiles(pkg.path)
end
namespace_files = get!(dest, pkg.namespace, NamespaceFiles(pkg.path))
full_path = (p)->joinpath(pkg.path, lstrip(p, ['/','\\']))
for resource in pkg.resources
paths = dev && has_dev_path(resource) ? get_dev_path(resource) : get_relative_path(resource)
for path in paths
push!.(
Ref(namespace_files.files),
lstrip.(path, Ref(['/', '\\']))
)
end
end
end
function walk_assets(callback, app::DashApp)
assets_ignore = get_setting(app, :assets_ignore)
assets_regex = Regex(assets_ignore)
assets_filter = isempty(assets_ignore) ?
(f) -> true :
(f) -> !occursin(assets_regex, f)
assets_path = get_assets_path(app)
if get_setting(app, :include_assets_files) && isdir(assets_path)
for (base, dirs, files) in walkdir(assets_path)
if !isempty(files)
relative = ""
if base != assets_path
relative = join(
splitpath(
relpath(base, assets_path)
), "/"
) * "/"
end
for file in Iterators.filter(assets_filter, files)
file_type::Symbol = endswith(file, ".js") ? :js :
(
endswith(file, ".css") ? :css :
(
file == "favicon.ico" ? :favicon : :none
)
)
if file_type != :none
full_path = joinpath(base, file)
callback(file_type,
relative*file,
full_path,
trunc(Int64, stat(full_path).mtime)
)
end
end
end
end
end
end
_convert_external(v::String) = AppExternalResource(v)
_convert_external(v::Dict{String, String}) = AppCustomResource(v)
function _convert_resource(resource::Resource; namespace, version, ts, dev, serve_locally)::Vector{AppResource}
if !serve_locally && has_external_url(resource)
return AppExternalResource.(get_external_url(resource))
end
relative_path = dev && has_dev_path(resource) ?
get_dev_path(resource) :
(has_relative_path(resource) ? get_relative_path(resource) : nothing)
if !isnothing(relative_path)
return AppRelativeResource.(namespace, relative_path, version, ts)
end
if serve_locally
#TODO Warning
#FIXME Why warning? It's strange logic in python§
return AppResource[]
end
error("$(resource) does not have a relative_package_path, absolute_path, or an external_url.")
end
function _convert_resource_pkg(pkg::ResourcePkg, type::Symbol; dev, serve_locally, eager_loading)
result = AppResource[]
iterator = Iterators.filter(pkg.resources) do r
get_type(r) == type && !isdynamic(r, eager_loading)
end
ts = ispath(pkg.path) ? trunc(Int64, stat(pkg.path).mtime) : 0
for resource in iterator
append!(
result,
_convert_resource(
resource,
namespace = pkg.namespace,
version = pkg.version,
ts = ts,
dev = dev, serve_locally = serve_locally
)
)
end
return result
end
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 884 | const fp_version_clean = r"[^\w-]"
const fp_cache_regex = r"^v[\w-]+m[0-9a-fA-F]+$"
function build_fingerprint(path::AbstractString, version, hash_value)
path_parts = split(path, '/')
(filename, extension) = split(path_parts[end], '.', limit = 2)
return string(
join(vcat(path_parts[1:end-1], filename), '/'),
".v", replace(string(version), fp_version_clean=>"_"),
'm', hash_value,
'.', extension
)
end
function parse_fingerprint_path(path::AbstractString)
path_parts = split(path, '/')
name_parts = split(path_parts[end], '.')
if length(name_parts) > 2 && occursin(fp_cache_regex, name_parts[2])
origin_path = string(
join(vcat(path_parts[1:end-1], [name_parts[1]]), '/'),
'.', join(name_parts[3:end], '.')
)
return (origin_path, true)
end
return (path, false)
end
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 1185 | function is_hot_restart_available()
return !isinteractive() && !isempty(Base.PROGRAM_FILE)
end
function hot_restart(func::Function; check_interval = 1., env_key = "IS_HOT_RELOADABLE", suppress_warn = false)
if !is_hot_restart_available()
error("Hot reloading is disabled for interactive sessions. Please run your app using julia from the command line to take advantage of this feature.")
end
app_path = abspath(Base.PROGRAM_FILE)
if get(ENV, env_key, "false") == "true"
(server, _) = func()
files = parse_includes(app_path)
poll_until_changed(files, interval = check_interval)
close(server)
else
julia_str = joinpath(Sys.BINDIR, Base.julia_exename())
ENV[env_key] = "true"
try
while true
sym = gensym()
task = @async Base.eval(Main,
:(module $(sym) include($app_path) end)
)
wait(task)
end
catch e
if e isa InterruptException
println("finished")
return
else
rethrow(e)
end
end
end
end
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 1671 | using UUIDs
function format_tag(name ::String, attributes::Dict{String, String}, inner::String = ""; opened = false, closed = false)
attrs_string = join(
["$k=\"$v\"" for (k, v) in attributes],
" "
)
tag = "<$name $attrs_string"
if closed
tag *= "/>"
elseif opened
tag *= ">"
else
tag *= ">$inner</$name>"
end
end
function interpolate_string(s::String; kwargs...)
result = s
for (k, v) in kwargs
result = replace(result, "{%$(k)%}" => v)
end
return result
end
function validate_index(name::AbstractString, index::AbstractString, checks::Vector)
missings = filter(checks) do check
!occursin(check[2], index)
end
if !isempty(missings)
error(
string(
"Missing item", (length(missings)>1 ? "s" : ""), " ",
join(getindex.(missings, 1), ", "),
" in ", name
)
)
end
end
macro var_str(s)
return Symbol(s)
end
function parse_props(s)
function make_prop(part)
m = match(r"^(?<id>[A-Za-z]+[\w\-\:\.]*)\.(?<prop>[A-Za-z]+[\w\-\:\.]*)$", strip(part))
if isnothing(m)
error("expected <id>.<property>[,<id>.<property>...] in $(part)")
end
return (Symbol(m[:id]), Symbol(m[:prop]))
end
props_parts = split(s, ",", keepempty = false)
return map(props_parts) do part
return make_prop(part)
end
end
function generate_hash()
return strip(string(UUIDs.uuid4()), '-')
end
sort_by_keys(data) = (;sort!(collect(pairs(data)), by = (x)->x[1])...,)
sorted_json(data) = JSON3.write(sort_by_keys(data))
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 830 | function parse_elem!(file::AbstractString, ex::Expr, dest::Set{String})
if ex.head == :call && ex.args[1] == :include && ex.args[2] isa String
dir = dirname(file)
include_file = normpath(joinpath(dir, ex.args[2]))
parse_includes!(include_file, dest)
return
end
for arg in ex.args
parse_elem!(file, arg, dest)
end
end
function parse_elem!(file::AbstractString, ex, dest::Set{String}) end
function parse_includes!(file::AbstractString, dest::Set{String})
!isfile(file) && return
file in dest && return
push!(dest, abspath(file))
ex = Base.parse_input_line(read(file, String); filename=file)
parse_elem!(file, ex, dest)
end
function parse_includes(file::AbstractString)
result = Set{String}()
parse_includes!(file, result)
return result
end
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 2436 | function program_path()
(isinteractive() || isempty(Base.PROGRAM_FILE)) && return nothing
return dirname(abspath(Base.PROGRAM_FILE))
end
function app_root_path()
prog_path = program_path()
return isnothing(prog_path) ? pwd() : prog_path
end
function pathname_configs(url_base_pathname, requests_pathname_prefix, routes_pathname_prefix)
raise_error = (s) -> error("""
$s This is ambiguous.
To fix this, set `routes_pathname_prefix` instead of `url_base_pathname`.
Note that `requests_pathname_prefix` is the prefix for the AJAX calls that
originate from the client (the web browser) and `routes_pathname_prefix` is
the prefix for the API routes on the backend (as defined within HTTP.jl).
`url_base_pathname` will set `requests_pathname_prefix` and
`routes_pathname_prefix` to the same value.
If you need these to be different values then you should set
`requests_pathname_prefix` and `routes_pathname_prefix`,
not `url_base_pathname`.
""")
if !isnothing(url_base_pathname) && !isnothing(requests_pathname_prefix)
raise_error("You supplied `url_base_pathname` and `requests_pathname_prefix`")
end
if !isnothing(url_base_pathname) && !isnothing(routes_pathname_prefix)
raise_error("You supplied `url_base_pathname` and `routes_pathname_prefix`")
end
if !isnothing(url_base_pathname) && isnothing(routes_pathname_prefix)
routes_pathname_prefix = url_base_pathname
elseif isnothing(routes_pathname_prefix)
routes_pathname_prefix = "/"
end
!startswith(routes_pathname_prefix, "/") && error("routes_pathname_prefix` needs to start with `/`")
!endswith(routes_pathname_prefix, "/") && error("routes_pathname_prefix` needs to end with `/`")
app_name = dash_env("APP_NAME")
if isnothing(requests_pathname_prefix) && !isnothing(app_name)
requests_pathname_prefix = "/" * app_name * routes_pathname_prefix
elseif isnothing(requests_pathname_prefix)
requests_pathname_prefix = routes_pathname_prefix
end
!startswith(requests_pathname_prefix, "/") &&
error("requests_pathname_prefix` needs to start with `/`")
!endswith(requests_pathname_prefix, routes_pathname_prefix) &&
error("requests_pathname_prefix` needs to end with `routes_pathname_prefix`")
return (url_base_pathname, requests_pathname_prefix, routes_pathname_prefix)
end
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 1895 | struct WatchState
filename::String
mtime ::Float64
WatchState(filename) = new(filename, mtime(filename))
end
function poll_until_changed(files::Set{String}; interval = 1.)
watched = WatchState[]
for f in files
!isfile(f) && return
push!(watched, WatchState(f))
end
active = true
while active
for w in watched
if !isfile(w.filename)
active = false
break;
end
if mtime(w.filename) != w.mtime
active = false
break;
end
end
sleep(interval)
end
end
function init_watched(folders)
watched = Dict{String, Float64}()
for folder in folders
!isdir(folder) && continue
for (base, _, files) in walkdir(folder)
for f in files
path = joinpath(base, f)
new_time = mtime(path)
watched[path] = new_time
end
end
end
return watched
end
function poll_folders(on_change, folders, initial_watched; interval = 1.)
watched = initial_watched
while true
walked = Set{String}()
for folder in folders
!isdir(folder) && continue
for (base, _, files) in walkdir(folder)
for f in files
path = joinpath(base, f)
new_time = mtime(path)
if new_time > get(watched, path, -1.)
on_change(path, new_time, false)
end
watched[path] = new_time
push!(walked, path)
end
end
end
for path in keys(watched)
if !(path in walked)
on_change(path, -1., true)
delete!(watched, path)
end
end
sleep(interval)
end
end
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 251 | using Aqua
# ideally we get both these tests to work, but:
# stale_deps is ignored to help transition from DashCoreComponents
# amiguities is ignored because they originate outside the package
Aqua.test_all(Dash; ambiguities=false, stale_deps=false)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 25440 | import HTTP, JSON3
using Test
using Dash
@testset "callback! prevent_initial_call" begin
#============= default ===========#
app = dash()
app.layout = html_div() do
dcc_input(id = "my-id", value="initial value", type = "text"),
html_div(id = "my-div"),
html_div(id = "my-div2")
end
callback!(app, Output("my-div", "children"), Input("my-id", "value")) do value
return value
end
callback!(app, Output("my-div2", "children"), Input("my-id", "value")) do value
return value
end
handler = make_handler(app)
request = HTTP.Request("GET", "/_dash-dependencies")
resp = Dash.HttpHelpers.handle(handler, request)
deps = JSON3.read(String(resp.body))
@test deps[1].prevent_initial_call == false
@test deps[2].prevent_initial_call == false
#============= manual on single callback ===========#
app = dash()
app.layout = html_div() do
dcc_input(id = "my-id", value="initial value", type = "text"),
html_div(id = "my-div"),
html_div(id = "my-div2")
end
callback!(app, Output("my-div", "children"), Input("my-id", "value"), prevent_initial_call = true) do value
return value
end
callback!(app, Output("my-div2", "children"), Input("my-id", "value")) do value
return value
end
handler = make_handler(app)
request = HTTP.Request("GET", "/_dash-dependencies")
resp = Dash.HttpHelpers.handle(handler, request)
deps = JSON3.read(String(resp.body))
@test deps[1].prevent_initial_call == true
@test deps[2].prevent_initial_call == false
#============= prevent_initial_callbacks ===========#
app = dash(prevent_initial_callbacks = true)
app.layout = html_div() do
dcc_input(id = "my-id", value="initial value", type = "text"),
html_div(id = "my-div"),
html_div(id = "my-div2")
end
callback!(app, Output("my-div", "children"), Input("my-id", "value")) do value
return value
end
callback!(app, Output("my-div2", "children"), Input("my-id", "value")) do value
return value
end
handler = make_handler(app)
request = HTTP.Request("GET", "/_dash-dependencies")
resp = Dash.HttpHelpers.handle(handler, request)
deps = JSON3.read(String(resp.body))
@test deps[1].prevent_initial_call == true
@test deps[2].prevent_initial_call == true
#============= prevent_initial_callbacks + manual ===========#
app = dash(prevent_initial_callbacks = true)
app.layout = html_div() do
dcc_input(id = "my-id", value="initial value", type = "text"),
html_div(id = "my-div"),
html_div(id = "my-div2")
end
callback!(app, Output("my-div", "children"), Input("my-id", "value")) do value
return value
end
callback!(app, Output("my-div2", "children"), Input("my-id", "value"), prevent_initial_call = false) do value
return value
end
handler = make_handler(app)
request = HTTP.Request("GET", "/_dash-dependencies")
resp = Dash.HttpHelpers.handle(handler, request)
deps = JSON3.read(String(resp.body))
@test deps[1].prevent_initial_call == true
@test deps[2].prevent_initial_call == false
end
@testset "callback! single output" begin
app = dash()
app.layout = html_div() do
dcc_input(id = "my-id", value="initial value", type = "text"),
html_div(id = "my-div")
end
callback!(app, Output("my-div", "children"), Input("my-id", "value")) do value
return value
end
@test length(app.callbacks) == 1
@test haskey(app.callbacks, Symbol("my-div.children"))
@test app.callbacks[Symbol("my-div.children")].func("test") == "test"
handler = make_handler(app)
request = HTTP.Request("GET", "/_dash-dependencies")
resp = Dash.HttpHelpers.handle(handler, request)
deps = JSON3.read(String(resp.body))
@test length(deps) == 1
cb = deps[1]
@test cb.output == "my-div.children"
@test cb.inputs[1].id == "my-id"
@test cb.inputs[1].property == "value"
@test :clientside_function in keys(cb)
@test isnothing(cb.clientside_function)
handler = Dash.make_handler(app)
test_json = """{"output":"my-div.children","changedPropIds":["my-id.value"],"inputs":[{"id":"my-id","property":"value","value":"test"}]}"""
request = HTTP.Request("POST", "/_dash-update-component", [], Vector{UInt8}(test_json))
response = Dash.HttpHelpers.handle(handler, request)
@test response.status == 200
resp_obj = JSON3.read(String(response.body))
@test in(:multi, keys(resp_obj))
@test resp_obj.response.var"my-div".children == "test"
end
@testset "callback! multi output" begin
app = dash()
app.layout = html_div() do
dcc_input(id = "my-id", value="initial value", type = "text"),
html_div(id = "my-div"),
html_div(id = "my-div2")
end
callback!(app, [Output("my-div","children"), Output("my-div2","children")], Input("my-id","value"), State("my-id","type")) do value, state
return value, state
end
@test length(app.callbacks) == 1
@test haskey(app.callbacks, Symbol("..my-div.children...my-div2.children.."))
@test app.callbacks[Symbol("..my-div.children...my-div2.children..")].func("value", "state") == ("value", "state")
handler = Dash.make_handler(app)
test_json = """{"output":"..my-div.children...my-div2.children..","changedPropIds":["my-id.value"],"inputs":[{"id":"my-id","property":"value","value":"test"}], "state":[{"id":"my-id","property":"type","value":"state"}]}"""
request = HTTP.Request("POST", "/_dash-update-component", [], Vector{UInt8}(test_json))
response = Dash.HttpHelpers.handle(handler, request)
@test response.status == 200
resp_obj = JSON3.read(String(response.body))
@test in(:multi, keys(resp_obj))
@test resp_obj.response[Symbol("my-div")].children == "test"
@test resp_obj.response[Symbol("my-div2")].children == "state"
app = dash()
app.layout = html_div() do
dcc_input(id = "my-id", value="initial value", type = "text"),
html_div(id = "my-div"),
html_div(id = "my-div2")
end
callback!(app, [Output("my-div","children")], Input("my-id","value"), State("my-id","type")) do value, state
return (value,)
end
@test length(app.callbacks) == 1
@test haskey(app.callbacks, Symbol("..my-div.children.."))
@test app.callbacks[Symbol("..my-div.children..")].func("value", "state") == ("value", )
handler = Dash.make_handler(app)
test_json = """{"output":"..my-div.children..","changedPropIds":["my-id.value"],"inputs":[{"id":"my-id","property":"value","value":"test"}], "state":[{"id":"my-id","property":"type","value":"state"}]}"""
request = HTTP.Request("POST", "/_dash-update-component", [], Vector{UInt8}(test_json))
response = Dash.HttpHelpers.handle(handler, request)
@test response.status == 200
resp_obj = JSON3.read(String(response.body))
@test in(:multi, keys(resp_obj))
@test resp_obj.response[Symbol("my-div")].children == "test"
end
@testset "callback! multi output flat" begin
app = dash()
app.layout = html_div() do
dcc_input(id = "my-id", value="initial value", type = "text"),
dcc_input(id = "my-id2", value="initial value", type = "text"),
html_div(id = "my-div"),
html_div(id = "my-div2")
end
callback!(app, Output("my-div","children"), Output("my-div2","children"),
Input("my-id","value"), Input("my-id", "value"), State("my-id","type")) do value, value2, state
return value * value2, state
end
@test length(app.callbacks) == 1
@test haskey(app.callbacks, Symbol("..my-div.children...my-div2.children.."))
@test app.callbacks[Symbol("..my-div.children...my-div2.children..")].func("value", " value2", "state") == ("value value2", "state")
app = dash()
app.layout = html_div() do
dcc_input(id = "my-id", value="initial value", type = "text"),
dcc_input(id = "my-id2", value="initial value", type = "text"),
html_div(id = "my-div"),
html_div(id = "my-div2")
end
callback!(app, Output("my-div","children"),
Input("my-id","value"), Input("my-id", "value")) do value, value2
return value * value2
end
@test length(app.callbacks) == 1
@test haskey(app.callbacks, Symbol("my-div.children"))
@test app.callbacks[Symbol("my-div.children")].func("value", " value2") == "value value2"
end
@testset "callback! multi output same component id" begin
app = dash()
app.layout = html_div() do
dcc_input(id = "input-one",
placeholder = "text or number?")
dcc_input(id = "input-two",
placeholder = "")
end
callback!(app, Output("input-two","placeholder"), Output("input-two","type"),
Input("input-one","value")) do val1
if val1 in ["text", "number"]
return "$val1 ??", val1
end
return "invalid", nothing
end
@test length(app.callbacks) == 1
@test haskey(app.callbacks, Symbol("..input-two.placeholder...input-two.type.."))
@test app.callbacks[Symbol("..input-two.placeholder...input-two.type..")].func("text") == ("text ??", "text")
@test Dash.process_callback_call(app,
Symbol("..input-two.placeholder...input-two.type.."),
[(id = "input-two", property = "placeholder"),
(id = "input-two", property = "type")],
[(value = "text",)], [])[:response] == Dict("input-two" => Dict(:type => "text",
:placeholder => "text ??"))
end
@testset "callback! checks" begin
app = dash()
app.layout = html_div() do
dcc_input(id = "my-id", value="initial value", type = "text"),
html_div(id = "my-div"),
html_div(id = "my-div2")
end
callback!(app, Output("my-div","children"), Input("my-id","value")) do value
return value
end
callback!(app, Output("my-div2","children"), Input("my-id","value")) do value
return "v_$(value)"
end
@test length(app.callbacks) == 2
@test haskey(app.callbacks, Symbol("my-div.children"))
@test haskey(app.callbacks, Symbol("my-div2.children"))
@test app.callbacks[Symbol("my-div.children")].func("value") == "value"
@test app.callbacks[Symbol("my-div2.children")].func("value") == "v_value"
#empty input
@test_throws ErrorException callback!(app,
[Output("my-id","value"), Output("my-div","children")],
Input[]) do value
return "v_$(value)"
end
app = dash()
app.layout = html_div() do
dcc_input(id = "my-id", value="initial value", type = "text"),
dcc_input(id = "my-id2", value="initial value", type = "text"),
html_div(id = "my-div"),
html_div(id = "my-div2")
end
#empty output
@test_throws ErrorException callback!(app,
Input("my-id","value")) do value
return "v_$(value)"
end
#empty input
@test_throws ErrorException callback!(app,
Output("my-div2", "children")) do value
return "v_$(value)"
end
#wrong args order
@test_throws ErrorException callback!(app,
Input("my-id","value"), Output("my-div", "children")) do value
return "v_$(value)"
end
@test_throws ErrorException callback!(app,
Output("my-div2", "children"), Input("my-id","value"), Output("my-div", "children")) do value
return "v_$(value)"
end
@test_throws ErrorException callback!(app,
Output("my-div2", "children"), Input("my-id","value"), State("my-div", "children"), Input("my-id2", "value")) do value, value2
return "v_$(value)"
end
end
@testset "multiple callbacks targeting same output" begin
app = dash()
app.layout = html_div() do
dcc_input(id = "my-id", value="initial value", type = "text"),
dcc_input(id = "my-id2", value="initial value2", type = "text"),
html_div(id = "my-div")
end
callback!(app, Output("my-div","children"), Input("my-id","value")) do value
return value
end
testresult = @test_throws ErrorException callback!(app, Output("my-div","children"), Input("my-id2","value")) do value
return "v_$(value)"
end
@test testresult.value.msg == "Multiple callbacks can not target the same output. Offending output: my-div.children"
end
@testset "empty triggered params" begin
app = dash()
app.layout = html_div() do
dcc_input(id = "test-in", value="initial value", type = "text"),
html_div(id = "test-out")
end
callback!(app, Output("test-out", "children"), Input("test-out", "value")) do value
context = callback_context()
@test length(context.triggered) == 0
@test isempty(context.triggered)
return string(value)
end
@test length(app.callbacks) == 1
handler = Dash.make_handler(app)
request = (
output = "test-out.children",
changedPropIds = [],
inputs = [
(id = "test-in", property = "value", value = "test")
]
)
test_json = JSON3.write(request)
request = HTTP.Request("POST", "/_dash-update-component", [], Vector{UInt8}(test_json))
response = Dash.HttpHelpers.handle(handler, request)
@test response.status == 200
end
@testset "pattern-match" begin
app = dash()
app.layout = html_div() do
dcc_input(id = (type="test", index = 1), value="initial value", type = "text"),
dcc_input(id = (type="test", index = 2), value="initial value", type = "text"),
html_div(id = (type = "test-out", index = 1)),
html_div(id = (type = "test-out", index = 2))
end
changed_key = """{"index":2,"type":"test"}.value"""
callback!(app, Output((type = "test-out", index = MATCH), "children"), Input((type="test", index = MATCH), "value")) do value
context = callback_context()
@test haskey(context.inputs, changed_key)
@test context.inputs[changed_key] == "test"
@test length(context.triggered) == 1
@test context.triggered[1].prop_id == changed_key
@test context.triggered[1].value == "test"
return string(value)
end
@test length(app.callbacks) == 1
out_key = Symbol("""{"index":["MATCH"],"type":"test-out"}.children""")
@test haskey(app.callbacks, out_key)
handler = Dash.make_handler(app)
request = (
output = string(out_key),
outputs = (id = (index = 1, type="test_out"), property = "children"),
changedPropIds = [changed_key],
inputs = [
(id = (index=2, type="test"), property = "value", value = "test")
]
)
test_json = JSON3.write(request)
request = HTTP.Request("POST", "/_dash-update-component", [], Vector{UInt8}(test_json))
response = Dash.HttpHelpers.handle(handler, request)
@test response.status == 200
resp_obj = JSON3.read(String(response.body))
@test in(:multi, keys(resp_obj))
@test resp_obj.response.var"{\"index\":1,\"type\":\"test_out\"}".children == "test"
end
@testset "pattern-match ALL single out" begin
app = dash()
app.layout = html_div() do
dcc_input(id = (type="test", index = 1), value="initial value", type = "text"),
dcc_input(id = (type="test", index = 2), value="initial value", type = "text"),
html_div(id = (type = "test-out", index = 1)),
html_div(id = (type = "test-out", index = 2))
end
first_key = """{"index":1,"type":"test"}.value"""
changed_key = """{"index":2,"type":"test"}.value"""
callback!(app, Output((type = "test-out", index = ALL), "children"), Input((type="test", index = ALL), "value")) do value
context = callback_context()
@test haskey(context.inputs, first_key)
@test context.inputs[first_key] == "test 1"
@test haskey(context.inputs, changed_key)
@test context.inputs[changed_key] == "test"
@test length(context.triggered) == 1
@test context.triggered[1].prop_id == changed_key
@test context.triggered[1].value == "test"
return value
end
@test length(app.callbacks) == 1
out_key = Symbol("""{"index":["ALL"],"type":"test-out"}.children""")
@test haskey(app.callbacks, out_key)
handler = Dash.make_handler(app)
request = (
output = string(out_key),
outputs = [
(id = (index=1, type="test-out"), property = "children"),
(id = (index=2, type="test-out"), property = "children")
],
changedPropIds = [changed_key],
inputs = [
[
(id = (index=1, type="test"), property = "value", value = "test 1"),
(id = (index=2, type="test"), property = "value", value = "test")
]
]
)
test_json = JSON3.write(request)
request = HTTP.Request("POST", "/_dash-update-component", [], Vector{UInt8}(test_json))
response = Dash.HttpHelpers.handle(handler, request)
@test response.status == 200
s = String(response.body)
resp_obj = JSON3.read(s)
@test in(:multi, keys(resp_obj))
@test resp_obj.response.var"{\"index\":1,\"type\":\"test-out\"}".children =="test 1"
@test resp_obj.response.var"{\"index\":2,\"type\":\"test-out\"}".children =="test"
end
@testset "pattern-match ALL multi out" begin
app = dash()
app.layout = html_div() do
dcc_input(id = (type="test", index = 1), value="initial value", type = "text"),
dcc_input(id = (type="test", index = 2), value="initial value", type = "text"),
html_div(id = (type = "test-out", index = 1)),
html_div(id = (type = "test-out", index = 2))
end
first_key = """{"index":1,"type":"test"}.value"""
changed_key = """{"index":2,"type":"test"}.value"""
callback!(app, [Output((type = "test-out", index = ALL), "children")], Input((type="test", index = ALL), "value")) do value
context = callback_context()
@test haskey(context.inputs, first_key)
@test context.inputs[first_key] == "test 1"
@test haskey(context.inputs, changed_key)
@test context.inputs[changed_key] == "test"
@test length(context.triggered) == 1
@test context.triggered[1].prop_id == changed_key
@test context.triggered[1].value == "test"
return [value]
end
@test length(app.callbacks) == 1
out_key = Symbol("""..{"index":["ALL"],"type":"test-out"}.children..""")
@test haskey(app.callbacks, out_key)
handler = Dash.make_handler(app)
request = (
output = string(out_key),
outputs = [[
(id = (index=1, type="test-out"), property = "children"),
(id = (index=2, type="test-out"), property = "children")
]],
changedPropIds = [changed_key],
inputs = [
[
(id = (index=1, type="test"), property = "value", value = "test 1"),
(id = (index=2, type="test"), property = "value", value = "test")
]
]
)
test_json = JSON3.write(request)
request = HTTP.Request("POST", "/_dash-update-component", [], Vector{UInt8}(test_json))
response = Dash.HttpHelpers.handle(handler, request)
@test response.status == 200
resp_obj = JSON3.read(String(response.body))
@test in(:multi, keys(resp_obj))
@test resp_obj.response.var"{\"index\":1,\"type\":\"test-out\"}".children =="test 1"
@test resp_obj.response.var"{\"index\":2,\"type\":\"test-out\"}".children =="test"
end
@testset "invalid multi out" begin
app = dash()
app.layout = html_div() do
html_div(id="a"),
html_div(id="b"),
html_div(id="c"),
html_div(id="d"),
html_div(id="e"),
html_div(id="f")
end
callback!(app, [Output("b", "children")], Input("a", "children")) do a
return (1,2)
end
#invalid number of outputs
@test_throws Dash.InvalidCallbackReturnValue Dash.process_callback_call(app, :var"..b.children..", [(id = "b", property = "children")], [(value = "aaa",)], [])
callback!(app, Output("c", "children"), Output("d", "children"), Input("a", "children")) do a
return 1
end
#result not array
@test_throws Dash.InvalidCallbackReturnValue Dash.process_callback_call(
app, Symbol("..c.children...d.children.."),
[(id = "b", property = "children")], [(value = "aaa",)], []
)
app = dash()
app.layout = html_div() do
html_div(id=(index = 1,)),
html_div(id=(index = 2,)),
html_div(id=(index = 3,))
end
callback!(app, Output((index = ALL,), "children"), Input((index = ALL,), "css")) do inputs
return [1,2]
end
#pattern-match output elements length not match to specs
@test_throws Dash.InvalidCallbackReturnValue Dash.process_callback_call(
app, Symbol("""{"index":["ALL"]}.children"""),
[[
(id = """{"index":1}""", property = "children"),
(id = """{"index":2}""", property = "children"),
(id = """{"index":3}""", property = "children"),
]],
[[(value = "aaa",), (value = "bbb",), (value = "ccc",)]], []
)
app = dash()
app.layout = html_div() do
html_div(id=(index = 1,)),
html_div(id=(index = 2,)),
html_div(id=(index = 3,))
end
callback!(app, Output((index = ALL,), "children"), Input((index = ALL,), "css")) do inputs
return 1
end
#pattern-match output element not array
@test_throws Dash.InvalidCallbackReturnValue Dash.process_callback_call(
app, Symbol("""{"index":["ALL"]}.children"""),
[[
(id = """{"index":1}""", property = "children"),
(id = """{"index":2}""", property = "children"),
(id = """{"index":3}""", property = "children"),
]],
[[(value = "aaa",), (value = "bbb",), (value = "ccc",)]], []
)
end
@testset "clientside callbacks function" begin
app = dash()
app.layout = html_div() do
dcc_input(id = "my-id", value="initial value", type = "text"),
html_div(id = "my-div")
end
callback!(ClientsideFunction("namespace", "func_name"),app, Output("my-div","children"), Input("my-id","value"))
@test length(app.callbacks) == 1
@test haskey(app.callbacks, Symbol("my-div.children"))
@test app.callbacks[Symbol("my-div.children")].func isa ClientsideFunction
@test app.callbacks[Symbol("my-div.children")].func.namespace == "namespace"
@test app.callbacks[Symbol("my-div.children")].func.function_name == "func_name"
handler = make_handler(app)
request = HTTP.Request("GET", "/_dash-dependencies")
resp = Dash.HttpHelpers.handle(handler, request)
deps = JSON3.read(String(resp.body))
@test length(deps) == 1
cb = deps[1]
@test cb.output == "my-div.children"
@test cb.inputs[1].id == "my-id"
@test cb.inputs[1].property == "value"
@test :clientside_function in keys(cb)
@test cb.clientside_function.namespace == "namespace"
@test cb.clientside_function.function_name == "func_name"
end
@testset "clientside callbacks string" begin
app = dash()
app.layout = html_div() do
dcc_input(id = "my-id", value="initial value", type = "text"),
html_div(id = "my-div")
end
callback!(
"""
function(input_value) {
return (
parseFloat(input_value_1, 10)
);
}
"""
, app,
Output("my-div", "children"),
Input("my-id", "value")
)
@test length(app.callbacks) == 1
@test haskey(app.callbacks, Symbol("my-div.children"))
@test app.callbacks[Symbol("my-div.children")].func isa ClientsideFunction
@test app.callbacks[Symbol("my-div.children")].func.namespace == "_dashprivate_my-div"
@test app.callbacks[Symbol("my-div.children")].func.function_name == "children"
@test length(app.inline_scripts) == 1
@test occursin("clientside[\"_dashprivate_my-div\"]", app.inline_scripts[1])
@test occursin("ns[\"children\"]", app.inline_scripts[1])
handler = make_handler(app)
request = HTTP.Request("GET", "/_dash-dependencies")
resp = Dash.HttpHelpers.handle(handler, request)
deps = JSON3.read(String(resp.body))
@test length(deps) == 1
cb = deps[1]
@test cb.output == "my-div.children"
@test cb.inputs[1].id == "my-id"
@test cb.inputs[1].property == "value"
@test :clientside_function in keys(cb)
@test cb.clientside_function.namespace == "_dashprivate_my-div"
@test cb.clientside_function.function_name == "children"
request = HTTP.Request("GET", "/")
resp = Dash.HttpHelpers.handle(handler, request)
body = String(resp.body)
@test occursin("clientside[\"_dashprivate_my-div\"]", body)
@test occursin("ns[\"children\"]", body)
end
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 1650 | using Test
using Dash
using Base64
@testset "Send String" begin
data = "test string"
res = dcc_send_string(data, "test_file.csv"; type = "text/csv")
@test res[:content] == data
@test res[:filename] == "test_file.csv"
@test res[:type] == "text/csv"
@test !res[:base64]
data2 = "test 2 string"
res = dcc_send_string(data2, "test_file.csv"; type = "text/csv") do io, data
write(io, data)
end
@test res[:content] == data2
@test res[:filename] == "test_file.csv"
@test res[:type] == "text/csv"
@test !res[:base64]
end
@testset "Send Bytes" begin
data = "test string"
res = dcc_send_bytes(Vector{UInt8}(data), "test_file.csv"; type = "text/csv")
@test res[:content] == Base64.base64encode(data)
@test res[:filename] == "test_file.csv"
@test res[:type] == "text/csv"
@test res[:base64]
data2 = "test 2 string"
res = dcc_send_bytes(write, data2, "test_file.csv"; type = "text/csv")
@test res[:content] == Base64.base64encode(data2)
@test res[:filename] == "test_file.csv"
@test res[:type] == "text/csv"
@test res[:base64]
end
@testset "Send File" begin
file = "assets/test.png"
res = dcc_send_file(file, nothing; type = "text/csv")
@test res[:content] == Base64.base64encode(read(file))
@test res[:filename] == "test.png"
@test res[:type] == "text/csv"
@test res[:base64]
file = "assets/test.png"
res = dcc_send_file(file, "ttt.jpeg"; type = "text/csv")
@test res[:content] == Base64.base64encode(read(file))
@test res[:filename] == "ttt.jpeg"
@test res[:type] == "text/csv"
@test res[:base64]
end
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 8837 | using Test
using Dash
using Dash: ApplicationResources, main_registry, HandlerState, make_handler
using HTTP
@testset "external_stylesheets" begin
app = dash()
resources = ApplicationResources(app, main_registry())
index_page = Dash.index_page(app, resources)
@test isnothing(findfirst("link rel=\"stylesheet\"", index_page))
app = dash(external_stylesheets = ["https://test.css"])
resources = ApplicationResources(app, main_registry())
index_page = Dash.index_page(app, resources)
@test !isnothing(findfirst("<link rel=\"stylesheet\" href=\"https://test.css\">", index_page))
app = dash(external_stylesheets = [
"https://test.css",
Dict("href" => "https://test2.css", "rel" => "stylesheet")
]
)
resources = ApplicationResources(app, main_registry())
index_page = Dash.index_page(app, resources)
@test !isnothing(findfirst("<link rel=\"stylesheet\" href=\"https://test.css\">", index_page))
@test !isnothing(findfirst("href=\"https://test2.css\"", index_page))
end
@testset "external_scripts" begin
app = dash(external_scripts = ["https://test.js"])
resources = ApplicationResources(app, main_registry())
index_page = Dash.index_page(app, resources)
@test !isnothing(findfirst("""<script src="https://test.js"></script>""", index_page))
app = dash(external_scripts = [
"https://test.js",
Dict("src" => "https://test2.js", "crossorigin" => "anonymous")
])
resources = ApplicationResources(app, main_registry())
index_page = Dash.index_page(app, resources)
@test !isnothing(findfirst("""<script src="https://test.js"></script>""", index_page))
@test !isnothing(findfirst("""<script src="https://test2.js" crossorigin="anonymous"></script>""", index_page))
end
@testset "url paths" begin
app = dash(requests_pathname_prefix = "/reg/prefix/", routes_pathname_prefix = "/prefix/")
@test app.config.requests_pathname_prefix == "/reg/prefix/"
@test app.config.routes_pathname_prefix == "/prefix/"
app = dash(routes_pathname_prefix = "/prefix/")
@test app.config.routes_pathname_prefix == "/prefix/"
@test app.config.requests_pathname_prefix == "/prefix/"
app = dash()
@test app.config.routes_pathname_prefix == "/"
@test app.config.requests_pathname_prefix == "/"
ENV["DASH_APP_NAME"] = "test-app"
app = dash(routes_pathname_prefix = "/prefix/")
@test app.config.routes_pathname_prefix == "/prefix/"
@test app.config.requests_pathname_prefix == "/test-app/prefix/"
app = dash()
@test app.config.routes_pathname_prefix == "/"
@test app.config.requests_pathname_prefix == "/test-app/"
delete!(ENV, "DASH_APP_NAME")
end
@testset "assets paths" begin
app = dash()
app.layout = html_div()
handler = make_handler(app)
request = HTTP.Request("GET", "/assets/test.png")
res = Dash.HttpHelpers.handle(handler, request)
@test res.status == 200
request = HTTP.Request("GET", "/assets/test3.png")
res = Dash.HttpHelpers.handle(handler, request)
@test res.status == 404
request = HTTP.Request("GET", "/images/test.png")
res = Dash.HttpHelpers.handle(handler, request)
@test startswith(HTTP.header(res, "Content-Type"), "text/html")
app = dash(url_base_pathname = "/test/")
app.layout = html_div()
handler = make_handler(app)
request = HTTP.Request("GET", "/assets/test.png")
res = Dash.HttpHelpers.handle(handler, request)
@test res.status == 404
request = HTTP.Request("GET", "/test/assets/test.png")
res = Dash.HttpHelpers.handle(handler, request)
@test res.status == 200
request = HTTP.Request("GET", "/images/test.png")
res = Dash.HttpHelpers.handle(handler, request)
@test res.status == 404
app = dash(assets_url_path = "ass")
app.layout = html_div()
handler = make_handler(app)
request = HTTP.Request("GET", "/ass/test.png")
res = Dash.HttpHelpers.handle(handler, request)
@test res.status == 200
request = HTTP.Request("GET", "/ass/test3.png")
res = Dash.HttpHelpers.handle(handler, request)
@test res.status == 404
request = HTTP.Request("GET", "/assets/test3.png")
res = Dash.HttpHelpers.handle(handler, request)
@test startswith(HTTP.header(res, "Content-Type"), "text/html")
request = HTTP.Request("GET", "/images/test.png")
res = Dash.HttpHelpers.handle(handler, request)
@test startswith(HTTP.header(res, "Content-Type"), "text/html")
app = dash(assets_folder = "images")
app.layout = html_div()
handler = make_handler(app)
request = HTTP.Request("GET", "/assets/test.png")
res = Dash.HttpHelpers.handle(handler, request)
@test res.status == 404
request = HTTP.Request("GET", "/assets/test_images.png")
res = Dash.HttpHelpers.handle(handler, request)
@test res.status == 200
request = HTTP.Request("GET", "/images/test.png")
res = Dash.HttpHelpers.handle(handler, request)
@test startswith(HTTP.header(res, "Content-Type"), "text/html")
end
@testset "suppress_callback_exceptions" begin
app = dash()
resources = ApplicationResources(app, main_registry())
index_page = Dash.index_page(app, resources)
@test !isnothing(findfirst("\"suppress_callback_exceptions\":false", index_page))
@test isnothing(findfirst("\"suppress_callback_exceptions\":true", index_page))
app = dash(suppress_callback_exceptions = true)
resources = ApplicationResources(app, main_registry())
index_page = Dash.index_page(app, resources)
@test isnothing(findfirst("\"suppress_callback_exceptions\":false", index_page))
@test !isnothing(findfirst("\"suppress_callback_exceptions\":true", index_page))
end
@testset "meta_tags" begin
app = dash()
resources = ApplicationResources(app, main_registry())
index_page = Dash.index_page(app, resources)
@test !isnothing(
findfirst(
"<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">",
index_page)
)
@test !isnothing(
findfirst(
"<meta charset=\"UTF-8\">",
index_page)
)
app = dash(meta_tags = [Dict("type" => "tst", "rel" => "r")])
resources = ApplicationResources(app, main_registry())
index_page = Dash.index_page(app, resources)
@test !isnothing(
findfirst(
"<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">",
index_page)
)
@test !isnothing(
findfirst(
"<meta charset=\"UTF-8\">",
index_page)
)
@test !isnothing(
findfirst(
Dash.format_tag("meta", Dict("type" => "tst", "rel" => "r"), opened = true),
index_page)
)
app = dash(meta_tags = [Dict("charset" => "Win1251"), Dict("type" => "tst", "rel" => "r")])
resources = ApplicationResources(app, main_registry())
index_page = Dash.index_page(app, resources)
@test isnothing(
findfirst(
"<meta charset=\"UTF-8\">",
index_page)
)
@test !isnothing(
findfirst(
"<meta charset=\"Win1251\">",
index_page)
)
@test !isnothing(
findfirst(
Dash.format_tag("meta", Dict("type" => "tst", "rel" => "r"), opened = true),
index_page)
)
app = dash(meta_tags = [Dict("http-equiv" => "X-UA-Compatible", "content" => "IE"), Dict("type" => "tst", "rel" => "r")])
resources = ApplicationResources(app, main_registry())
index_page = Dash.index_page(app, resources)
@test isnothing(
findfirst(
"<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">",
index_page)
)
@test !isnothing(
findfirst(
Dash.format_tag("meta", Dict("http-equiv" => "X-UA-Compatible", "content" => "IE"), opened = true),
index_page)
)
end
@testset "index_string" begin
index_string = "test test test, {%metas%},{%title%},{%favicon%},{%css%},{%app_entry%},{%config%},{%scripts%},{%renderer%}"
app = dash(index_string = index_string)
resources = ApplicationResources(app, main_registry())
index_page = Dash.index_page(app, resources)
@test startswith(index_page, "test test test,")
end
@testset "show_undo_redo" begin
app = dash()
resources = ApplicationResources(app, main_registry())
index_page = Dash.index_page(app, resources)
@test !isnothing(findfirst("\"show_undo_redo\":false", index_page))
app = dash(show_undo_redo = true)
resources = ApplicationResources(app, main_registry())
index_page = Dash.index_page(app, resources)
@test !isnothing(findfirst("\"show_undo_redo\":true", index_page))
end
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 1285 | using Dash
using Dash.Contexts
@testset "task context" begin
storage = TaskContextStorage()
@test !has_context(storage)
with_context(storage, "test") do
@test has_context(storage)
@test get_context(storage) == "test"
with_context(storage, "inner") do
@test has_context(storage)
@test get_context(storage) == "inner"
end
@test get_context(storage) == "test"
end
@test !has_context(storage)
end
@testset "multiple tasks context" begin
storage = TaskContextStorage()
@test !has_context(storage)
with_context(storage, "test") do
@test has_context(storage)
@test get_context(storage) == "test"
@sync begin
@async begin
@test !has_context(storage)
end
@async begin
with_context(storage, "async_1") do
sleep(0.1)
@test get_context(storage) == "async_1"
end
end
@async begin
with_context(storage, "async_2") do
@test get_context(storage) == "async_2"
end
end
end
@test get_context(storage) == "test"
end
@test !has_context(storage)
end
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 7248 | import HTTP, JSON3
using Test
using DashBase
using Dash
@testset "Components" begin
a_comp = html_a("test", id = "test-a")
@test a_comp.id == "test-a"
@test a_comp.children == "test"
input_comp = dcc_input(id = "test-input", type="text")
@test input_comp.id == "test-input"
@test input_comp.type == "text"
@test_throws ErrorException html_a(undefined_prop = "rrrr")
component_with_children = html_div() do
html_a("fffff"),
html_h1("fffff")
end
@test !isnothing(component_with_children.children)
@test component_with_children.children isa Tuple{Component, Component}
@test length(component_with_children.children) == 2
@test DashBase.get_type(component_with_children.children[1]) == "A"
@test DashBase.get_type(component_with_children.children[2]) == "H1"
end
@testset "handler" begin
app = dash(external_stylesheets=["test.css"])
app.layout = html_div() do
dcc_input(id = "my-id", value="initial value", type = "text"),
html_div(id = "my-div"),
html_div(id = "my-div2")
end
callback!(app, Output("my-div","children"), Input("my-id","value")) do value
return value
end
callback!(app, Output("my-div2","children"), Input("my-id","value")) do value
return "v_$(value)"
end
handler = Dash.make_handler(app)
request = HTTP.Request("GET", "/")
response = Dash.HttpHelpers.handle(handler, request)
@test response.status == 200
body_str = String(response.body)
request = HTTP.Request("GET", "/_dash-layout")
response = Dash.HttpHelpers.handle(handler, request)
@test response.status == 200
body_str = String(response.body)
@test body_str == JSON3.write(app.layout)
request = HTTP.Request("GET", "/_dash-dependencies")
response = Dash.HttpHelpers.handle(handler, request)
@test response.status == 200
body_str = String(response.body)
resp_json = JSON3.read(body_str)
@test resp_json isa AbstractVector
@test length(resp_json) == 2
@test haskey(resp_json[1], :inputs)
@test haskey(resp_json[1], :state)
@test haskey(resp_json[1], :output)
@test length(resp_json[1].inputs) == 1
@test length(resp_json[1].state) == 0
@test resp_json[1].inputs[1].id == "my-id"
@test resp_json[1].inputs[1].property == "value"
@test resp_json[1].output == "my-div.children"
test_json = """{"output":"my-div.children","changedPropIds":["my-id.value"],"inputs":[{"id":"my-id","property":"value","value":"initial value3333"}]}"""
request = HTTP.Request("POST", "/_dash-update-component", [], Vector{UInt8}(test_json))
response = Dash.HttpHelpers.handle(handler, request)
@test response.status == 200
body_str = String(response.body)
@test body_str == """{"response":{"my-div":{"children":"initial value3333"}},"multi":true}"""
end
@testset "layout as function" begin
app = dash()
global_id = "my_div2"
layout_func = () -> begin
html_div() do
dcc_input(id = "my-id", value="initial value", type = "text"),
html_div(id = "my-div"),
html_div(id = global_id)
end
end
app.layout = layout_func
handler = Dash.make_handler(app)
request = HTTP.Request("GET", "/_dash-layout")
response = Dash.HttpHelpers.handle(handler, request)
@test response.status == 200
body_str = String(response.body)
@test body_str == JSON3.write(layout_func())
@test occursin("my_div2", body_str)
global_id = "my_div3"
response = Dash.HttpHelpers.handle(handler, request)
@test response.status == 200
body_str = String(response.body)
@test body_str == JSON3.write(layout_func())
@test occursin("my_div3", body_str)
end
@testset "assets" begin
app = dash(assets_folder = "assets")
app.layout = html_div() do
html_img(src = "assets/test.png")
end
@test Dash.get_assets_path(app) == joinpath(pwd(),"assets")
handler = Dash.make_handler(app)
request = HTTP.Request("GET", "/assets/test.png")
response = Dash.HttpHelpers.handle(handler, request)
@test response.status == 200
body_str = String(response.body)
request = HTTP.Request("GET", "/assets/wrong.png")
response = Dash.HttpHelpers.handle(handler, request)
@test response.status == 404
body_str = String(response.body)
end
@testset "PreventUpdate and no_update" begin
app = dash()
app.layout = html_div() do
html_div(10, id = "my-id"),
html_div(id = "my-div")
end
callback!(app, Output("my-div","children"), Input("my-id","children")) do value
throw(PreventUpdate())
end
handler = Dash.make_handler(app)
test_json = """{"output":"my-div.children","changedPropIds":["my-id.children"],"inputs":[{"id":"my-id","property":"children","value":10}]}"""
request = HTTP.Request("POST", "/_dash-update-component", [], Vector{UInt8}(test_json))
response = Dash.HttpHelpers.handle(handler, request)
@test response.status == 204
@test length(response.body) == 0
app = dash()
app.layout = html_div() do
html_div(10, id = "my-id"),
html_div(id = "my-div"),
html_div(id = "my-div2")
end
callback!(app, [Output("my-div","children"), Output("my-div2","children")], Input("my-id","children")) do value
no_update(), "test"
end
handler = Dash.make_handler(app)
test_json = """{"output":"..my-div.children...my-div2.children..","changedPropIds":["my-id.children"],"inputs":[{"id":"my-id","property":"children","value":10}]}"""
request = HTTP.Request("POST", "/_dash-update-component", [], Vector{UInt8}(test_json))
response = Dash.HttpHelpers.handle(handler, request)
@test response.status == 200
result = JSON3.read(String(response.body))
@test length(result[:response]) == 1
@test haskey(result[:response], Symbol("my-div2"))
@test !haskey(result[:response], Symbol("my-div"))
@test result[:response][Symbol("my-div2")][:children] == "test"
end
@testset "layout validation" begin
app = dash(assets_folder = "assets_compressed", compress = true)
@test_throws ErrorException make_handler(app)
app.layout = html_div(id="top") do
html_div(id="second") do
html_div("dsfsd", id = "inner1")
end,
html_div(id = "third") do
html_div("dsfsd", id = "inner2")
end
end
make_handler(app)
app.layout = html_div(id="top") do
html_div(id="second") do
html_div("dsfsd", id = "inner1")
end,
html_div(id = "second") do
html_div("dsfsd", id = "inner2")
end
end
@test_throws ErrorException make_handler(app)
end
@testset "Index by id" begin
app = dash()
app.layout = html_div() do
dcc_input(id = "my-id", value="initial value", type = "text"),
html_div(id = "my-div", children = [
html_div(),
"string",
html_div(id = "target")
]),
html_div(id = "my-div2")
end
@test app.layout["target"].id == "target"
@test app.layout["ups"] === nothing
end
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 4466 | using Test
using Dash
@testset "default args" begin
app = dash()
@test app.root_path == pwd()
@test isempty(app.config.external_stylesheets)
@test isempty(app.config.external_scripts)
@test app.config.requests_pathname_prefix == "/"
@test app.config.routes_pathname_prefix == "/"
@test app.config.assets_folder == "assets"
@test app.config.assets_url_path == "assets"
@test app.config.assets_ignore == ""
@test app.config.serve_locally == true
@test app.config.suppress_callback_exceptions == false
@test app.config.eager_loading == false
@test isempty(app.config.meta_tags)
@test app.index_string == Dash.default_index
@test app.config.assets_external_path === nothing
@test app.config.include_assets_files == true
@test app.config.show_undo_redo == false
end
@testset "setted args" begin
app = dash(; external_stylesheets=["https://test.css"])
@test app.config.external_stylesheets == ["https://test.css"]
app = dash(; external_stylesheets=[Dict("url" => "https://test.css", "integrity" => "integrity")])
@test app.config.external_stylesheets == [
Dict("url" => "https://test.css", "integrity" => "integrity")
]
app = dash(; external_scripts = ["http://test.js"])
@test app.config.external_scripts == ["http://test.js"]
app = dash(; external_scripts=[Dict("url" => "https://test.js", "integrity" => "integrity")])
@test app.config.external_scripts == [
Dict("url" => "https://test.js", "integrity" => "integrity")
]
app = dash(; url_base_pathname = "/base/")
@test app.config.url_base_pathname == "/base/"
@test app.config.requests_pathname_prefix == "/base/"
@test app.config.routes_pathname_prefix == "/base/"
app = dash(; requests_pathname_prefix = "/prefix/")
@test app.config.requests_pathname_prefix == "/prefix/"
@test app.config.routes_pathname_prefix == "/"
app = dash(; routes_pathname_prefix = "/prefix/")
@test app.config.requests_pathname_prefix == "/prefix/"
@test app.config.routes_pathname_prefix == "/prefix/"
app = dash(; requests_pathname_prefix = "/reg/prefix/", routes_pathname_prefix = "/prefix/")
@test app.config.requests_pathname_prefix == "/reg/prefix/"
@test app.config.routes_pathname_prefix == "/prefix/"
@test_throws ErrorException app = dash(; url_base_pathname = "/base")
@test_throws ErrorException app = dash(; url_base_pathname = "base/")
@test_throws ErrorException app = dash(; url_base_pathname = "/", routes_pathname_prefix = "/prefix/")
@test_throws ErrorException app = dash(; requests_pathname_prefix = "/prefix")
@test_throws ErrorException app = dash(; routes_pathname_prefix = "/prefix")
@test_throws ErrorException app = dash(; requests_pathname_prefix = "prefix/")
@test_throws ErrorException app = dash(; routes_pathname_prefix = "prefix/")
@test_throws ErrorException app = dash(; requests_pathname_prefix = "/reg/prefix/", routes_pathname_prefix = "/ix/")
app = dash(; assets_folder = "images")
@test app.config.assets_folder == "images"
app = dash(; assets_url_path = "/images")
@test app.config.assets_url_path == "images"
app = dash(; assets_ignore = "ignore")
@test app.config.assets_ignore == "ignore"
app = dash(; serve_locally = false)
@test app.config.serve_locally == false
app = dash(; suppress_callback_exceptions = true)
@test app.config.suppress_callback_exceptions == true
app = dash(; eager_loading = false)
@test app.config.eager_loading == false
app = dash(; meta_tags = [Dict(["name"=>"test", "content" => "content"])])
@test app.config.meta_tags == [Dict(["name"=>"test", "content" => "content"])]
@test_throws ErrorException app = dash(; index_string = "<html></html>")
app = dash(; index_string = "<html>{%app_entry%}{%config%}{%scripts%}</html>")
@test app.index_string == "<html>{%app_entry%}{%config%}{%scripts%}</html>"
app = dash(; assets_external_path = "external")
@test app.config.assets_external_path == "external"
app = dash(; include_assets_files = true)
@test app.config.include_assets_files == true
app = dash(; show_undo_redo = false)
@test app.config.show_undo_redo == false
@test app.config.prevent_initial_callbacks == false
app = dash(; prevent_initial_callbacks = true)
@test app.config.prevent_initial_callbacks == true
end
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 515 | #=
dev.jl is a draft file that I use during the development of a new functionality if I need to call some function, etc. and see how it works.
I.e. at the beginning of the development of a new functionality, I disable all tests except dev.jl,
after the overall architecture emerges, I disable dev.jl and start writing full-fledged tests
=#
using Test
using Dash
using JSON3
using HTTP
@testset "dev" begin
r = Dash.load_meta("dash_core_components")
c = Dash.generate_embeded_components()
println(c)
end
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 3320 | using Test
using Dash
using Dash:DevTools
@testset "DevTools creation" begin
@test true
tools = DevTools()
@test tools.ui == false
@test tools.props_check == false
@test tools.serve_dev_bundles == false
@test tools.hot_reload == false
@test tools.silence_routes_logging == false
@test tools.prune_errors == false
@test tools.hot_reload_interval ≈ 3.
@test tools.hot_reload_watch_interval ≈ 0.5
@test tools.hot_reload_max_retry ≈ 8
tools = DevTools(false)
@test tools.ui == false
@test tools.props_check == false
@test tools.serve_dev_bundles == false
@test tools.hot_reload == false
@test tools.silence_routes_logging == false
@test tools.prune_errors == false
@test tools.hot_reload_interval ≈ 3.
@test tools.hot_reload_watch_interval ≈ 0.5
@test tools.hot_reload_max_retry ≈ 8
tools = DevTools(true)
@test tools.ui == true
@test tools.props_check == true
@test tools.serve_dev_bundles == true
@test tools.hot_reload == true
@test tools.silence_routes_logging == true
@test tools.prune_errors == true
@test tools.hot_reload_interval ≈ 3.
@test tools.hot_reload_watch_interval ≈ 0.5
@test tools.hot_reload_max_retry ≈ 8
tools = DevTools(true,
props_check = false,
serve_dev_bundles = true,
hot_reload = false,
silence_routes_logging = true,
prune_errors = false,
hot_reload_interval = 2.2,
hot_reload_watch_interval = 0.1,
hot_reload_max_retry = 2
)
@test tools.ui == true
@test tools.props_check == false
@test tools.serve_dev_bundles == true
@test tools.hot_reload == false
@test tools.silence_routes_logging == true
@test tools.prune_errors == false
@test tools.hot_reload_interval ≈ 2.2
@test tools.hot_reload_watch_interval ≈ 0.1
@test tools.hot_reload_max_retry ≈ 2
end
@testset "DevTools end" begin
UI = false
ENV["DASH_UI"] = "False"
ENV["DASH_PROPS_CHECK"] = "False"
ENV["DASH_SERVE_DEV_BUNDLES"] = "False"
ENV["DASH_HOT_RELOAD"] = "False"
ENV["DASH_SILENCE_ROUTES_LOGGING"] = "false"
ENV["DASH_PRUNE_ERRORS"] = "0"
ENV["DASH_HOT_RELOAD_INTERVAL"] = "2.8"
ENV["DASH_HOT_RELOAD_WATCH_INTERVAL"] = "0.34"
ENV["DASH_HOT_RELOAD_MAX_RETRY"] = "7"
tools = DevTools(true)
@test tools.ui == false
@test tools.props_check == false
@test tools.serve_dev_bundles == false
@test tools.hot_reload == false
@test tools.silence_routes_logging == false
@test tools.prune_errors == false
@test tools.hot_reload_interval ≈ 2.8
@test tools.hot_reload_watch_interval ≈ 0.34
@test tools.hot_reload_max_retry ≈ 7
tools = DevTools(true, hot_reload_interval = 1.6)
@test tools.hot_reload_interval ≈ 1.6
delete!(ENV, "DASH_UI")
delete!(ENV, "DASH_PROPS_CHECK")
delete!(ENV, "DASH_SERVE_DEV_BUNDLES")
delete!(ENV, "DASH_HOT_RELOAD")
delete!(ENV, "DASH_SILENCE_ROUTES_LOGGING")
delete!(ENV, "DASH_PRUNE_ERRORS")
delete!(ENV, "DASH_HOT_RELOAD_INTERVAL")
delete!(ENV, "DASH_HOT_RELOAD_WATCH_INTERVAL")
delete!(ENV, "DASH_HOT_RELOAD_MAX_RETRY")
end
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 1697 | using Test
using Dash
using Dash:dash_env, @env_default!
@testset "env" begin
@test isnothing(dash_env("test"))
@test dash_env("test", "aaaa") == "aaaa"
@test isnothing(dash_env(Int, "test"))
@test dash_env(Int, "test", 10) == 10
ENV["DASH_STRING_TEST"] = "test_path"
@test dash_env("string_test", "aaaa") == "test_path"
@test_throws ArgumentError dash_env(Int, "string_test", "aaaa") == "test_path"
string_test = nothing
@env_default! string_test
@test string_test == "test_path"
string_test = "aaaa"
@env_default! string_test
@test string_test == "aaaa"
ENV["DASH_INT_TEST"] = "100"
@test dash_env("int_test", "aaaa") == "100"
@test dash_env(Int, "int_test", 50) == 100
int_test = nothing
@env_default! int_test Int
@test int_test == 100
int_test = 50
@env_default! int_test Int
@test int_test == 50
int_test2 = nothing
@env_default! int_test2 Int 40
@test int_test2 == 40
ENV["DASH_BOOL_TEST"] = "1"
@test dash_env(Bool, "bool_test", 50) == true
ENV["DASH_BOOL_TEST"] = "0"
@test dash_env(Bool, "bool_test", 50) == false
ENV["DASH_BOOL_TEST"] = "TRUE"
@test dash_env(Bool, "bool_test", 50) == true
ENV["DASH_BOOL_TEST"] = "FALSE"
@test dash_env(Bool, "bool_test", 50) == false
end
@testset "prefixes" begin
ENV["DASH_HOST"] = "localhost"
@test dash_env("host") == "localhost"
@test isnothing(dash_env("host", prefix = ""))
delete!(ENV, "PORT")
@test dash_env(Int64, "port", 8050, prefix = "") == 8050
ENV["PORT"] = "2001"
@test isnothing(dash_env(Int64, "port"))
@test dash_env(Int64, "port", prefix = "") == 2001
end
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 12362 | using Test
using HTTP
using Dash
using Dash: make_handler, compress_handler, process_resource, state_handler, HandlerState,
process_resource, Route, Router, add_route!, make_handler
using Dash.HttpHelpers: StaticRoute, DynamicRoute, try_handle, RouteHandler, _make_route
using CodecZlib
using MD5
struct TestState
setting::Bool
end
function path_request(path, method = "GET")
request = HTTP.Request(method, path)
r_path = HTTP.URI(request.target).path
return (r_path, request)
end
@testset "route" begin
route = DynamicRoute("/ddd/*/fff/*")
@test route.static_segments == ((1, "ddd"), (3, "fff"))
@test isempty(route.variables)
route = DynamicRoute("/ddd/<var1>/fff/<var2>")
@test route.static_segments == ((1,"ddd"), (3, "fff"))
route.variables.var1 == 2
route.variables.var2 == 4
route = _make_route("/fff/sss/ggg/vvvv")
@test route isa StaticRoute
@test route.url == "/fff/sss/ggg/vvvv"
route = _make_route("/fff/sss/<var1>/vvvv")
@test route isa DynamicRoute
route = _make_route("/test_req/test1")
handler = (req) -> HTTP.Response(200)
route_handler = RouteHandler(route, handler)
res = try_handle(route_handler, path_request("/test_req/test2")...)
@test isnothing(res)
res = try_handle(route_handler, path_request("/test_req/test1")...)
@test !isnothing(res)
@test res.status == 200
route = _make_route("/test_req/<var1>/test1")
handler = (req;kwargs...) ->
begin
tmp = String[]
for (k,v) in kwargs
@test v isa SubString
push!(tmp, string(k, "->",v))
end
HTTP.Response(200, join(tmp, ","))
end
route_handler = RouteHandler(route, handler)
res = try_handle(route_handler, path_request("/test_req/asdasd/test2")...)
@test isnothing(res)
res = try_handle(route_handler, path_request("/test_req/asdasd/test1")...)
@test res.status == 200
@test String(res.body) == "var1->asdasd"
res = try_handle(route_handler, path_request("/test_req/asdasd/test1/")...)
@test res.status == 200
@test String(res.body) == "var1->asdasd"
route = _make_route("/test_req/*/test1")
route_handler = RouteHandler(route, handler)
res = try_handle(route_handler, path_request("/test_req/asdasd/test2")...)
@test isnothing(res)
res = try_handle(route_handler, path_request("/test_req/asdasd/test1")...)
@test res.status == 200
@test String(res.body) == ""
route = _make_route("/test_req/*/test1/<var1>")
route_handler = RouteHandler(route, handler)
res = try_handle(route_handler, path_request("/test_req/asdasd/test1")...)
@test isnothing(res)
res = try_handle(route_handler, path_request("/test_req/asdasd/test1/ddd")...)
@test res.status == 200
@test String(res.body) == "var1->ddd"
route = _make_route("/test_req/<var2>/test1/<var1>")
route_handler = RouteHandler(route, handler)
res = try_handle(route_handler, path_request("/test_req/asdasd/test1")...)
@test isnothing(res)
res = try_handle(route_handler, path_request("/test_req/as/test1/ddd")...)
@test res.status == 200
@test String(res.body) == "var1->ddd,var2->as"
route = Route("GET", "/*") do req
return HTTP.Response(200)
end
res = try_handle(route, path_request("/test_req")...)
@test res.status == 200
res = try_handle(route, path_request("/test_req", "POST")...)
@test isnothing(res)
end
@testset "router" begin
router = Router()
add_route!(router, "/") do req
HTTP.Response(200, "index")
end
add_route!(router, "POST", "/test_post") do req
HTTP.Response(200, "test_post")
end
handler1 = (req;var1) -> HTTP.Response(200, "var1=$var1")
add_route!(handler1, router, "/var/<var1>/")
add_route!((req;var1, var2) -> HTTP.Response(200, "var1=$var1,var2=$var2"),
router, "/var/<var1>/<var2>/")
res = Dash.HttpHelpers.handle(router, HTTP.Request("GET",""))
@test res.status == 200
@test String(res.body) == "index"
res = Dash.HttpHelpers.handle(router, HTTP.Request("GET","/"))
@test res.status == 200
@test String(res.body) == "index"
res = Dash.HttpHelpers.handle(router, HTTP.Request("GET","/test_post"))
@test res.status == 404
res = Dash.HttpHelpers.handle(router, HTTP.Request("POST","/test_post"))
@test res.status == 200
@test String(res.body) == "test_post"
res = Dash.HttpHelpers.handle(router, HTTP.Request("POST","/var/"))
@test res.status == 404
res = Dash.HttpHelpers.handle(router, HTTP.Request("POST","/var/ass"))
@test res.status == 200
@test String(res.body) == "var1=ass"
res = Dash.HttpHelpers.handle(router, HTTP.Request("POST","/var/ass/"))
@test res.status == 200
@test String(res.body) == "var1=ass"
res = Dash.HttpHelpers.handle(router, HTTP.Request("POST","/var/ass/fff"))
@test res.status == 200
@test String(res.body) == "var1=ass,var2=fff"
res = Dash.HttpHelpers.handle(router, HTTP.Request("POST","/var/ass/fff/"))
@test res.status == 200
@test String(res.body) == "var1=ass,var2=fff"
res = Dash.HttpHelpers.handle(router, HTTP.Request("POST","/var/ass/fff/dd"))
@test res.status == 404
add_route!((req, param;var1) -> HTTP.Response(200, "$param, var1=$var1"),
router, "POST", "/<var1>")
res = Dash.HttpHelpers.handle(router, HTTP.Request("POST","/test_post"))
@test res.status == 200
@test String(res.body) == "test_post"
res = Dash.HttpHelpers.handle(router, HTTP.Request("POST","/test"), "aaa")
@test res.status == 200
@test String(res.body) == "aaa, var1=test"
res = Dash.HttpHelpers.handle(router, HTTP.Request("POST","/test/renderer/r.js"), "aaa")
@test res.status == 200
@test String(res.body) == "aaa, var1=test/renderer/r.js"
end
@testset "base_handler" begin
function structsequal(a::T, b::T)::Bool where T
for name in propertynames(a)
if getfield(a, name) != getfield(b, name)
return false
end
end
return true
end
base_handler = function(request, state)
@test request.target == "/test_path"
@test state isa TestState
@test state.setting
return HTTP.Response(200, "test1")
end
state = TestState(true)
test_handler = state_handler(base_handler, state)
test_request = HTTP.Request("GET", "/test_path")
res = Dash.HttpHelpers.handle(test_handler, test_request)
@test structsequal(res, test_handler(test_request)) #RequestHandlerFunction must be directly callable since HTTP.jl will use it
@test res.status == 200
@test String(res.body) == "test1"
@test startswith(HTTP.header(res, "Content-Type", ""), "text/plain")
@test parse(Int, HTTP.header(res, "Content-Length", "0")) == sizeof("test1")
base_handler_http = function(request, state)
@test request.target == "/test_path2"
@test state isa TestState
@test state.setting
return HTTP.Response(200, "<html></html>")
end
state = TestState(true)
test_handler = state_handler(base_handler_http, state)
test_request = HTTP.Request("GET", "/test_path2")
res = Dash.HttpHelpers.handle(test_handler, test_request)
@test structsequal(res, test_handler(test_request))
@test res.status == 200
@test String(res.body) == "<html></html>"
@test startswith(HTTP.header(res, "Content-Type", ""), "text/html")
@test parse(Int, HTTP.header(res, "Content-Length", "0")) == sizeof("<html></html>")
base_handler_js = function(request, state)
@test request.target == "/test_path3"
@test state isa TestState
@test state.setting
return HTTP.Response(200, ["Content-Type"=>"text/javascript"], body = "<html></html>")
end
test_handler = state_handler(base_handler_js, state)
test_request = HTTP.Request("GET", "/test_path3")
res = Dash.HttpHelpers.handle(test_handler, test_request)
@test structsequal(res, test_handler(test_request))
@test res.status == 200
@test String(res.body) == "<html></html>"
@test startswith(HTTP.header(res, "Content-Type", ""), "text/javascript")
@test parse(Int, HTTP.header(res, "Content-Length", "0")) == sizeof("<html></html>")
end
@testset "compression" begin
base_handler = function(request, state)
@test request.target == "/test_path"
@test state isa TestState
@test state.setting
return HTTP.Response(200, "test1")
end
state = TestState(true)
handler = compress_handler(state_handler(base_handler, state))
test_request = HTTP.Request("GET", "/test_path")
HTTP.setheader(test_request, "Accept-Encoding" => "gzip")
res = Dash.HttpHelpers.handle(handler, test_request)
@test res.status == 200
@test String(res.body) == "test1"
@test !HTTP.hasheader(res, "Content-Encoding")
base_handler = function(request, state)
@test request.target == "/test_big"
@test state isa TestState
@test state.setting
return HTTP.Response(200, repeat("<html></html>", 500))
end
test_request = HTTP.Request("GET", "/test_big")
HTTP.setheader(test_request, "Accept-Encoding" => "gzip")
handler = compress_handler(state_handler(base_handler, state))
res = Dash.HttpHelpers.handle(handler, test_request)
@test res.status == 200
@test HTTP.header(res, "Content-Encoding") == "gzip"
@test HTTP.header(res, "Content-Length") == string(sizeof(res.body))
@test transcode(GzipDecompressor, res.body) == Vector{UInt8}(repeat("<html></html>", 500))
end
@testset "resource handler" begin
test_registry = ResourcesRegistry(
dash_dependency = (
dev = ResourcePkg(
"dash_renderer",
"resources",
[
Resource(
relative_package_path = ["props.min.js"],
)
]
),
prod = ResourcePkg(
"dash_renderer",
"resources",
[
Resource(
relative_package_path = ["props.min.js"],
)
]
)
),
dash_renderer = ResourcePkg(
"dash_renderer",
"resources",
[
Resource(
relative_package_path = "dash-renderer/dash_renderer.js",
dev_package_path = "dash-renderer/dash_renderer.js",
)
]
)
)
test_app = dash()
handler = make_handler(test_app, test_registry)
request = HTTP.Request("GET", "/_dash-component-suites/dash_renderer/dash-renderer/dash_renderer.js")
resp = Dash.HttpHelpers.handle(handler, request)
@test resp.status == 200
@test String(resp.body) == "var a = [1,2,3,4,5,6]\n"
@test HTTP.hasheader(resp, "ETag")
@test HTTP.header(resp, "ETag") == bytes2hex(md5("var a = [1,2,3,4,5,6]\n"))
@test HTTP.header(resp, "Content-Type") == "application/javascript"
etag = HTTP.header(resp, "ETag")
HTTP.setheader(request, "If-None-Match"=>etag)
resp = Dash.HttpHelpers.handle(handler, request)
@test resp.status == 304
request = HTTP.Request("GET", "/_dash-component-suites/dash_renderer/props.min.js")
resp = Dash.HttpHelpers.handle(handler, request)
HTTP.setheader(request, "If-None-Match"=>bytes2hex(md5("var a = [1,2,3,4,5,6]")))
@test resp.status == 200
@test String(resp.body) == "var string = \"fffffff\"\n"
@test HTTP.hasheader(resp, "ETag")
@test HTTP.header(resp, "ETag") == bytes2hex(md5("var string = \"fffffff\"\n"))
etag = HTTP.header(resp, "ETag")
HTTP.setheader(request, "If-None-Match"=>etag)
resp = Dash.HttpHelpers.handle(handler, request)
@test resp.status == 304
request = HTTP.Request("GET", "/_dash-component-suites/dash_renderer/props.v1_2_3m2333123.min.js")
resp = Dash.HttpHelpers.handle(handler, request)
HTTP.setheader(request, "If-None-Match"=>bytes2hex(md5("var a = [1,2,3,4,5,6]")))
@test resp.status == 200
@test String(resp.body) == "var string = \"fffffff\"\n"
@test HTTP.hasheader(resp, "Cache-Control")
end
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 2368 | import HTTP, JSON3
using Test
using Dash
@testset "deps to json" begin
@test JSON3.write(ALL) == "[\"ALL\"]"
@test JSON3.write(MATCH) == "[\"MATCH\"]"
@test JSON3.write(ALLSMALLER) == "[\"ALLSMALLER\"]"
test_dep = Input((type = "test", index = MATCH), "value")
@test JSON3.write(test_dep) == """{"id":{"type":"test","index":["MATCH"]},"property":"value"}"""
end
@testset "json keys sorted" begin
test_dep = (type = "test", index = 1)
test_dep2 = (index = 1, type = "test")
test_json = Dash.sorted_json(test_dep)
test_JSON3 = Dash.sorted_json(test_dep2)
@test test_json == test_JSON3
@test test_json == """{"index":1,"type":"test"}"""
end
@testset "id equality" begin
@test ALL == ALL
@test ALL != MATCH
@test Input("a", "b") == Input("a", "b")
@test Input("a", "b") != Input("a", "c")
@test Input("a", "b") != Input("c", "b")
@test Input("a", "b") == Output("a", "b")
@test Input("a", "b") in [Output("a", "b"), Output("a", "c")]
#wilds
@test Input((a=1, b=2), "c") == Input((a=1, b=2), "c")
@test Input((a=1, b=2), "c") == Output((a=1, b=2), "c")
@test Input((a=1, b=2), "c") != Input((a=1, b=2), "e")
@test Input((a=1, b=2), "c") != Output((a=1, e=2), "c")
@test Input((a=1, b=2), "c") != Output((a=1, b=3), "c")
@test Input((a=ALL, b=2), "c") == Output((a=1, b=2), "c")
@test Input((a=ALL, b=3), "c") != Output((a=1, b=2), "c")
@test Input((a=ALL, b=2), "c") == Output((a=1, b=ALL), "c")
@test Input((a=MATCH, b=2), "c") == Output((a=1, b=2), "c")
@test Input((a=1, b=2), "c") == Output((a=MATCH, b=2), "c")
@test Input((a = ALLSMALLER, b=2), "c") != Output((a = MATCH, b=2), "c")
@test Input((a=ALL, b=2), "c") in [Output((a=1, b="ssss"), "c"), Output((a=1, b=2), "c")]
@test isequal(Output((a = ALL, b=2), "c"), Output((a = 1, b=2), "c"))
@test Output((a = ALL, b=2), "c") in [Output((a = 1, b=2), "c"), Output((a=2, b=2), "c")]
test = [Output((a = ALL, b=2), "c"), Output((a=2, b=2), "c"), Output((a = 1, b=2), "c")]
@test !Dash.check_unique(test)
test2 = [Output((a = 2, b=2), "c"), Output((a=2, b=2), "c"), Output((a = 1, b=2), "c")]
@test !Dash.check_unique(test2)
test2 = [Output((a = 2, b=2), "e"), Output((a=2, b=2), "c"), Output((a = 1, b=2), "c")]
@test Dash.check_unique(test2)
end
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 1381 | using Test
using Dash
using Dash: HandlerState, main_registry, start_reload_poll, enable_dev_tools!
import HTTP
import JSON3
@testset "reload state" begin
rm("assets/test2.png", force = true)
app = dash()
enable_dev_tools!(app, dev_tools_hot_reload_watch_interval = 1.)
app.layout = html_div()
state = HandlerState(app, main_registry())
start_reload_poll(state)
initial_hash = state.reload.hash
sleep(1)
@test length(state.reload.changed_assets) == 0
write("assets/test2.png", "")
sleep(2)
@test state.reload.hash != initial_hash
@test length(state.reload.changed_assets) == 1
@test length(state.reload.changed_assets) == 1
@test state.reload.changed_assets[1].url == "/assets/test2.png"
rm("assets/test2.png", force = true)
end
@testset "reload handler" begin
rm("assets/test2.css", force = true)
app = dash()
enable_dev_tools!(app, dev_tools_hot_reload = true, dev_tools_hot_reload_watch_interval = 1.)
app.layout = html_div()
handler = make_handler(app)
write("assets/test2.css", "")
sleep(2)
response = Dash.HttpHelpers.handle(handler, HTTP.Request("GET", "/_reload-hash"))
data = JSON3.read(response.body)
@test length(data.files) == 1
@test data.files[1].url == "/assets/test2.css"
@test data.files[1].is_css == true
rm("assets/test2.css", force = true)
end
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 18070 | using Test
using Dash: Resource, ResourcePkg, ResourcesRegistry,
AppResource, AppRelativeResource, AppExternalResource, AppCustomResource, AppAssetResource, ApplicationResources,
isdynamic, register_package!
@testset "lazy + dynamic" begin
test_resource = Resource(
relative_package_path = "test.js",
dynamic = true
)
@test test_resource.async == :lazy
@test isdynamic(test_resource, true)
@test isdynamic(test_resource, false)
test_resource = Resource(
relative_package_path = "test.js",
dynamic = false
)
@test test_resource.async == :none
@test !isdynamic(test_resource, true)
@test !isdynamic(test_resource, false)
@test_throws ArgumentError test_resource = Resource(
relative_package_path = "test.js",
dynamic = false,
async = :false
)
test_resource = Resource(
relative_package_path = "test.js",
async = :lazy
)
@test test_resource.async == :lazy
@test isdynamic(test_resource, true)
@test isdynamic(test_resource, false)
test_resource = Resource(
relative_package_path = "test.js",
async = :eager
)
@test test_resource.async == :eager
@test !isdynamic(test_resource, true)
@test isdynamic(test_resource, false)
end
@testset "application resources base registry" begin
test_registry = ResourcesRegistry(
dash_dependency = (
dev = ResourcePkg(
"dash_renderer",
"path",
[
Resource(
relative_package_path = ["path1.dev.js", "path2.dev.js"],
external_url = ["external_path1.dev.js", "external_path2.dev.js"]
)
]
),
prod = ResourcePkg(
"dash_renderer",
"path",
[
Resource(
relative_package_path = ["path1.prod.js", "path2.prod.js"],
external_url = ["external_path1.prod.js", "external_path2.prod.js"]
)
]
)
),
dash_renderer = ResourcePkg(
"dash_renderer",
"path",
[
Resource(
relative_package_path = "dash-renderer/dash_renderer.min.js",
dev_package_path = "dash-renderer/dash_renderer.dev.js",
external_url = "https://dash_renderer.min.js"
)
]
)
)
test_app = dash(include_assets_files = false)
app_resources = ApplicationResources(test_app, test_registry)
@test length(app_resources.css) == 0
@test length(app_resources.js) == 3
@test app_resources.js[1] isa AppRelativeResource
@test app_resources.js[1].namespace == "dash_renderer"
@test app_resources.js[1].relative_path == "path1.prod.js"
@test app_resources.js[2] isa AppRelativeResource
@test app_resources.js[2].namespace == "dash_renderer"
@test app_resources.js[2].relative_path == "path2.prod.js"
@test app_resources.js[end] isa AppRelativeResource
@test app_resources.js[end].namespace == "dash_renderer"
@test app_resources.js[end].relative_path == "dash-renderer/dash_renderer.min.js"
@test haskey(app_resources.files, "dash_renderer")
@test app_resources.files["dash_renderer"].base_path == "path"
@test "path1.prod.js" in app_resources.files["dash_renderer"].files
@test "path2.prod.js" in app_resources.files["dash_renderer"].files
@test "dash-renderer/dash_renderer.min.js" in app_resources.files["dash_renderer"].files
test_app = dash(include_assets_files = false)
enable_dev_tools!(test_app, debug = false, dev_tools_serve_dev_bundles = true)
app_resources = ApplicationResources(test_app, test_registry)
@test length(app_resources.css) == 0
@test length(app_resources.js) == 3
@test app_resources.js[1] isa AppRelativeResource
@test app_resources.js[1].namespace == "dash_renderer"
@test app_resources.js[1].relative_path == "path1.prod.js"
@test app_resources.js[2] isa AppRelativeResource
@test app_resources.js[2].namespace == "dash_renderer"
@test app_resources.js[2].relative_path == "path2.prod.js"
@test app_resources.js[end] isa AppRelativeResource
@test app_resources.js[end].namespace == "dash_renderer"
@test app_resources.js[end].relative_path == "dash-renderer/dash_renderer.dev.js"
@test haskey(app_resources.files, "dash_renderer")
@test app_resources.files["dash_renderer"].base_path == "path"
@test "path1.prod.js" in app_resources.files["dash_renderer"].files
@test "path2.prod.js" in app_resources.files["dash_renderer"].files
@test "dash-renderer/dash_renderer.dev.js" in app_resources.files["dash_renderer"].files
test_app = dash(include_assets_files = false)
enable_dev_tools!(test_app, debug = false, dev_tools_props_check = true, dev_tools_serve_dev_bundles = true)
app_resources = ApplicationResources(test_app, test_registry)
@test length(app_resources.css) == 0
@test length(app_resources.js) == 3
@test app_resources.js[1] isa AppRelativeResource
@test app_resources.js[1].namespace == "dash_renderer"
@test app_resources.js[1].relative_path == "path1.dev.js"
@test app_resources.js[2] isa AppRelativeResource
@test app_resources.js[2].namespace == "dash_renderer"
@test app_resources.js[2].relative_path == "path2.dev.js"
@test app_resources.js[end] isa AppRelativeResource
@test app_resources.js[end].namespace == "dash_renderer"
@test app_resources.js[end].relative_path == "dash-renderer/dash_renderer.dev.js"
@test haskey(app_resources.files, "dash_renderer")
@test app_resources.files["dash_renderer"].base_path == "path"
@test "path1.dev.js" in app_resources.files["dash_renderer"].files
@test "path2.dev.js" in app_resources.files["dash_renderer"].files
@test "dash-renderer/dash_renderer.dev.js" in app_resources.files["dash_renderer"].files
test_app = dash(serve_locally = false, include_assets_files = false)
app_resources = ApplicationResources(test_app, test_registry)
@test length(app_resources.css) == 0
@test length(app_resources.js) == 3
@test app_resources.js[1] isa AppExternalResource
@test app_resources.js[1].url == "external_path1.prod.js"
@test app_resources.js[2] isa AppExternalResource
@test app_resources.js[2].url == "external_path2.prod.js"
@test app_resources.js[end] isa AppExternalResource
@test app_resources.js[end].url == "https://dash_renderer.min.js"
@test isempty(app_resources.files)
end
@testset "application resources dynamic" begin
test_registry = ResourcesRegistry(
dash_dependency = (
dev = ResourcePkg(
"dash_renderer",
"path",
[
Resource(
relative_package_path = "path1.dev.js",
external_url = "external_path1.dev.js"
)
]
),
prod = ResourcePkg(
"dash_renderer",
"path",
[
Resource(
relative_package_path = "path1.prod.js",
external_url = "external_path1.prod.js"
)
]
)
),
dash_renderer = ResourcePkg(
"dash_renderer",
"path",
[
Resource(
relative_package_path = "dash-renderer/dash_renderer.min.js",
external_url = "https://dash_renderer.min.js"
),
Resource(
relative_package_path = "dash-renderer/dash_renderer.dyn.js",
external_url = "https://dash_renderer.dyn.js",
dynamic = true
),
Resource(
relative_package_path = "dash-renderer/dash_renderer.eag.js",
external_url = "https://dash_renderer.eag.js",
async = :eager
)
]
)
)
test_app = dash(include_assets_files = false)
app_resources = ApplicationResources(test_app, test_registry)
@test length(app_resources.css) == 0
@test length(app_resources.js) == 2
@test app_resources.js[2].relative_path == "dash-renderer/dash_renderer.min.js"
@test haskey(app_resources.files, "dash_renderer")
@test app_resources.files["dash_renderer"].base_path == "path"
@test "path1.prod.js" in app_resources.files["dash_renderer"].files
@test "dash-renderer/dash_renderer.min.js" in app_resources.files["dash_renderer"].files
@test "dash-renderer/dash_renderer.dyn.js" in app_resources.files["dash_renderer"].files
@test "dash-renderer/dash_renderer.eag.js" in app_resources.files["dash_renderer"].files
test_app = dash(eager_loading = true, include_assets_files = false)
app_resources = ApplicationResources(test_app, test_registry)
@test length(app_resources.css) == 0
@test length(app_resources.js) == 3
@test app_resources.js[2].relative_path == "dash-renderer/dash_renderer.min.js"
@test app_resources.js[3].relative_path == "dash-renderer/dash_renderer.eag.js"
end
@testset "application resources components" begin
test_registry = ResourcesRegistry(
dash_dependency = (
dev = ResourcePkg(
"dash_renderer",
"path",
[
Resource(
relative_package_path = "path1.dev.js",
external_url = "external_path1.dev.js"
)
]
),
prod = ResourcePkg(
"dash_renderer",
"path",
[
Resource(
relative_package_path = "path1.prod.js",
external_url = "external_path1.prod.js"
)
]
)
),
dash_renderer = ResourcePkg(
"dash_renderer",
"path",
[
Resource(
relative_package_path = "dash-renderer/dash_renderer.min.js",
external_url = "https://dash_renderer.min.js"
),
]
)
)
register_package!(test_registry,
ResourcePkg(
"comps",
"comps_path",
[
Resource(
relative_package_path = "comp.js"
),
Resource(
relative_package_path = "comp.dyn.js",
dynamic = true
),
Resource(
relative_package_path = "comp.css",
type = :css
)
]
)
)
test_app = dash(include_assets_files = false)
app_resources = ApplicationResources(test_app, test_registry)
@test length(app_resources.css) == 1
@test length(app_resources.js) == 3
@test app_resources.js[1].relative_path == "path1.prod.js"
@test app_resources.js[2].namespace == "comps"
@test app_resources.js[2].relative_path == "comp.js"
@test app_resources.js[end].relative_path == "dash-renderer/dash_renderer.min.js"
@test haskey(app_resources.files, "comps")
@test app_resources.files["comps"].base_path == "comps_path"
@test "comp.js" in app_resources.files["comps"].files
@test "comp.dyn.js" in app_resources.files["comps"].files
@test "comp.css" in app_resources.files["comps"].files
end
@testset "application resources external" begin
test_registry = ResourcesRegistry(
dash_dependency = (
dev = ResourcePkg(
"dash_renderer",
"path",
[
Resource(
relative_package_path = "path1.dev.js",
external_url = "external_path1.dev.js"
)
]
),
prod = ResourcePkg(
"dash_renderer",
"path",
[
Resource(
relative_package_path = "path1.prod.js",
external_url = "external_path1.prod.js"
)
]
)
),
dash_renderer = ResourcePkg(
"dash_renderer",
"path",
[
Resource(
relative_package_path = "dash-renderer/dash_renderer.min.js",
external_url = "https://dash_renderer.min.js"
),
]
)
)
external_css = ["test.css", Dict("rel"=>"stylesheet", "href"=>"test.css")]
external_js = ["test.js", Dict("crossorigin"=>"anonymous", "src"=>"test.js")]
test_app = dash(external_stylesheets = external_css, include_assets_files = false, external_scripts = external_js)
app_resources = ApplicationResources(test_app, test_registry)
@test length(app_resources.css) == 2
@test length(app_resources.js) == 4
@test app_resources.js[1].relative_path == "path1.prod.js"
@test app_resources.js[end].relative_path == "dash-renderer/dash_renderer.min.js"
@test app_resources.css[1] isa AppExternalResource
@test app_resources.css[1].url == "test.css"
@test app_resources.css[2] isa AppCustomResource
@test app_resources.css[2].params["href"] == "test.css"
@test app_resources.css[2].params["rel"] == "stylesheet"
@test app_resources.js[2] isa AppExternalResource
@test app_resources.js[2].url == "test.js"
@test app_resources.js[3] isa AppCustomResource
@test app_resources.js[3].params["src"] == "test.js"
@test app_resources.js[3].params["crossorigin"] == "anonymous"
end
@testset "application resources assets" begin
test_registry = ResourcesRegistry(
dash_dependency = (
dev = ResourcePkg(
"dash_renderer",
"path",
[
]
),
prod = ResourcePkg(
"dash_renderer",
"path",
[
]
)
),
dash_renderer = ResourcePkg(
"dash_renderer",
"path",
[
]
)
)
test_app = dash(assets_folder = "assets_include")
app_resources = ApplicationResources(test_app, test_registry)
@test length(app_resources.css) == 1
@test length(app_resources.js) == 4
@test app_resources.favicon.path == "favicon.ico"
@test all(app_resources.css) do r
r isa AppAssetResource
end
@test app_resources.css[1].path == "test.css"
@test all(app_resources.js) do r
r isa AppAssetResource
end
@test any(app_resources.js) do r
r.path == "test1.js"
end
@test any(app_resources.js) do r
r.path == "test2.js"
end
@test any(app_resources.js) do r
r.path == "sub/sub1.js"
end
@test any(app_resources.js) do r
r.path == "sub/sub2.js"
end
test_app = dash(assets_folder = "assets_include", include_assets_files = false)
app_resources = ApplicationResources(test_app, test_registry)
@test length(app_resources.css) == 0
@test length(app_resources.js) == 0
@test app_resources.favicon === nothing
test_app = dash(assets_folder = "assets_include", serve_locally = false)
app_resources = ApplicationResources(test_app, test_registry)
@test length(app_resources.css) == 1
@test length(app_resources.js) == 4
@test app_resources.favicon.path == "favicon.ico"
@test all(app_resources.css) do r
r isa AppAssetResource
end
@test app_resources.css[1].path == "test.css"
@test all(app_resources.js) do r
r isa AppAssetResource
end
@test any(app_resources.js) do r
r.path == "test1.js"
end
@test any(app_resources.js) do r
r.path == "test2.js"
end
@test any(app_resources.js) do r
r.path == "sub/sub1.js"
end
@test any(app_resources.js) do r
r.path == "sub/sub2.js"
end
test_app = dash(assets_folder = "assets_include", serve_locally = false, assets_external_path = "http://ext/")
app_resources = ApplicationResources(test_app, test_registry)
@test length(app_resources.css) == 1
@test length(app_resources.js) == 4
@test app_resources.favicon.path == "favicon.ico"
@test all(app_resources.css) do r
r isa AppExternalResource
end
@test app_resources.css[1].url == "http://ext/test.css"
@test all(app_resources.js) do r
r isa AppExternalResource
end
@test any(app_resources.js) do r
r.url == "http://ext/test1.js"
end
@test any(app_resources.js) do r
r.url == "http://ext/test2.js"
end
@test any(app_resources.js) do r
r.url == "http://ext/sub/sub1.js"
end
@test any(app_resources.js) do r
r.url == "http://ext/sub/sub2.js"
end
test_app = dash(assets_folder = "assets_include", assets_ignore = ".*1")
app_resources = ApplicationResources(test_app, test_registry)
@test length(app_resources.css) == 1
@test length(app_resources.js) == 2
@test app_resources.favicon.path == "favicon.ico"
@test all(app_resources.css) do r
r isa AppAssetResource
end
@test app_resources.css[1].path == "test.css"
@test all(app_resources.js) do r
r isa AppAssetResource
end
@test !any(app_resources.js) do r
r.path == "test1.js"
end
@test any(app_resources.js) do r
r.path == "test2.js"
end
@test !any(app_resources.js) do r
r.path == "sub/sub1.js"
end
@test any(app_resources.js) do r
r.path == "sub/sub2.js"
end
end
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 374 | include("env.jl")
include("resources.jl")
include("devtools.jl")
include("dash_creation.jl")
include("handlers.jl")
include("config_functional.jl")
include("utils.jl")
include("context.jl")
include("core.jl")
include("misc.jl")
include("callbacks.jl")
include("components_utils.jl")
include("table_format.jl")
include("reload_hash.jl")
include("aqua.jl")
#include("dev.jl")
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 5863 | using Test
using Dash
using Dash.TableFormat
import JSON3
@testset "named values" begin
@test TableFormat.Align.left.value == "<"
a = TableFormat.Align.default
@test a == TableFormat.Align.default
@test TableFormat.possible_values(TableFormat.Align) == "Align.default, Align.left, Align.right, Align.center, Align.right_sign"
@test a != TableFormat.Align.left
@test a != TableFormat.Scheme.default
end
@testset "specifier" begin
f = Format()
@test f.specifier[:align] == TableFormat.Align.default.value
TableFormat.align!(f, TableFormat.Align.left)
@test f.specifier[:align] == TableFormat.Align.left.value
@test_throws ArgumentError TableFormat.align!(f, TableFormat.Group.no)
TableFormat.fill!(f, '-')
@test f.specifier[:fill] == "-"
TableFormat.fill!(f, "+")
@test f.specifier[:fill] == "+"
@test_throws ArgumentError TableFormat.fill!(f, "++")
TableFormat.group!(f, TableFormat.Group.yes)
@test f.specifier[:group] == TableFormat.Group.yes.value
TableFormat.group!(f, true)
@test f.specifier[:group] == TableFormat.Group.yes.value
TableFormat.group!(f, false)
@test f.specifier[:group] == TableFormat.Group.no.value
@test_throws ArgumentError TableFormat.group!(f, "ffff")
TableFormat.padding!(f, TableFormat.Padding.yes)
@test f.specifier[:padding] == TableFormat.Padding.yes.value
TableFormat.padding!(f, true)
@test f.specifier[:padding] == TableFormat.Padding.yes.value
TableFormat.padding!(f, false)
@test f.specifier[:padding] == TableFormat.Padding.no.value
@test_throws ArgumentError TableFormat.padding!(f, "ffff")
TableFormat.padding_width!(f, 100)
@test f.specifier[:width] == 100
TableFormat.padding_width!(f, nothing)
@test f.specifier[:width] == ""
@test_throws ArgumentError TableFormat.padding_width!(f, "ffff")
@test_throws ArgumentError TableFormat.padding_width!(f, -10)
TableFormat.precision!(f, 3)
@test f.specifier[:precision] == ".3"
TableFormat.precision!(f, nothing)
@test f.specifier[:precision] == ""
@test_throws ArgumentError TableFormat.precision!(f, "ffff")
@test_throws ArgumentError TableFormat.precision!(f, -10)
@test f.specifier[:type] == TableFormat.Scheme.default.value
TableFormat.scheme!(f, TableFormat.Scheme.decimal)
@test f.specifier[:type] == TableFormat.Scheme.decimal.value
@test_throws ArgumentError TableFormat.scheme!(f, "ccc")
@test f.specifier[:sign] == TableFormat.Sign.default.value
TableFormat.sign!(f, TableFormat.Sign.negative)
@test f.specifier[:sign] == TableFormat.Sign.negative.value
@test_throws ArgumentError TableFormat.sign!(f, "ccc")
@test f.specifier[:symbol] == TableFormat.DSymbol.no.value
TableFormat.symbol!(f, TableFormat.DSymbol.yes)
@test f.specifier[:symbol] == TableFormat.DSymbol.yes.value
@test_throws ArgumentError TableFormat.symbol!(f, "ccc")
@test f.specifier[:trim] == TableFormat.Trim.no.value
TableFormat.trim!(f, TableFormat.Trim.yes)
@test f.specifier[:trim] == TableFormat.Trim.yes.value
TableFormat.trim!(f, false)
@test f.specifier[:trim] == TableFormat.Trim.no.value
@test_throws ArgumentError TableFormat.trim!(f, "ccc")
end
@testset "locale" begin
f = Format()
@test isempty(f.locale)
TableFormat.symbol_prefix!(f, "lll")
@test haskey(f.locale, :symbol)
@test f.locale[:symbol][1] == "lll"
@test f.locale[:symbol][2] == ""
TableFormat.symbol_prefix!(f, "rrr")
@test f.locale[:symbol][1] == "rrr"
@test f.locale[:symbol][2] == ""
f = Format()
@test isempty(f.locale)
TableFormat.symbol_suffix!(f, "lll")
@test haskey(f.locale, :symbol)
@test f.locale[:symbol][1] == ""
@test f.locale[:symbol][2] == "lll"
TableFormat.symbol_suffix!(f, "rrr")
@test f.locale[:symbol][1] == ""
@test f.locale[:symbol][2] == "rrr"
TableFormat.symbol_prefix!(f, "kkk")
@test f.locale[:symbol][1] == "kkk"
@test f.locale[:symbol][2] == "rrr"
f = Format()
TableFormat.decimal_delimiter!(f, '|')
@test f.locale[:decimal] == "|"
TableFormat.group_delimiter!(f, ';')
@test f.locale[:group] == ";"
TableFormat.groups!(f, [3,3,3])
@test f.locale[:grouping] == [3,3,3]
TableFormat.groups!(f, [5])
@test f.locale[:grouping] == [5]
@test_throws ArgumentError TableFormat.groups!(f, Int[])
@test_throws ArgumentError TableFormat.groups!(f, Int[-1,2])
end
@testset "nully & prefix" begin
f = Format()
TableFormat.nully!(f, "gggg")
@test f.nully == "gggg"
TableFormat.si_prefix!(f, TableFormat.Prefix.femto)
@test f.prefix == TableFormat.Prefix.femto.value
end
@testset "Format creation" begin
f = Format(
align = Align.left,
fill = "+",
group = true,
padding = Padding.yes,
padding_width = 10,
precision = 2,
scheme = Scheme.decimal,
sign = Sign.negative,
symbol = DSymbol.yes,
trim = Trim.yes,
symbol_prefix = "tt",
symbol_suffix = "kk",
decimal_delimiter = ";",
group_delimiter = ",",
groups = [2, 2],
nully = "f",
si_prefix = Prefix.femto
)
@test f.specifier == Dict{Symbol, Any}(
:align => Align.left.value,
:fill => "+",
:group => Group.yes.value,
:padding => Padding.yes.value,
:width => 10,
:precision => ".2",
:type => Scheme.decimal.value,
:sign => Sign.negative.value,
:symbol => DSymbol.yes.value,
:trim => Trim.yes.value
)
@test f.nully == "f"
@test f.prefix == Prefix.femto.value
@test f.locale[:symbol] == ["tt", "kk"]
@test f.locale[:decimal] == ";"
@test f.locale[:group] == ","
@test f.locale[:grouping] == [2,2]
end
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 1412 | using Test
using Dash: interpolate_string, build_fingerprint, parse_fingerprint_path
@testset "interpolate_string" begin
test_str = """
{%head%}
blah blah blah blah blah blah blah blah blah blah
{%middle%}
da da da da da da da da da da da da da {%da%} da
end
"""
inter = interpolate_string(test_str, head="hd", middle = :mmmm, da = 10)
@test inter == """
hd
blah blah blah blah blah blah blah blah blah blah
mmmm
da da da da da da da da da da da da da 10 da
end
"""
end
@testset "fingerprint" begin
test_url = "/test/test_test/file.js"
fp = build_fingerprint(test_url, "1.3.4", 3112231)
@test fp == "/test/test_test/file.v1_3_4m3112231.js"
(origin, is_fp) = parse_fingerprint_path(fp)
@test is_fp
@test origin == test_url
test_url = "/test/test_test/file.2.3.js"
fp = build_fingerprint(test_url, "1.3.4", 3112231)
@test fp == "/test/test_test/file.v1_3_4m3112231.2.3.js"
(origin, is_fp) = parse_fingerprint_path(fp)
@test is_fp
@test origin == test_url
(origin, is_fp) = parse_fingerprint_path(test_url)
@test !is_fp
@test origin == test_url
end
@testset "parse_includes" begin
files = Dash.parse_includes(joinpath("hot_reload", "app.jl"))
for f in ["app.jl", "file1.jl", "file2.jl", "file3.jl", "file4.jl"]
@test abspath(joinpath("hot_reload", f)) in files
end
end
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 66 | include("file1.jl")
module TestModule
include("file2.jl")
end
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 569 | using Dash
using PlotlyBase
app = dash()
app.layout = html_div() do
dcc_graph(id = "graph",
figure = Plot(scatter(x=1:10, y = 1:10))
),
html_button("draw", id = "draw"),
html_div("", id = "status")
end
callback!(app, Output("graph", "figure"), Output("status", "children"), Input("draw", "n_clicks")) do nclicks
plot = isnothing(nclicks) ?
no_update() :
Plot([scatter(x=1:10, y = 1:10), scatter(x=1:10, y = 1:2:20)])
status = isnothing(nclicks) ? "first" : "second"
return (plot, status)
end
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 561 | using Dash
using PlotlyJS
app = dash()
app.layout = html_div() do
dcc_graph(id = "graph",
figure = plot(scatter(x=1:10, y = 1:20))
),
html_button("draw", id = "draw"),
html_div("", id = "status")
end
callback!(app, Output("graph", "figure"), Output("status", "children"), Input("draw", "n_clicks")) do nclicks
p = isnothing(nclicks) ?
no_update() :
plot([scatter(x=1:10, y = 1:10), scatter(x=1:10, y = 1:2:20)])
status = isnothing(nclicks) ? "first" : "second"
return (p, status)
end
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 501 | using Dash
using Plots
plotly()
app = dash()
app.layout = html_div() do
dcc_graph(id = "graph", figure = plot((1:10, 1:10))),
html_button("draw", id = "draw"),
html_div("", id = "status")
end
callback!(app,
Output("graph", "figure"),
Output("status", "children"),
Input("draw", "n_clicks")) do nclicks
return if isnothing(nclicks)
no_update(), "first"
else
plot([(1:10, 1:10), (1:10, 1:2:20)]), "second"
end
end
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 503 | using Dash
using Plots
plotlyjs()
app = dash()
app.layout = html_div() do
dcc_graph(id = "graph", figure = plot((1:10, 1:10))),
html_button("draw", id = "draw"),
html_div("", id = "status")
end
callback!(app,
Output("graph", "figure"),
Output("status", "children"),
Input("draw", "n_clicks")) do nclicks
return if isnothing(nclicks)
no_update(), "first"
else
plot([(1:10, 1:10), (1:10, 1:2:20)]), "second"
end
end
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 244 | using Dash
app = dash(show_undo_redo=true)
app.layout = html_div() do
dcc_input(id="a"),
html_div(id="b")
end
callback!(app,
Output("b","children"),
Input("a","value")
) do inputValue
return inputValue
end
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 128 | using Dash
app = dash()
app.layout = html_div() do
html_div("Hello Dash.jl testing", id="container")
end
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 182 | using Dash
app = dash(meta_tags = [Dict(["name"=>"description", "content" => "some content"])])
app.layout = html_div(children = "Hello world!", id = "hello-div")
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 249 | using Dash
app = dash(meta_tags = [Dict(["charset"=>"ISO-8859-1", "keywords"=>"dash,pleasant,productive", "http-equiv"=>"content-type", "content"=>"text/html"])])
app.layout = html_div(children = "Hello world!", id = "hello-div")
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 108 | using Dash
app = dash()
app.layout = html_div(children = "Hello world!", id = "hello-div")
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 141 | using Dash
app = dash(;update_title = "... computing !")
app.layout = html_div(children = "Hello world!", id = "hello-div")
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 126 | using Dash
app = dash(;update_title = "")
app.layout = html_div(children = "Hello world!", id = "hello-div")
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 444 | using Dash
app = dash()
app.layout = html_div() do
dcc_input(id="input", value = "initial value"),
html_div() do
html_div(
[
1.5,
nothing,
"string",
html_div(id="output")
]
)
end
end
call_count = 0
callback!(app,
Output("output","children"),
Input("input","value")
) do value
return value
end
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 489 | using Dash
app = dash()
app.layout = html_div() do
dcc_input(id="input", value = "initial value"),
html_div(id="output")
end
callback!(app, Output("output","children"), Input("input","value")) do input
return html_div() do
dcc_input(id = "sub-input-1", value = "sub input initial value"),
html_div(id = "sub-output-1")
end
end
callback!(app, Output("sub-output-1","children"), Input("sub-input-1","value")) do value
return value
end
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 469 | using Dash
app = dash()
app.layout = html_div() do
dcc_tabs() do
dcc_tab() do
html_button(id="btn", children = "Update Input"),
html_div(id = "output", children = ["Hello"])
end,
dcc_tab() do
html_div("test")
end
end
end
callback!(app, Output("output","children"), Input("btn","n_clicks")) do n_clicks
isnothing(n_clicks) && throw(PreventUpdate())
return "Bye"
end
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 672 | using Dash
outputs = [
[nothing, ""],
["a string", "a string"],
[123, "123"],
[123.45, "123.45"],
[[6, 7, 8], "678"],
[["a", "list", "of", "strings"], "alistofstrings"],
[["strings", 2, "numbers"], "strings2numbers"],
[["a string", html_div("and a div")], "a string\nand a div"],
]
app = dash()
app.layout = html_div() do
html_button(id="btn", children = "Update Input"),
html_div(id = "out", children = "init")
end
callback!(app, Output("out","children"), Input("btn","n_clicks")) do n_clicks
(isnothing(n_clicks) || n_clicks > length(outputs)) && throw(PreventUpdate())
return outputs[n_clicks][1]
end
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 339 | using Dash
app = dash()
app.layout = html_div() do
dcc_input(id="input", value = "initial value"),
html_div(id="output1"),
html_div(id="output2")
end
callback!(app, Output("output1","children"), Output("output2","children"), Input("input","value")) do input
return ("$input first", "$input second")
end
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 653 | using Dash
app = dash()
app.layout = html_div() do
dcc_dropdown(id = "input",
options = [
(label="regular", value="regular"),
(label="prevent", value="prevent"),
(label="no_update", value="no_update"),
]
),
html_div(id="output"),
html_div(id="regular_output")
end
callback!(app, Output("regular_output","children"), Input("input","value")) do input
return input
end
callback!(app, Output("output","children"), Input("input","value")) do input
input == "prevent" && throw(PreventUpdate())
input == "no_update" && return no_update()
return input
end
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 878 |
using Dash
app = dash()
app.layout = html_div() do
dcc_dropdown(id = "input",
options = [
(label="regular", value="regular"),
(label="prevent", value="prevent"),
(label="no_update1", value="no_update1"),
(label="no_update2", value="no_update2"),
]
),
html_div(id="output1"),
html_div(id="output2"),
html_div(id="regular_output")
end
callback!(app, Output("regular_output","children"), Input("input","value")) do input
return input
end
callback!(app, Output("output1","children"), Output("output2","children"), Input("input","value")) do input
input == "prevent" && throw(PreventUpdate())
if input == "no_update1"
return (no_update(), input)
end
if input == "no_update2"
return (input, no_update())
end
return (input, input)
end
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 271 |
using Dash
app = dash()
app.layout = html_div() do
dcc_input(id="input", value = "initial value"),
html_div(id = "output")
end
callback!(app,
[Output("output","children")],
Input("input","value")
) do value
return (value,)
end
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 464 | using Dash
app = dash()
app.layout = html_div() do
dcc_input(id="input", value = "initial value"),
dcc_input(id="input2", value = "prevented"),
html_div("initial",id="output")
end
callback!(app,
Output("input2","value"),
Input("input","value"),
prevent_initial_call = true
) do value
return value
end
callback!(app,
Output("output","children"),
Input("input2","value")
) do value
return value
end
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 520 | using HTTP
using Dash
app = dash()
app.layout = html_div() do
dcc_input(id = "input", value = "ab"),
html_div(id = "output")
end
callback!(app,
Output("output", "children"),
Input("input", "value")
) do value
cookie = HTTP.Cookie("dash_cookie", value * " - cookie")
cookie_str = HTTP.Cookies.stringify(cookie)
println(cookie_str)
http_response = callback_context().response
push!(http_response.headers, "Set-Cookie"=>cookie_str)
return value * " - output"
end
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 525 | using Dash
app = dash()
btns = ["btn-$i" for i in 1:6]
app.layout = html_div() do
html_div([html_button(btn, id = btn) for btn in btns]),
html_div(id = "output")
end
callback!(app,
Output("output", "children"),
[Input(btn, "n_clicks") for btn in btns]
) do args...
isempty(callback_context().triggered) && throw(PreventUpdate())
trigger = callback_context().triggered[1]
name = split(trigger.prop_id, ".")[1]
return "Just clicked $(name) for the $(trigger.value) time!"
end
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 1730 | using Dash
function fibonacci_app(clientside)
app = dash()
app.layout = html_div() do
dcc_input(id = "n", type = "number", min = 0, max = 10, value = 4),
html_div(id = "series"),
html_div(id = "sum")
end
get_n(n::Int) = n
function get_n(n::String)
try
return parse(Int, n)
catch
return 0
end
end
get_n(n) = 0
callback!(app, Output("series", "children"),Input("n", "value")) do n
return [html_div(id=(i = i,)) for i in 1:get_n(n)]
end
if clientside
callback!(
"""
function(vals) {
var len = vals.length;
return len < 2 ? len : +(vals[len - 1] || 0) + +(vals[len - 2] || 0);
}
""", app,
Output((i = MATCH,), "children"),
Input((i = ALLSMALLER,), "children")
)
callback!(
"""
function(vals) {
var sum = vals.reduce(function(a, b) { return +a + +b; }, 0);
return vals.length + ' elements, sum: ' + sum;
}
""", app,
Output("sum", "children"),
Input((i = ALL,), "children"),
)
else
callback!(app,
Output((i = MATCH,), "children"), Input((i = ALLSMALLER,), "children")
) do prev
(length(prev) < 2) && return length(prev)
return prev[end] + prev[end - 1]
end
callback!(app, Output("sum", "children"), Input((i = ALL,), "children")) do seq
seq_sum = isempty(seq) ? 0 : sum(get_n, seq)
return "$(length(seq)) elements, sum: $(seq_sum)"
end
end
return app
end
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 61 | include("todo_app.jl")
app = todo_app(false)
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 60 | include("todo_app.jl")
app = todo_app(true)
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 71 | include("fibonacci_app.jl")
app = fibonacci_app(false)
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 70 | include("fibonacci_app.jl")
app = fibonacci_app(true)
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 964 | using Dash
app = dash(suppress_callback_exceptions = true)
app.layout = html_div() do
html_button("Add Filter", id="add-filter", n_clicks=0),
html_div([], id="container")
end
callback!(app,
Output("container", "children"),
Input("add-filter", "n_clicks"),
State("container", "children")
) do n_clicks, children
new_element = html_div() do
dcc_dropdown(
id = (type = "dropdown", index = n_clicks),
options = [(label = i, value = i) for i in ["NYC", "MTL", "LA", "TOKYO"]]
),
html_div(
id = (type = "output", index = n_clicks)
)
end
return vcat(children, new_element)
end
callback!(app,
Output((type = "output", index = MATCH), "children"),
Input((type = "dropdown", index = MATCH), "value"),
State((type = "dropdown", index = MATCH), "id"),
) do value, id
return html_div("Dropdown $(id.index) = $(value)")
end
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 1249 | using Dash
app = dash()
app.layout = html_div() do
dcc_input(id=(type = "input", index = 1), value="input-1"),
html_div(id="container"),
html_div(id="output-outer"),
html_button("Show content", id="btn")
end
callback!(app, Output("container", "children"), Input("btn", "n_clicks")) do n
if !isnothing(n) && n > 0
return html_div(
[
dcc_input(id=(type = "input", index = 2), value="input-2"),
html_div(id="output-inner"),
]
)
else
return "No content initially"
end
end
function trigger_info()
triggered = callback_context().triggered
trig_string = ""
prop_ids = ""
if isempty(triggered)
trig_string = "Falsy"
else
trig_string = "Truthy"
prop_ids = join(getproperty.(triggered, :prop_id), ", ")
end
return "triggered is $trig_string with prop_ids $prop_ids"
end
callback!(app,
Output("output-inner", "children"),
Input((type = "input", index = ALL), "value"),
) do wc_inputs
return trigger_info()
end
callback!(app,
Output("output-outer", "children"),
Input((type = "input", index = ALL), "value")
) do value
return trigger_info()
end
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 3572 | using Dash
function todo_app(content_callback)
app = dash()
content = html_div() do
html_div("Dash To-Do list"),
dcc_input(id="new-item"),
html_button("Add", id="add"),
html_button("Clear Done", id="clear-done"),
html_div(id="list-container"),
html_hr(),
html_div(id="totals")
end
if content_callback
app.layout = html_div() do
html_div(id="content"),
dcc_location(id="url")
end
callback!(app, Output("content", "children"), Input("url", "pathname")) do v
return content
end
else
app.layout = content
end
style_todo = Dict("display" => "inline", "margin" =>"10px")
style_done = Dict("textDecoration" => "line-through", "color" => "#888")
merge!(style_done, style_todo)
callback!(app, Output("list-container", "children"), Output("new-item", "value"),
Input("add", "n_clicks"),
Input("new-item", "n_submit"),
Input("clear-done", "n_clicks"),
State("new-item", "value"),
State((item = ALL,), "children"),
State((item = ALL, action = "done"), "value"),
) do add, add2, clear, new_item, items, items_done
triggered = [t.prop_id for t in callback_context().triggered]
adding = any((id)->id in ("add.n_clicks", "new-item.n_submit"), triggered)
clearing = any((id)->id == "clear-done.n_clicks", triggered)
new_spec = Vector{Any}()
push!.(Ref(new_spec),
Iterators.filter(zip(items, items_done)) do (text, done)
return !(clearing && !isempty(done))
end
)
adding && push!(new_spec, (new_item, []))
new_list = [
html_div(style = (clear = "both",)) do
dcc_checklist(
id=(item = i, action = "done"),
options=[(label = "", value = "done")],
value=done,
style=(display = "inline",),
),
html_div(
text, id=(item = i,), style= !isempty(done) ? style_done : style_todo
),
html_div(id=(item = i, preceding = true), style=style_todo)
end
for (i, (text, done)) in enumerate(new_spec)
]
return [new_list, adding ? "" : new_item]
end
callback!(app,
Output((item = MATCH,), "style"),
Input((item = MATCH, action = "done"), "value")
) do done
println(done)
return !isempty(done) ? style_done : style_todo
end
callback!(app,
Output((item = MATCH, preceding = true), "children"),
Input((item = ALLSMALLER, action = "done"), "value"),
Input((item = MATCH, action = "done"), "value"),
) do done_before, this_done
!isempty(this_done) && return ""
all_before = length(done_before)
done_before = count((d)->!isempty(d), done_before)
out = "$(done_before) of $(all_before) preceding items are done"
(all_before == done_before) && (out *= " DO THIS NEXT!")
return out
end
callback!(app,
Output("totals", "children"), Input((item = ALL, action = "done"), "value")
) do done
count_all = length(done)
count_done = count((d)->!isempty(d), done)
result = "$(count_done) of $(count_all) items completed"
(count_all > 0) && (result *= " - $(floor(Int, 100 * count_done / count_all))%")
return result
end
return app
end
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 453 | using Dash
app = dash()
app.layout = html_div() do
dcc_input(id="input"),
html_div(id="output-clientside"),
html_div(id="output-serverside")
end
callback!(app, Output("output-serverside", "children"), Input("input","value")) do value
return "Server says \"$(value)\""
end
callback!(
ClientsideFunction("clientside", "display"),
app,
Output("output-clientside", "children"),
Input("input", "value")
)
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 1290 | using Dash
app = dash()
app.layout = html_div() do
html_label("x"),
dcc_input(id="x", value = 3),
html_label("y"),
dcc_input(id="y", value = 6),
html_label("x + y (clientside)"),
dcc_input(id="x-plus-y"),
html_label("x+y / 2 (serverside)"),
dcc_input(id="x-plus-y-div-2"),
html_div() do
html_label("Display x, y, x+y/2 (serverside)"),
dcc_textarea(id = "display-all-of-the-values")
end,
html_label("Mean(x, y, x+y, x+y/2) (clientside)"),
dcc_input(id="mean-of-all-values")
end
callback!(
ClientsideFunction("clientside", "add"),
app,
Output("x-plus-y", "value"),
[Input("x","value"), Input("y","value")]
)
callback!(app, Output("x-plus-y-div-2", "value"), Input("x-plus-y", "value")) do value
return Float64(value) / 2.
end
callback!(app,
Output("display-all-of-the-values", "value"),
[Input("x","value"), Input("y","value"), Input("x-plus-y","value"), Input("x-plus-y-div-2","value")]
) do args...
return join(string.(args), "\n")
end
callback!(
ClientsideFunction("clientside", "mean"),
app,
Output("mean-of-all-values","value"),
[Input("x","value"), Input("y","value"), Input("x-plus-y","value"), Input("x-plus-y-div-2","value")]
)
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 437 | using Dash
app = dash()
app.layout = html_div() do
dcc_input(id="first", value = 1),
dcc_input(id="second"),
dcc_input(id="third")
end
callback!(
ClientsideFunction("clientside", "add1_break_at_11"),
app, Output("second", "value"), Input("first", "value")
)
callback!(
ClientsideFunction("clientside", "add1_break_at_11"),
app, Output("third", "value"), Input("second","value")
)
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 463 | using Dash
app = dash()
app.layout = html_div() do
dcc_input(id="input", value = 1),
dcc_input(id="output-1"),
dcc_input(id="output-2"),
dcc_input(id="output-3"),
dcc_input(id="output-4")
end
callback!(
ClientsideFunction("clientside", "add_to_four_outputs"),
app,
Output("output-1","value"), Output("output-2","value"), Output("output-3","value"), Output("output-4","value"),
Input("input","value")
)
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 334 | using Dash
app = dash()
app.layout = html_div() do
html_div("hello", id="input"),
html_div(id="side-effect"),
html_div("output", id="output")
end
callback!(
ClientsideFunction("clientside", "side_effect_and_return_a_promise"),
app, Output("output","children"), Input("input","children")
)
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 509 | using Dash
app = dash()
app.layout = html_div() do
dcc_input(id="first", value = 1),
dcc_input(id="second", value = 1),
dcc_input(id="third", value = 1)
end
callback!(
ClientsideFunction("clientside", "add1_prevent_at_11"),
app, Output("second","value"), Input("first","value"), State("third","value")
)
callback!(
ClientsideFunction("clientside", "add1_prevent_at_11"),
app, Output("third","value"), Input("second","value"), State("third","value")
)
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 409 | using Dash
app = dash()
app.layout = html_div() do
dcc_input(id="first", value = 1),
dcc_input(id="second", value = 1),
dcc_input(id="third", value = 1)
end
callback!(
ClientsideFunction("clientside", "add1_no_update_at_11"),
app, [Output("second","value"), Output("third","value")], Input("first","value"),
[State("second","value"), State("third","value")]
)
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 485 | using Dash
app = dash()
app.layout = html_div() do
dcc_input(id="input"),
html_div(id="output-clientside"),
html_div(id="output-serverside")
end
callback!(app, Output("output-serverside","children"), Input("input","value")) do value
return "Server says \"$(value)\""
end
callback!(
"""
function (value) {
return 'Client says "' + value + '"';
}
""",
app, Output("output-clientside","children"), Input("input","value") )
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 198 | using Dash
app = dash()
app.layout = html_div(id="outer-div") do
html_div("A div", id="first-inner-div"),
html_br(),
html_div("Another div", id="second-inner-div")
end
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 617 | using Dash
app = dash(assets_ignore=".*ignored.*")
app.index_string = """<!DOCTYPE html>
<html>
<head>
{%metas%}
<title>{%title%}</title>
{%css%}
</head>
<body>
<div id="tested"></div>
{%app_entry%}
<footer>
{%config%}
{%scripts%}
{%renderer%}
</footer>
</body>
</html>"""
app.layout = html_div(id="layout") do
html_div("Content", id="content"),
dcc_input(id="test")
end
callback!(app,
Output("output","children"),
Input("input","value")
) do value
return value
end
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 1450 | using Dash
js_files = [
"https://www.google-analytics.com/analytics.js",
Dict("src"=> "https://cdn.polyfill.io/v2/polyfill.min.js"),
Dict(
"src"=> "https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js",
"integrity"=> "sha256-43x9r7YRdZpZqTjDT5E0Vfrxn1ajIZLyYWtfAXsargA=",
"crossorigin"=> "anonymous",
),
Dict(
"src"=> "https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js",
"integrity"=> "sha256-7/yoZS3548fXSRXqc/xYzjsmuW3sFKzuvOCHd06Pmps=",
"crossorigin"=> "anonymous",
),
]
css_files = [
"https://codepen.io/chriddyp/pen/bWLwgP.css",
Dict(
"href"=> "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css",
"rel"=> "stylesheet",
"integrity"=> "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO",
"crossorigin"=> "anonymous",
)
]
app = dash(external_scripts=js_files, external_stylesheets=css_files)
app.index_string = """<!DOCTYPE html>
<html>
<head>
{%metas%}
<title>{%title%}</title>
{%css%}
</head>
<body>
<div id="tested"></div>
<div id="ramda-test"></div>
<button type="button" id="btn">Btn</button>
{%app_entry%}
<footer>
{%config%}
{%scripts%}
{%renderer%}
</footer>
</body>
</html>"""
app.layout = html_div()
run_server(app)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 244 | using Dash
app = dash()
app.layout = html_div() do
html_p(id="tcid", children = "Hello Props Check"),
dcc_graph(id="broken", animate = 3)
end
run_server(app, debug = true, dev_tools_hot_reload = false, dev_tools_props_check = false)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 239 | using Dash
app = dash()
app.layout = html_div() do
html_p(id="tcid", children = "Hello Disable UI"),
dcc_graph(id="broken", animate = 3)
end
run_server(app, debug = true,
dev_tools_hot_reload = false, dev_tools_ui = false
)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 601 | using Dash
app = dash(assets_folder="hr_assets")
app.index_string = """<!DOCTYPE html>
<html>
<head>
{%metas%}
<title>{%title%}</title>
{%css%}
</head>
<body>
<div id="tested"></div>
{%app_entry%}
<footer>
{%config%}
{%scripts%}
{%renderer%}
</footer>
</body>
</html>"""
app.layout = html_div(id="hot-reload-content") do
html_h3("Hot reload")
end
run_server(app,
dev_tools_hot_reload=true,
dev_tools_hot_reload_interval=0.1,
dev_tools_hot_reload_max_retry=100,
)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 486 | using Dash
app = dash()
app.layout = html_div(id="before-reload-content") do
html_h3("Hot restart"),
dcc_input(id="input", value="initial"),
html_div(id="output")
end
callback!(app, Output("output","children"), Input("input","value")) do value
return "before reload $value"
end
run_server(app,
dev_tools_hot_reload=true,
dev_tools_hot_reload_interval=0.1,
dev_tools_hot_reload_watch_interval=0.1,
dev_tools_hot_reload_max_retry=100
)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | code | 4590 | using Dash
test_cases = Dict(
"not-boolean" => Dict(
"fail"=> true,
"name"=> "simple \"not a boolean\" check",
"component"=> dcc_input,
"props"=> (debounce = 0,),
),
"missing-required-nested-prop"=> Dict(
"fail"=> true,
"name"=> "missing required \"value\" inside options",
"component"=> dcc_checklist,
"props"=> (options = [Dict("label" => "hello")], value = ["test"]),
),
"invalid-arrayOf"=> Dict(
"fail"=> true,
"name"=> "invalid arrayOf",
"component"=> dcc_checklist,
"props"=> (options = "test", value = []),
),
"invalid-oneOf"=> Dict(
"fail"=> true,
"name"=> "invalid oneOf",
"component"=> dcc_input,
"props"=> (type = "test",),
),
"invalid-oneOfType"=> Dict(
"fail"=> true,
"name"=> "invalid oneOfType",
"component"=> dcc_input,
"props"=> (max = true,),
),
"invalid-shape-5"=> Dict(
"fail"=> true,
"name"=> "invalid not required key",
"component"=> dcc_dropdown,
"props"=> (options = [Dict("label"=> "new york", "value"=> "ny", "typo"=> "asdf")],),
),
"string-not-list"=> Dict(
"fail"=> true,
"name"=> "string-not-a-list",
"component"=> dcc_checklist,
"props"=> (options = [Dict("label"=> "hello", "value"=> "test")], value = "test"),
),
"no-properties"=> Dict(
"fail"=> false,
"name"=> "no properties",
"component"=> dcc_input,
"props"=> (),
),
"nested-children"=> Dict(
"fail"=> true,
"name"=> "nested children",
"component"=> html_div,
"props"=> (children = [[1]],),
),
"deeply-nested-children"=> Dict(
"fail"=> true,
"name"=> "deeply nested children",
"component"=> html_div,
"props"=> (children = html_div([html_div([3, html_div([[10]])])]),),
),
"dict"=> Dict(
"fail"=> true,
"name"=> "returning a dictionary",
"component"=> html_div,
"props"=> (children = Dict("hello" => "world"),),
),
"allow-nested-prop"=> Dict(
"fail"=> false,
"name"=> "allow nested prop",
"component"=> dcc_checklist,
"props"=> (options = [Dict("label"=> "hello", "value"=> true)], value = ["test"]),
),
"allow-null-2"=> Dict(
"fail"=> false,
"name"=> "allow null as value",
"component"=> dcc_dropdown,
"props"=> (value = nothing,),
),
"allow-null-3"=> Dict(
"fail"=> false,
"name"=> "allow null in properties",
"component"=> dcc_input,
"props"=> (value = nothing,),
),
"allow-null-4"=> Dict(
"fail"=> false,
"name"=> "allow null in oneOfType",
"component"=> dcc_store,
"props"=> (id = "store", data = nothing),
),
"long-property-string"=> Dict(
"fail"=> false,
"name"=> "long property string with id",
"component"=> html_div,
"props"=> (id = "pink div", style = repeat("color=> hotpink; ", 1000)),
),
"multiple-wrong-values"=> Dict(
"fail"=> true,
"name"=> "multiple wrong props",
"component"=> dcc_dropdown,
"props"=> (id = "dropdown", value = 10, options = "asdf"),
),
"boolean-html-properties"=> Dict(
"fail"=> true,
"name"=> "dont allow booleans for dom props",
"component"=> html_div,
"props"=> (contentEditable = true,),
),
"allow-exact-with-optional-and-required-1"=> Dict(
"fail"=> false,
"name"=> "allow exact with optional and required keys",
"component"=> dcc_dropdown,
"props"=> (options = [Dict("label"=> "new york", "value"=> "ny", "disabled"=> false)],),
),
"allow-exact-with-optional-and-required-2"=> Dict(
"fail"=> false,
"name"=> "allow exact with optional and required keys 2",
"component"=> dcc_dropdown,
"props"=> (options = [Dict("label"=> "new york", "value"=> "ny")],),
)
)
app = dash()
app.layout = html_div() do
html_div(id="content"),
dcc_location(id="location")
end
callback!(app, Output("content","children"), Input("location","pathname")) do pathname
if isnothing(pathname) || pathname == "/"
return "Initial state"
end
test_case = test_cases[strip(pathname, '/')]
return html_div(
id="new-component", children=test_case["component"](;test_case["props"]...)
)
end
run_server(app, debug = true, dev_tools_hot_reload = false)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | docs | 2165 | # Change Log for Dash for Julia
All notable changes to this project will be documented in this file. This project adheres to Semantic Versioning.
## [0.1.0] - 2020-09-10
### Added
- Support for clientside callbacks [#30](https://github.com/plotly/Dash.jl/pull/30)
- Support for hot reloading on application or asset changes [#25](https://github.com/plotly/Dash.jl/pull/25)
- Asset serving of CSS, JavaScript, and other resources [#18](https://github.com/plotly/Dash.jl/pull/18)
- Support for passing functions as layouts [#18](https://github.com/plotly/Dash.jl/pull/18)
- Resource registry for component assets [#18](https://github.com/plotly/Dash.jl/pull/18)
- Asynchronous component loading & fingerprinting component assets [#18](https://github.com/plotly/Dash.jl/pull/18)
- Developer tools UI support [#18](https://github.com/plotly/Dash.jl/pull/18)
- Dash environment variables are now supported [#18](https://github.com/plotly/Dash.jl/pull/18)
- Index page/layout validation now performed [#18](https://github.com/plotly/Dash.jl/pull/18)
- Support for `gzip` compression [#14](https://github.com/plotly/Dash.jl/pull/14)
- Parity with core Dash API parameters [#12](https://github.com/plotly/Dash.jl/pull/12)
- Integration tests are now supported, server startup message appears on app initialization [#21](https://github.com/plotly/Dash.jl/pull/21)
### Changed
- Dash.jl now starts via `run_server` with `host` and `port` arguments [#2](https://github.com/plotly/Dash.jl/issues/2)
- Defining layouts in Dash.jl now occurs similarly to Dash for Python/R [#1](https://github.com/plotly/Dash.jl/issues/1)
### Removed
- `make_handler` no longer used to start Dash server [#2](https://github.com/plotly/Dash.jl/issues/2)
- `layout_maker` has been removed [#18](https://github.com/plotly/Dash.jl/pull/18)
- `layout_maker` is no longer called by the app developer to define the layout [#1](https://github.com/plotly/Dash.jl/issues/1)
### Fixed
- Request headers are now properly specified [#28](https://github.com/plotly/Dash.jl/issues/28)
- Unspecified `children` now passed as `nothing` rather than undefined [#27](https://github.com/plotly/Dash.jl/issues/27)
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | docs | 4693 | # Contributor Guide
## Git
We use the `dev` branch for development. All feature branches should be based
off `dev`.
The `master` branch corresponds to the latest release. We deploy to [Julia
General Registry][jgr] and `git tag -a` off `master`.
## Running the unit tests (aka Julia tests)
```sh
git clone [email protected]:plotly/Dash.jl.git
cd Dash.jl
julia
```
```jl
julia> import Pkg
julia> Pkg.activate(".")
julia> Pkg.instantiate()
julia> Pkg.update()
julia> Pkg.test()
```
To run the unit tests for multiple versions of Julia, we recommend using [`juliaup`][juliaup].
## Running the integration tests
The integration tests make use of the [`dash.testing`][testing] module part of
the Python version of dash.
Instructions on how to install the required system dependencies can be found
in the [dash Contributor Guide][dash-cg].
Then,
```sh
cd Dash.jl
git clone --depth 1 https://github.com/plotly/dash.git -b dev dash-main
python3 -m venv venv
pip install --upgrade pip wheel
cd dash-main && pip install -e .[ci,dev,testing] && cd ..
cd test/integration
julia --project -e 'import Pkg; Pkg.develop(path="../../"); Pkg.instantiate(); Pkg.update();'
pytest --headless --nopercyfinalize --percy-assets=../assets/ .
```
Alternatively, one can run the integration tests using the same Docker
image as for our CircleCI test runs. See the [Docker image guide][docker-test]
for the details.
## Updating the resources
See the [Generate Dash.jl artifacts][resources].
## Updating the CircleCI Docker image
See the [Docker image guide][docker-update].
## Code Style
- indent with 4 spaces (no tabs),
- no whitespaces at EOLs,
- add a single newline at EOFs.
See the [`lint.yml` workflow][lint] for the details.
## Making a release
**Please follow the steps in order!** For example, running `git tag -a` before
`@JuliaRegistrator register` will lead to a failed release!
In the following steps, note that "X.Y.Z" refers to the new version we are
releasing.
### step 1
Make sure the [unit tests][jltest] and [CircleCI integration tests][circlecI]
are passing off the `dev` branch.
### step 2
Make a [PR][compare] with `master` as the _base_ branch and `dev` as _compare_ branch.
For consistency, name the PR: "Release X.Y.Z"
### step 3
Bump the `version` field in the `Project.toml` (following [semver][semver]) and then
```sh
git checkout dev
git pull origin dev
git commit -m "X.Y.Z"
git push
```
**N.B.** use `X.Y.Z` not `vX.Y.Z` in the commit message, the leading `v` is
reserved for git tags.
### step 4
Wait for approval and then merge the PR onto `master`.
### step 5
Navigate on GitHub to the merge commit from the `master` branch e.g. this
[one][ex-commit] and then add the following comment:
```sh
@JuliaRegistrator register branch=master
```
which tells the [Julia Registrator][registrator] to create a PR to the
[General Registry][jgr] e.g. this [one][ex-jgr-pr].
### step 6
Wait for the Julia Registry PR to be merged. If things go well, this should be
automatic!
### step 7
Off `master`, create and push a new git tag with:
```sh
git checkout master
git tag -a vX.Y.Z # N.B. leading `v`
git push --tags
```
### step 8
Go the [release page][releases] and create a new release,
name it "Version X.Y.Z" for consistency and fill out sections:
- (usually) _Added_, _Changed_, _Fixed_ while including links to the PRs merged since the last release
- _New Contributor_, which should include mentions for all the first-time contributors
finally, place a [GitHub compare link][compare] between the last release and X.Y.Z
e.g. this [one][ex-diff].
### step 9
you are done :tada:
[jgr]: https://github.com/JuliaRegistries/General
[juliaup]: https://github.com/JuliaLang/juliaup
[testing]: https://dash.plotly.com/testing#end-to-end-tests
[dash-cg]: https://github.com/plotly/dash/blob/dev/CONTRIBUTING.md#tests
[resources]: ./gen_resources/README.md
[docker-test]: ./build/README.md#local-usage
[docker-update]: ./build/README.md#how-to-update-the-docker-image
[lint]: ./.github/workflows/lint.yml
[jltest]: https://github.com/plotly/Dash.jl/actions/workflows/jl_test.yml?query=branch%3Adev
[circlecI]: https://app.circleci.com/pipelines/github/plotly/Dash.jl?branch=dev
[semver]: https://pkgdocs.julialang.org/v1/toml-files/#The-version-field
[registrator]: https://github.com/JuliaRegistries/Registrator.jl
[releases]: https://github.com/plotly/Dash.jl/releases
[compare]: https://github.com/plotly/Dash.jl/compare/
[ex-commit]: https://github.com/plotly/Dash.jl/commit/5ec76d9d3360f370097937efd06e5de5a6025888
[ex-jgr-pr]: https://github.com/JuliaRegistries/General/pull/77586
[ex-diff]: https://github.com/plotly/Dash.jl/compare/v1.1.2...v1.2.0
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | docs | 6120 | # Dash for Julia
[](https://github.com/plotly/Dash.jl/actions/workflows/jl_test.yml?query=branch%3Adev)
[](https://circleci.com/gh/plotly/Dash.jl/tree/dev)
[](https://github.com/plotly/Dash.jl/blob/master/LICENSE)
[](https://github.com/plotly/Dash.jl/graphs/contributors)
#### Create beautiful, analytic applications in Julia
Built on top of Plotly.js, React and HTTP.jl, [Dash](https://plotly.com/dash/) ties modern UI elements like dropdowns, sliders, and graphs directly to your analytical Julia code.
Just getting started? Check out the [Dash for Julia User Guide](https://dash.plotly.com/julia)! If you can't find documentation there, then check out the unofficial [contributed examples](https://github.com/plotly/Dash.jl/issues/50) or check out source code from [demo applications](https://dash.gallery) in Python and then reference the Julia syntax style.
## Other resources
* <https://community.plotly.com/c/plotly-r-matlab-julia-net/julia/23>
* <https://discourse.julialang.org/tag/dash>
## Project Status
Julia components can be generated in tandem with Python and R components. Interested in getting involved with the project? Sponsorship is a great way to accelerate the progress of open source projects like this one; please feel free to [reach out to us](https://plotly.com/consulting-and-oem/)!
## Installation
To install the most recently released version:
```julia
pkg> add Dash
```
To install the latest (stable) development version instead:
```julia
pkg> add Dash#dev
```
## Usage
### Basic application
```julia
using Dash
app = dash(external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"])
app.layout = html_div() do
html_h1("Hello Dash"),
html_div("Dash.jl: Julia interface for Dash"),
dcc_graph(id = "example-graph",
figure = (
data = [
(x = [1, 2, 3], y = [4, 1, 2], type = "bar", name = "SF"),
(x = [1, 2, 3], y = [2, 4, 5], type = "bar", name = "Montréal"),
],
layout = (title = "Dash Data Visualization",)
))
end
run_server(app)
```
__then go to `http://127.0.0.1:8050` in your browser to view the Dash app!__
### Basic Callback
```julia
using Dash
app = dash(external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"])
app.layout = html_div() do
dcc_input(id = "my-id", value = "initial value", type = "text"),
html_div(id = "my-div")
end
callback!(app, Output("my-div", "children"), Input("my-id", "value")) do input_value
"You've entered $(input_value)"
end
run_server(app)
```
* You can make your Dash app interactive by registering callbacks with the `callback!` function.
* Outputs and inputs (and states, see below) of callback can be `Output`, `Input`, `State` objects or splats / vectors of this objects.
* Callback functions must have the signature ``(inputs..., states...)``, and provide a return value with the same number elements as the number of `Output`s to update.
### States and Multiple Outputs
```julia
using Dash
app = dash(external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"])
app.layout = html_div() do
dcc_input(id = "my-id", value = "initial value", type = "text"),
html_div(id = "my-div"),
html_div(id = "my-div2")
end
callback!(app,
Output("my-div","children"),
Output("my-div2","children"),
Input("my-id", "value"),
State("my-id", "type")) do input_value, state_value
return ("You've entered $(input_value) in input with type $(state_value)",
"You've entered $(input_value)")
end
run_server(app)
```
## Comparison with original Python syntax
### Component naming
* Python:
```python
import dash
dash.html.Div
dash.dcc.Graph
dash.dash_table.DataTable
```
* Dash.jl:
```julia
using Dash
html_div
dcc_graph
dash_datatable
```
### Component creation
Just as in Python, functions for declaring components have keyword arguments, which are the same as in Python. ``html_div(id = "my-id", children = "Simple text")``.
For components which declare `children`, two additional signatures are available:
* ``(children; kwargs..)`` and
* ``(children_maker::Function; kwargs...)``
So one can write ``html_div("Simple text", id = "my-id")`` for simple elements, or choose an abbreviated syntax with `do` syntax for complex elements:
```julia
html_div(id = "outer-div") do
html_h1("Welcome"),
html_div(id = "inner-div") do
#= inner content =#
end
end
```
### Application and layout
* Python:
```python
app = dash.Dash(external_stylesheets=["https://codepen.io/chriddyp/pen/bWLwgP.css"])
app.layout = html.Div(children=[....])
```
* Dash.jl:
```julia
app = dash(external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"])
app.layout = html_div() do
#= inner content =#
end
```
### Callbacks
* Python:
```python
@app.callback(Output('output', 'children'),
Input('submit-button', 'n_clicks')],
State('state-1', 'value'),
State('state-2', 'value'))
def update_output(n_clicks, state1, state2):
# logic
```
* Dash.jl:
```julia
callback!(app,
Output("output", "children"),
Input("submit-button", "n_clicks")],
State("state-1", "value"),
State("state-2", "value")) do n_clicks, state1, state2
# logic
end
```
### JSON
Dash apps transfer data between the browser (aka the frontend) and the Julia process running the app (aka the backend) in JSON.
Dash.jl uses [JSON3.jl](https://github.com/quinnj/JSON3.jl) for JSON serialization/deserialization.
Note that JSON3.jl converts
* `Vector`s and `Tuple`s to JSON arrays
* `Dict`s and `NamedTuple`s to JSON objects
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | docs | 3237 | # Docker image for running integration tests
As CircleCI does not have Julia [Orbs](https://circleci.com/orbs/) yet, we rely
on a custom docker image to have access to Python, headless Chrome and Julia
in the same container.
Since <https://github.com/plotly/Dash.jl/pull/207>, we tag the build images
as [`etpinard/dashjl-tests`](https://hub.docker.com/r/etpinard/dashjl-tests). We
previously used the [`plotly/julia:ci`](https://hub.docker.com/r/plotly/julia/tags) image.
## When should we update the docker image?
The integration tests rely on the Python version of [dash](https://github.com/plotly/dash)
and its [testing framework](https://github.com/plotly/dash/tree/dev/dash/testing).
So, we should use the latest CircleCI python + browsers image latest Python version
that is included in the [dash CircleCI config](https://github.com/plotly/dash/blob/dev/.circleci/config.yml)
as our base image.
We should also update the Julia version from time to time. It might be nice to
run the integration tests on multiple Julia versions eventually.
## How to update the docker image?
Ask for push rights on docker hub first, then
```sh
cd Dash.jl/build
docker build -t etpinard:dashjl-tests:<x.y.z> .
docker push etpinard:dashjl-test:<x.y.z>
```
where `<x.y.z>` is the semver tag for the new image.
## CircleCI usage
This image is pulled from within Dash.jl's [CircleCI config.yml](../.circleci/config.yml):
```yaml
docker:
- image: etpinard/dashjl-tests:<x.y.z>
```
where `<x.y.z>` is the latest tag listed on <https://hub.docker.com/r/etpinard/dashjl-tests/tags>.
## Local usage
```sh
# grab a copy of the python (main) dash repo
cd Dash.jl
git clone --depth 1 https://github.com/plotly/dash.git -b dev dash-main
# start `dashjl-tests`
# [on 1st session]
docker run -t -d --name dashjl-tests -v .:/home/circleci/project etpinard/dashjl-tests:<x.y.z>
# [otherwise]
docker start dashjl-tests
# ssh into it as root (some python deps need that unfortunately)
docker exec -u 0 -it dashjl-tests bash
# [on 1st session] install pip deps
cd /home/circleci/project/dash-main
pip install --upgrade pip wheel
pip install -e .[ci,dev,testing] --progress-bar off
# [on 1st session] install chrome
cd /home/circleci
wget https://raw.githubusercontent.com/CircleCI-Public/browser-tools-orb/main/src/scripts/install-chrome.sh
chmod +x install-chrome.sh
ORB_PARAM_CHANNEL="stable" ORB_PARAM_CHROME_VERSION="latest" ./install-chrome.sh
# [on 1st session] install chromedriver
cd /home/circleci
wget https://raw.githubusercontent.com/CircleCI-Public/browser-tools-orb/main/src/scripts/install-chromedriver.sh
chmod +x ./install-chromedriver.sh
ORB_PARAM_DRIVER_INSTALL_DIR=/usr/local/bin/ ./install-chromedriver.sh
# [on 1st session] instantiate julia deps
cd /home/circleci/project/test/integration
julia --project -e 'import Pkg; Pkg.develop(path="../../"); Pkg.instantiate()'
# [optionally] if you want to use an unreleased version of DashBase
julia --project -e 'import Pkg; Pkg.add(name="DashBase", rev="master")'
# update julia deps then run integration tests
cd /home/circleci/project/test/integration
julia --project -e 'import Pkg; Pkg.update()'
pytest --headless --nopercyfinalize --percy-assets=../assets/ .
```
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | docs | 89 | # Dashboards.jl API
```@index
```
```@docs
Dash
@callid_str
callback!
make_handler
```
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | docs | 7629 | # Dashboards
Julia backend for [Plotly Dash](https://github.com/plotly/dash)
## Version 0.2.8 released
* Integration with travis ci
* [dash-bootstrap-components](https://github.com/facultyai/dash-bootstrap-components) added with prefix dbc. Examples of use will be soon
* pass_changed_props argument added to [`callback!`](@ref) function. For details see docs of [`callback!`](@ref)
## Version 0.2.5 released
* Now you can use `PlotlyBase.Plot` to work with the `figure` property of the `dcc_graph` component. Examples are: [Plot usage in layout](https://github.com/waralex/DashboardsExamples/blob/master/dash_tutorial/2_dash_layout_4.jl), [Plot usage in callback](https://github.com/waralex/DashboardsExamples/blob/master/dash_tutorial/3_basic_dash_callbacks_2.jl)
* Added `PreventUpdate` exception and `no_update()` function to prevent updates in callback. See [PreventUpdate example](https://github.com/waralex/DashboardsExamples/blob/master/dash_tutorial/4_state_and_prevent_update_3.jl) and [no_update() example](https://github.com/waralex/DashboardsExamples/blob/master/dash_tutorial/4_state_and_prevent_update_3.jl)
* Most of dashboards from [Dash Tutorial](https://dash.plot.ly/) are implemented using Dashboards.jl. See [DashboardsExamples repo](https://github.com/waralex/DashboardsExamples)
## Installation
Julia version >= 1.2 is required.
It also works in 1.1 now, but I do not plan testing and support for versions under 1.2
```julia
import Pkg; Pkg.add("Dashboards")
```
## Usage
### Basic application
```jldoctest
julia> import HTTP
julia> using Dashboards
julia> app = Dash(external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"]) do
html_div() do
html_h1("Hello Dashboards"),
html_div("Dashboards: Julia interface for Dash"),
dcc_graph(
id = "example-graph",
figure = (
data = [
(x = [1, 2, 3], y = [4, 1, 2], type = "bar", name = "SF"),
(x = [1, 2, 3], y = [2, 4, 5], type = "bar", name = "Montréal"),
],
layout = (title = "Dash Data Visualization",)
)
)
end
end
julia> handler = make_handler(app, debug = true)
julia> HTTP.serve(handler, HTTP.Sockets.localhost, 8080)
```
* The `Dash` struct represent dashboard application.
* The constructor for `Dash` struct is ``Dash(layout_maker::Function, name::String; external_stylesheets::Vector{String} = Vector{String}(), url_base_pathname="/", assets_folder::String = "assets")`` where `layout_maker` is a function with signature ()::Component
* Unlike the python version where each Dash component is represented as a separate class, all components in Dashboard are represented by struct `Component`.
* You can create `Component` specific for concrete Dash component by the set of functions in the form ``lowercase(<component package>)_lowercase(<component name>)``. For example, in python html `<div>` element is represented as `HTML.Div` in Dashboards it is created using function `html_div`
* The list of all supported components is available in docstring for Dashboards module
* All functions for a component creation have the signature `(;kwargs...)::Component`. List of key arguments specific for the concrete component is available in the docstring for each function
* Functions for creation components which have `children` property have two additional methods ``(children::Any; kwargs...)::Component`` and ``(children_maker::Function; kwargs..)::Component``. `children` must by string or number or single component or collection of components
* ``make_handler(app::Dash; debug::Bool = false)`` makes handler function for using in HTTP package
__Once you have run the code to create the Dashboard, go to `http://127.0.0.1:8080` in your browser to view the Dashboard!__
### Basic Callback
```jldoctest
julia> import HTTP
julia> using Dashboards
julia> app = Dash(external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"]) do
html_div() do
dcc_input(id = "my-id", value="initial value", type = "text"),
html_div(id = "my-div")
end
end
julia> callback!(app, callid"my-id.value => my-div.children") do input_value
"You've entered $(input_value)"
end
julia> handler = make_handler(app, debug = true)
julia> HTTP.serve(handler, HTTP.Sockets.localhost, 8080)
```
* You can make your dashboard interactive by register callbacks for changes in frontend with function ``callback!(func::Function, app::Dash, id::CallbackId)``
* Inputs and outputs (and states, see below) of callback are described by struct `CallbackId` which can easily created by string macro `callid""`
* `callid""` parse string in form ``"[{state1 [,...]}] input1[,...] => output1[,...]"`` where all items is ``"<element id>.<property name>"``
* Callback function must have the signature(states..., inputs...) and return data for output
### States and Multiple Outputs
```jldoctest
julia> import HTTP
julia> using Dashboards
julia> app = Dash(external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"]) do
html_div() do
dcc_input(id = "my-id", value="initial value", type = "text"),
html_div(id = "my-div"),
html_div(id = "my-div2")
end
end
julia> callback!(app, callid"{my-id.type} my-id.value => my-div.children, my-div2.children") do state_value, input_value
"You've entered $(input_value) in input with type $(state_value)",
"You've entered $(input_value)"
end
julia> handler = make_handler(app, debug = true)
julia> HTTP.serve(handler, HTTP.Sockets.localhost, 8080)
```
* For multiple output callback must return any collection with element for each output
## Comparison with original python syntax
### component naming:
`html.Div` => `html_div`, `dcc.Graph` => `dcc_graph` and etc
### component creation:
Just like in Python, functions for creating components have keywords arguments, which are the same as in Python. ``html_div(id="my-id", children="Simple text")``.
For components that have `children` prop, two additional signatures are available. ``(children; kwargs..)`` and ``(children_maker::Function; kwargs...)`` so You can write ``html_div("Simple text", id="my-id")`` for simple elements or avoid the hell of nested brackets with `do` syntax for complex elements:
```julia
html_div(id="outer-div") do
html_h1("Welcome"),
html_div(id="inner-div") do
......
end
end
```
### application and layout:
* python:
```python
app = dash.Dash("Test", external_stylesheets=external_stylesheets)
app.layout = html.Div(children=[....])
```
* Dashboards:
```julia
app = Dash("Test", external_stylesheets=external_stylesheets) do
html_div() do
......
end
end
```
### callbacks:
* python:
```python
@app.callback(Output('output', 'children'),
[Input('submit-button', 'n_clicks')],
[State('state-1', 'value'),
State('state-2', 'value')])
def update_output(n_clicks, state1, state2):
.....
```
* Dashboards:
```julia
callback!(app, callid"""{state1.value, state2.value}
submit-button.n_clicks
=> output.children""" ) do state1, state2, n_clicks
.....
end
```
Be careful - in Dashboards states came first in arguments list
### json:
I use JSON3 for json serialization/deserialization. In component props you can use both Dicts and NamedTuples for json objects. But be careful with single property objects: `layout = (title = "Test graph")` is not interpreted as NamedTuple by Julia - you need add comma at the end `layout = (title = "Test graph",)`
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 1.5.0 | 826c9960644b38dcf0689115a86b57c3f1aa7f1d | docs | 2340 | # Generate Dash.jl artifacts
Dash.jl uses Julia
[Artifacts](https://docs.julialang.org/en/v1/stdlib/Artifacts/) to load
front-end resources that Dash.jl shares with the python version of
[dash](https://github.com/plotly/dash).
The [Artifacts.toml](../Artifacts.toml) file lists the location of the
publicly-available tarball containing all the required resources.
The tarballs are hosted on the
[DashCoreResources](https://github.com/plotly/DashCoreResources) repo, under
_Releases_. They are generated and deployed using the `generate.jl` script in
this directory.
## How to run `generate.jl` ?
### Step 0: get push rights to `DashCoreResources`
### Step 1: get GitHub personal access token
See [GitHub docs](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-fine-grained-personal-access-token)
for more info.
If using a fine-grained token, make sure to enable _Read and Write access to code_.
### Step 2: expose your token into your shell
```sh
# for example:
export GITHUB_TOKEN="<your GitHub personal access token>"
```
### Step 3: run `generate.jl`
```sh
cd Dash.jl/gen_resources
# install `generate.jl` deps
julia --project -e 'import Pkg; Pkg.instantiate()'
# generate `gen_resources/build/deploy/` content,
# but do not deploy!
julia --project generate.jl
# if everything looks fine,
# generate `gen_resources/build/deploy/` content (again) and
# deploy to the `DashCoreResource` releases with:
julia --project generate.jl --deploy
```
#### If `generate.jl` errors
<details>
<summary>with a PyError / PyImport error</summary>
that is an error like:
```sh
ERROR: LoadError: PyError (PyImport_ImportModule
The Python package dash could not be imported by pyimport. Usually this means
that you did not install dash in the Python version being used by PyCall.
PyCall is currently configured to use the Python version at:
/usr/bin/python3
```
try
```jl
using PyCall
ENV["PYTHON"] = joinpath(homedir(), ".julia/conda/3/x86_64/bin")
import Pkg
Pkg.build("PyCall")
# check that it matches with
PyCall.pyprogramname
```
and then re-run `generate.jl`.
</details>
### Step 4: Commit the changes to `Artifacts.toml`
and push to [plotly/Dash.jl](https://github.com/plotly/Dash.jl)
(preferably on a new branch) to get a CI test run started.
| Dash | https://github.com/plotly/Dash.jl.git |
|
[
"MIT"
] | 0.4.1 | 893a38118dc5a7554a52bbbc58d6de591e58f7b6 | code | 226 | using Documenter, AlphaVantage
makedocs(
sitename = "AlphaVantage.jl Documentation"
)
deploydocs(
deps = Deps.pip("mkdocs"),
repo = "github.com/ellisvalentiner/AlphaVantage.jl.git",
push_preview = true
)
| AlphaVantage | https://github.com/ellisvalentiner/AlphaVantage.jl.git |
|
[
"MIT"
] | 0.4.1 | 893a38118dc5a7554a52bbbc58d6de591e58f7b6 | code | 1333 | VERSION >= v"1.6.0"
module AlphaVantage
using Compat
using ArgCheck
using DelimitedFiles
using HTTP
using JSON
include("avclient.jl")
include("avresponse.jl")
include("utils.jl")
include("stock_time_series.jl")
include("digital_currency.jl")
include("foreign_exchange_currency.jl")
include("stock_technical_indicators.jl")
include("sector_performance.jl")
include("fundamental_values.jl")
include("fundamentals.jl")
include("economic_indicators.jl")
# avclient
export key, AlphaVantageClient, AlphaVantageResponse
# stock_time_series
export
time_series_intraday,
time_series_intraday_extended
# `time_series_daily` etc are exported in macro
# digital_currency
export crypto_rating, digital_currency_intraday
# `digital_currency_daily` etc are exported in macro
# foreign_exchange_currency
export
currency_exchange_rate,
fx_intraday,
fx_daily
# `fx_weekly` etc are exported in macro
# stock_technical_indicators
# `VWAP` etc are exported in macro
# sector_performance
export sector_performance
# fundamentals
export
company_overview,
income_statement,
balance_sheet,
cash_flow,
listing_status,
earnings,
earnings_calendar,
ipo_calendar
# economic_indicators
# others exported in macro
export
real_gdp,
treasury_yield,
federal_fund_rate,
cpi
end # module
| AlphaVantage | https://github.com/ellisvalentiner/AlphaVantage.jl.git |
|
[
"MIT"
] | 0.4.1 | 893a38118dc5a7554a52bbbc58d6de591e58f7b6 | code | 488 | mutable struct AlphaVantageClient
scheme::String
key::String
host::String
end
AlphaVantageClient(; scheme = "https", key = "", host = alphavantage_api) = AlphaVantageClient(scheme, key, host)
const GLOBAL = Ref(AlphaVantageClient(key = get(ENV, "ALPHA_VANTAGE_API_KEY", ""), host = get(ENV, "ALPHA_VANTAGE_HOST", "www.alphavantage.co")))
function key(client::AlphaVantageClient)
if isempty(client.key)
@warn "No API key found"
end
return client.key
end
| AlphaVantage | https://github.com/ellisvalentiner/AlphaVantage.jl.git |
|
[
"MIT"
] | 0.4.1 | 893a38118dc5a7554a52bbbc58d6de591e58f7b6 | code | 1573 | import Tables
struct AlphaVantageResponse
data::Vector{AbstractVector}
names::Vector{AbstractString}
AlphaVantageResponse(data::Vector{AbstractVector}, names::Vector{<:AbstractString}) = begin
l1 = length(data[1])
@assert all(t -> length(t) == l1, data)
@assert length(data) == length(names)
new(data, names)
end
end
function narrow_types(v::AbstractVector)
T = mapreduce(typeof, promote_type, v)
convert(AbstractVector{T}, v)
end
AlphaVantageResponse(data::AbstractVector{<:AbstractVector{T}} where T, names::AbstractVector{<:AbstractString}) = begin
AlphaVantageResponse(narrow_types(data), names)
end
AlphaVantageResponse(data::AbstractMatrix{T} where T, names::AbstractMatrix{<:AbstractString}) = begin
v = AbstractVector[narrow_types(c) for c in eachcol(data)]
n = vec(names)
AlphaVantageResponse(v, n)
end
AlphaVantageResponse(raw::Tuple{AbstractMatrix{Any}, AbstractMatrix{<:AbstractString}}) = begin
AlphaVantageResponse(raw[1], raw[2])
end
AlphaVantageResponse(d::Dict) = Tables.table(reshape(collect(values(d)), (1,:)), header=keys(d))
Tables.istable(::AlphaVantageResponse) = true
Tables.rowaccess(::AlphaVantageResponse) = false
Tables.columnaccess(::AlphaVantageResponse) = true
Tables.columns(t::AlphaVantageResponse) = t
Tables.getcolumn(t::AlphaVantageResponse, i::Int) = t.data[i]
Tables.getcolumn(t::AlphaVantageResponse, nm::Symbol) = begin
ind = findfirst(==(nm), Symbol.(t.names))
t.data[ind]
end
Tables.columnnames(t::AlphaVantageResponse) = Symbol.(t.names)
| AlphaVantage | https://github.com/ellisvalentiner/AlphaVantage.jl.git |
|
[
"MIT"
] | 0.4.1 | 893a38118dc5a7554a52bbbc58d6de591e58f7b6 | code | 2054 | for func in (:daily, :weekly, :monthly)
x = "digital_currency_$(func)"
fname = Symbol(x)
@eval begin
function ($fname)(symbol::String, market::String="USD"; client = GLOBAL[], outputsize::String="compact", datatype::Union{String, Nothing}=nothing, parser = "default")
@argcheck in(outputsize, ["compact", "full"])
@argcheck in(datatype, ["json", "csv", nothing])
params = Dict(
"function"=>uppercase($x),
"symbol"=>symbol,
"market"=>market,
"outputsize"=>outputsize,
"datatype"=>isnothing(datatype) ? "csv" : datatype,
"apikey"=>key(client)
)
uri = _build_uri(client.scheme, client.host, "query", params)
data = retry(_get_request, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))(uri)
p = _parser(parser, datatype)
return p(data)
end
export $fname
end
end
function digital_currency_intraday(symbol::String, market::String="USD", interval::String="1min"; client = GLOBAL[], outputsize::String="compact", datatype::Union{String, Nothing}=nothing, parser = "default")
@argcheck in(outputsize, ["compact", "full"])
@argcheck in(datatype, ["json", "csv", nothing])
@argcheck in(interval, ["1min", "5min", "15min", "30min", "60min"])
params = Dict(
"function"=>"CRYPTO_INTRADAY",
"symbol"=>symbol,
"market"=>market,
"interval"=>interval,
"outputsize"=>outputsize,
"datatype"=>isnothing(datatype) ? "csv" : datatype,
"apikey"=>key(client)
)
uri = _build_uri(client.scheme, client.host, "query", params)
data = retry(_get_request, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))(uri)
p = _parser(parser, datatype)
return p(data)
end
function crypto_rating(symbol::String; client = GLOBAL[], parser = "default")
@warn("crypto_rating no longer provided by AlphaVantage")
return nothing
end
| AlphaVantage | https://github.com/ellisvalentiner/AlphaVantage.jl.git |
|
[
"MIT"
] | 0.4.1 | 893a38118dc5a7554a52bbbc58d6de591e58f7b6 | code | 3639 |
function real_gdp(interval::String = "annual"; client=GLOBAL[], datatype::Union{String, Nothing}=nothing, parser = "default")
@argcheck in(interval, ["quarterly", "annual"])
@argcheck in(datatype, ["json", "csv", nothing])
params = Dict(
"function" => "REAL_GDP",
"interval" => interval,
"datatype" => isnothing(datatype) ? "csv" : datatype,
"apikey" => key(client)
)
uri = _build_uri(client.scheme, client.host, "query", params)
data = retry(_get_request, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))(uri)
p = _parser(parser, datatype)
return p(data)
end
function treasury_yield(interval::String = "monthly", maturity::String = "10year"; client=GLOBAL[], datatype::Union{String, Nothing}=nothing, parser = "default")
@argcheck in(interval, ["daily", "weekly", "monthly", nothing])
@argcheck in(maturity, ["3month", "5year", "10year", "30year", nothing])
@argcheck in(datatype, ["json", "csv", nothing])
params = Dict(
"function" => "TREASURY_YIELD",
"interval" => interval,
"maturity" => maturity,
"datatype" => isnothing(datatype) ? "csv" : datatype,
"apikey" => key(client)
)
uri = _build_uri(client.scheme, client.host, "query", params)
data = retry(_get_request, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))(uri)
p = _parser(parser, datatype)
return p(data)
end
function federal_fund_rate(interval::String = "monthly"; client=GLOBAL[], datatype::Union{String, Nothing}=nothing, parser = "default")
@argcheck in(interval, ["daily", "weekly", "monthly", nothing])
@argcheck in(datatype, ["json", "csv", nothing])
params = Dict(
"function" => "FEDERAL_FUNDS_RATE",
"interval" => interval,
"datatype" => isnothing(datatype) ? "csv" : datatype,
"apikey" => key(client)
)
uri = _build_uri(client.scheme, client.host, "query", params)
data = retry(_get_request, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))(uri)
p = _parser(parser, datatype)
return p(data)
end
function cpi(interval::String = "monthly"; client=GLOBAL[], datatype::Union{String, Nothing}=nothing, parser = "default")
@argcheck in(interval, ["monthly", "semiannual", nothing])
@argcheck in(datatype, ["json", "csv", nothing])
params = Dict(
"function" => "CPI",
"datatype" => isnothing(datatype) ? "csv" : datatype,
"apikey" => key(client)
)
uri = _build_uri(client.scheme, client.host, "query", params)
data = retry(_get_request, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))(uri)
p = _parser(parser, datatype)
return p(data)
end
for func in (:real_gdp_per_capita, :inflation,
:inflation_expectation, :consumer_sentiment,
:retail_sales, :durables,
:unemployment, :nonfarm_payroll)
@eval begin
function $(func)(; client = GLOBAL[], datatype::Union{String, Nothing}=nothing, parser = "default")
@argcheck in(datatype, ["json", "csv", nothing])
params = Dict(
"function"=>uppercase($(String(func))),
"datatype"=>isnothing(datatype) ? "csv" : datatype,
"apikey"=>key(client)
)
uri = _build_uri(client.scheme, client.host, "query", params)
data = retry(_get_request, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))(uri)
p = _parser(parser, datatype)
return p(data)
end
export $func
end
end
| AlphaVantage | https://github.com/ellisvalentiner/AlphaVantage.jl.git |
|
[
"MIT"
] | 0.4.1 | 893a38118dc5a7554a52bbbc58d6de591e58f7b6 | code | 3049 | function currency_exchange_rate(from_currency::String, to_currency::String; client = GLOBAL[], parser = "default")
params = Dict(
"function"=>"CURRENCY_EXCHANGE_RATE",
"from_currency"=>from_currency,
"to_currency"=>to_currency,
"apikey"=>key(client)
)
uri = _build_uri(client.scheme, client.host, "query", params)
data = retry(_get_request, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))(uri)
p = _parser(parser, "json")
return p(data)
end
function fx_intraday(from_currency::String, to_currency::String, interval::String="1min"; client = GLOBAL[], outputsize::String="compact", datatype::Union{String, Nothing}=nothing, parser = "default")
@argcheck in(interval, ["1min", "5min", "15min", "30min", "60min"])
@argcheck in(outputsize, ["compact", "full"])
@argcheck in(datatype, ["json", "csv", nothing])
params = Dict(
"function"=>"FX_INTRADAY",
"from_symbol"=>from_currency,
"to_symbol"=>to_currency,
"interval"=>interval,
"outputsize"=>outputsize,
"datatype"=>isnothing(datatype) ? "csv" : datatype,
"apikey"=>key(client)
)
uri = _build_uri(client.scheme, client.host, "query", params)
data = retry(_get_request, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))(uri)
p = _parser(parser, datatype)
return p(data)
end
function fx_daily(from_currency::String, to_currency::String; client = GLOBAL[], outputsize::String="compact", datatype::Union{String, Nothing}=nothing, parser = "default")
@argcheck in(outputsize, ["compact", "full"])
@argcheck in(datatype, ["json", "csv", nothing])
params = Dict(
"function"=>"FX_DAILY",
"from_symbol"=>from_currency,
"to_symbol"=>to_currency,
"outputsize"=>outputsize,
"datatype"=>isnothing(datatype) ? "csv" : datatype,
"apikey"=>key(client)
)
uri = _build_uri(client.scheme, client.host, "query", params)
data = retry(_get_request, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))(uri)
p = _parser(parser, datatype)
return p(data)
end
for func in (:weekly, :monthly)
x = "fx_$(func)"
fname = Symbol(x)
@eval begin
function ($fname)(from_currency::String, to_currency::String; client = GLOBAL[], datatype::Union{String, Nothing}=nothing, parser = "default")
@argcheck in(datatype, ["json", "csv", nothing])
params = Dict(
"function"=>uppercase($x),
"from_symbol"=>from_currency,
"to_symbol"=>to_currency,
"datatype"=>isnothing(datatype) ? "csv" : datatype,
"apikey"=>key(client)
)
uri = _build_uri(client.scheme, client.host, "query", params)
data = retry(_get_request, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))(uri)
p = _parser(parser, datatype)
return p(data)
end
export $fname
end
end
| AlphaVantage | https://github.com/ellisvalentiner/AlphaVantage.jl.git |
|
[
"MIT"
] | 0.4.1 | 893a38118dc5a7554a52bbbc58d6de591e58f7b6 | code | 4648 | COMPANY_OVERVIEW_KEYS = ["SharesOutstanding",
"ExDividendDate",
"52WeekLow",
"ReturnOnEquityTTM",
"LatestQuarter",
"200DayMovingAverage",
"EVToEBITDA",
"RevenuePerShareTTM",
"Beta",
"Sector",
"ForwardAnnualDividendYield",
"Exchange",
"PercentInsiders",
"QuarterlyEarningsGrowthYOY",
"Currency",
"EBITDA",
"ShortRatio",
"DividendYield",
"AnalystTargetPrice",
"DilutedEPSTTM",
"BookValue",
"LastSplitDate",
"SharesFloat",
"PriceToSalesRatioTTM",
"FullTimeEmployees",
"ShortPercentOutstanding",
"52WeekHigh",
"ReturnOnAssetsTTM",
"PayoutRatio",
"PriceToBookRatio",
"Symbol",
"QuarterlyRevenueGrowthYOY",
"DividendDate",
"ProfitMargin",
"50DayMovingAverage",
"LastSplitFactor",
"RevenueTTM",
"PEGRatio",
"OperatingMarginTTM",
"Industry",
"ForwardPE",
"EVToRevenue",
"ForwardAnnualDividendRate",
"ShortPercentFloat",
"SharesShortPriorMonth",
"TrailingPE",
"SharesShort",
"Country",
"Address",
"EPS",
"GrossProfitTTM",
"Name",
"MarketCapitalization",
"PERatio",
"DividendPerShare",
"Description",
"FiscalYearEnd",
"AssetType",
"PercentInstitutions"]
COMMON_KEYS = ["reportedCurrency", "netIncome"]
COMMON = [[("quarterlyReports", "income_statement", x, "fiscalDateEnding") for x in COMMON_KEYS];
[("annualReports", "income_statement", x, "fiscalDateEnding") for x in COMMON_KEYS]]
INCOME_STATEMENT_KEYS = [
"incomeTaxExpense",
"otherNonOperatingIncome",
"minorityInterest",
"discontinuedOperations",
"incomeBeforeTax",
"totalOtherIncomeExpense",
"interestIncome",
"researchAndDevelopment",
"grossProfit",
"totalRevenue",
"otherOperatingExpense",
"taxProvision",
"extraordinaryItems",
"ebit",
"otherItems",
"netIncomeApplicableToCommonShares",
"totalOperatingExpense",
"costOfRevenue",
"interestExpense",
"sellingGeneralAdministrative",
"operatingIncome",
"netIncomeFromContinuingOperations",
"netInterestIncome",
"effectOfAccountingCharges",
"nonRecurring",
"preferredStockAndOtherAdjustments"]
INCOME_STATEMENT = [[("quarterlyReports", "income_statement", x, "fiscalDateEnding") for x in INCOME_STATEMENT_KEYS];
[("annualReports", "income_statement", x, "fiscalDateEnding") for x in INCOME_STATEMENT_KEYS]]
BALANCE_SHEET_KEYS = ["totalPermanentEquity",
"warrants",
"negativeGoodwill",
"preferredStockTotalEquity",
"accumulatedAmortization",
"inventory",
"additionalPaidInCapital",
"commonStockTotalEquity",
"longTermInvestments",
"netTangibleAssets",
"cashAndShortTermInvestments",
"longTermDebt",
"otherShareholderEquity",
"totalCurrentAssets",
"treasuryStock",
"otherAssets",
"capitalSurplus",
"totalNonCurrentAssets",
"accountsPayable",
"totalNonCurrentLiabilities",
"otherLiabilities",
"totalShareholderEquity",
"liabilitiesAndShareholderEquity",
"otherCurrentAssets",
"totalCurrentLiabilities",
"otherNonCurrrentAssets",
"shortTermDebt",
"commonStockSharesOutstanding",
"capitalLeaseObligations",
"netReceivables",
"retainedEarningsTotalEquity",
"earningAssets",
"totalAssets",
"commonStock",
"cash",
"deferredLongTermLiabilities",
"totalLongTermDebt",
"retainedEarnings",
"shortTermInvestments",
"propertyPlantEquipment",
"goodwill",
"preferredStockRedeemable",
"totalLiabilities",
"otherNonCurrentLiabilities",
"currentLongTermDebt",
"intangibleAssets",
"accumulatedDepreciation",
"otherCurrentLiabilities",
"deferredLongTermAssetCharges"]
BALANCE_SHEET = [[("quarterlyReports", "balance_sheet", x, "fiscalDateEnding") for x in BALANCE_SHEET_KEYS];
[("annualReports", "balance_sheet", x, "fiscalDateEnding") for x in BALANCE_SHEET_KEYS]]
CASH_FLOW_KEYS = ["cashflowFromInvestment",
"changeInInventory",
"changeInAccountReceivables",
"changeInCashAndCashEquivalents",
"otherOperatingCashflow",
"dividendPayout",
"changeInReceivables",
"capitalExpenditures",
"changeInExchangeRate",
"operatingCashflow",
"cashflowFromFinancing",
"changeInLiabilities",
"stockSaleAndPurchase",
"otherCashflowFromFinancing",
"changeInOperatingActivities",
"depreciation",
"changeInCash",
"netBorrowings",
"investments",
"changeInNetIncome",
"otherCashflowFromInvestment"]
CASH_FLOW = [[("quarterlyReports", "cash_flow", x, "fiscalDateEnding") for x in CASH_FLOW_KEYS];
[("annualReports", "cash_flow", x, "fiscalDateEnding") for x in CASH_FLOW_KEYS]]
EARNINGS_KEYS_Q = ["reportedDate",
"estimatedEPS",
"surprise",
"surprisePercentage",
"reportedEPS"]
EARNINGS_KEYS_A = ["reportedEPS"]
EARNINGS = [[("quarterlyEarnings", "earnings", x, "reportedDate") for x in EARNINGS_KEYS_Q];
[("annualEarnings", "earnings", x, "fiscalDateEnding") for x in EARNINGS_KEYS_A]]
FUNDAMENTAL_VALUES = vcat(INCOME_STATEMENT, BALANCE_SHEET, CASH_FLOW, EARNINGS) | AlphaVantage | https://github.com/ellisvalentiner/AlphaVantage.jl.git |
|
[
"MIT"
] | 0.4.1 | 893a38118dc5a7554a52bbbc58d6de591e58f7b6 | code | 3264 | function _fundamental(func::String, symbol::String; client = GLOBAL[], outputsize::String="compact", datatype::Union{String, Nothing}=nothing, parser = "default")
@argcheck in(datatype, ["json", "csv", nothing])
params = Dict(
"function"=>func,
"symbol"=>symbol,
"outputsize"=>outputsize,
"datatype"=>datatype,
"apikey"=>key(client)
)
uri = _build_uri(client.scheme, client.host, "query", params)
data = retry(_get_request, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))(uri)
p = _parser(parser, datatype)
return p(data)
end
company_overview(symbol::String; kwargs...) = _fundamental("OVERVIEW", symbol::String; kwargs...)
income_statement(symbol::String; kwargs...) = _fundamental("INCOME_STATEMENT", symbol::String; kwargs...)
balance_sheet(symbol::String; kwargs...) = _fundamental("BALANCE_SHEET", symbol::String; kwargs...)
cash_flow(symbol::String; kwargs...) = _fundamental("CASH_FLOW", symbol::String; kwargs...)
earnings(symbol::String; kwargs...) = _fundamental("EARNINGS", symbol::String; kwargs...)
# Listing Status (https://www.alphavantage.co/documentation/#listing-status)
# ex: https://www.alphavantage.co/query?function=LISTING_STATUS&apikey=demo
function listing_status(; client = GLOBAL[], date = nothing, state = nothing, parser = "default")
query = ""
if !isnothing(state)
@argcheck in(state, ["active", "delisted"])
query *= "&state=$state"
end
!isnothing(date) && (query *= "&date=$date")
params = Dict(
"function"=>"LISTING_STATUS",
"date"=>date,
"state"=>state,
"apikey"=>key(client)
)
uri = _build_uri(client.scheme, client.host, "query", params)
data = retry(_get_request, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))(uri)
p = _parser(parser, "csv")
return p(data)
end
for (timeframe, f, value, dateKey) in FUNDAMENTAL_VALUES
timeframeF = replace(timeframe, "Report"=>"")
timeframeF = replace(timeframeF, "Earnings"=>"")
fname = Symbol(value * "_" * timeframeF)
fS = Symbol(f)
@eval begin
function $fname(symbol::String; kwargs...)
data = $fS(symbol; kwargs...)
dts = get.(data[$timeframe], $dateKey, "")
vals = get.(data[$timeframe], $value, "")
Dict(:Date => dts, Symbol($value)=>vals)
end
export $fname
end
end
function earnings_calendar(horizon::Int64; client=GLOBAL[], parser = "default")
params = Dict(
"function"=>"EARNINGS_CALENDAR",
"horizon"=>"$(horizon)month",
"apikey"=>key(client)
)
uri = _build_uri(client.scheme, client.host, "query", params)
data = retry(_get_request, delays=Base.ExponentialBackOff(n=3, first_delay=4, max_delay=1000))(uri)
p = _parser(parser, "csv")
return p(data)
end
function ipo_calendar(; client = GLOBAL[], parser = "default")
params = Dict(
"function"=>"IPO_CALENDAR",
"apikey"=>key(client)
)
uri = _build_uri(client.scheme, client.host, "query", params)
data = retry(_get_request, delays=Base.ExponentialBackOff(n=3, first_delay=4, max_delay=1000))(uri)
p = _parser(parser, "csv")
return p(data)
end
| AlphaVantage | https://github.com/ellisvalentiner/AlphaVantage.jl.git |
|
[
"MIT"
] | 0.4.1 | 893a38118dc5a7554a52bbbc58d6de591e58f7b6 | code | 536 | function sector_performance(; client = GLOBAL[], datatype::Union{String, Nothing}=nothing, parser = "default")
@argcheck in(datatype, ["json", "csv", nothing])
params = Dict(
"function"=>"SECTOR",
"datatype"=>isnothing(datatype) ? "csv" : datatype,
"apikey"=>key(client)
)
uri = _build_uri(client.scheme, client.host, "query", params)
data = retry(_get_request, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))(uri)
p = _parser(parser, datatype)
return p(data)
end
| AlphaVantage | https://github.com/ellisvalentiner/AlphaVantage.jl.git |
|
[
"MIT"
] | 0.4.1 | 893a38118dc5a7554a52bbbc58d6de591e58f7b6 | code | 5326 | interval_indicators = ["VWAP", "AD", "OBV",
"TRANGE", "STOCH", "STOCHF", "BOP",
"ULTOSC", "SAR", "ADOSC"]
for func in interval_indicators
fname = Symbol(func)
@eval begin
function ($fname)(symbol::String, interval::String; client = GLOBAL[], datatype::Union{String, Nothing}=nothing, parser = "default", kwargs...)
@argcheck in(interval, ["1min", "5min", "15min", "30min", "60min", "daily", "weekly", "monthly"])
params = Dict(
"function"=>uppercase($func),
"symbol"=>symbol,
"interval"=>interval,
"datatype"=>isnothing(datatype) ? "csv" : datatype,
kwargs...,
"apikey"=>key(client)
)
uri = _build_uri(client.scheme, client.host, "query", params)
data = retry(_get_request, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))(uri)
p = _parser(parser, datatype)
return p(data)
end
export $fname
end
end
interval_seriestype_indicators = ["HT_TRENDLINE", "HT_SINE", "HT_TRENDMODE",
"HT_DCPERIOD", "HT_DCPHASE", "HT_PHASOR",
"MACD", "MAMA", "MACDEXT", "APO", "PPO"]
for func in interval_seriestype_indicators
fname = Symbol(func)
@eval begin
function ($fname)(symbol::String, interval::String, series_type::String; client = GLOBAL[], datatype::Union{String, Nothing}=nothing, parser = "default", kwargs...)
@argcheck in(interval, ["1min", "5min", "15min", "30min", "60min", "daily", "weekly", "monthly"])
@argcheck in(series_type, ["open", "high", "low", "close"])
params = Dict(
"function"=>uppercase($func),
"symbol"=>symbol,
"interval"=>interval,
"series_type"=>series_type,
"datatype"=>isnothing(datatype) ? "csv" : datatype,
kwargs...,
"apikey"=>key(client)
)
uri = _build_uri(client.scheme, client.host, "query", params)
data = retry(_get_request, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))(uri)
p = _parser(parser, datatype)
return p(data)
end
export $fname
end
end
interval_timeperiod_indicators = ["ADX", "ADXR",
"AROON", "NATR", "WILLR",
"CCI", "AROONOSC", "MFI",
"DX", "MINUS_DI", "PLUS_DI",
"MINUS_DM", "PLUS_DM", "ATR"]
for func in interval_timeperiod_indicators
fname = Symbol(func)
@eval begin
function ($fname)(symbol::String, interval::String, time_period::Int64; client = GLOBAL[], datatype::Union{String, Nothing}=nothing, parser = "default", kwargs...)
@argcheck in(interval, ["1min", "5min", "15min", "30min", "60min", "daily", "weekly", "monthly"])
@argcheck time_period > 0
params = Dict(
"function"=>uppercase($func),
"symbol"=>symbol,
"interval"=>interval,
"time_period"=>time_period,
"datatype"=>isnothing(datatype) ? "csv" : datatype,
kwargs...,
"apikey"=>key(client)
)
uri = _build_uri(client.scheme, client.host, "query", params)
data = retry(_get_request, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))(uri)
p = _parser(parser, datatype)
return p(data)
end
export $fname
end
end
interval_timeperiod_seriestype_indicators = ["EMA", "SMA", "WMA",
"DEMA", "TEMA", "TRIMA",
"KAMA", "RSI", "T3",
"STOCHRSI", "MOM", "CMO",
"ROC", "ROCR", "TRIX",
"BBANDS", "MIDPOINT", "MIDPRICE"]
for func in interval_timeperiod_seriestype_indicators
fname = Symbol(func)
@eval begin
function ($fname)(symbol::String, interval::String, time_period::Int64, series_type::String; client = GLOBAL[], datatype::Union{String, Nothing}=nothing, parser = "default", kwargs...)
@argcheck in(interval, ["1min", "5min", "15min", "30min", "60min", "daily", "weekly", "monthly"])
@argcheck in(series_type, ["open", "high", "low", "close"])
@argcheck time_period > 0
params = Dict(
"function"=>uppercase($func),
"symbol"=>symbol,
"interval"=>interval,
"time_period"=>time_period,
"series_type"=>series_type,
"datatype"=>isnothing(datatype) ? "csv" : datatype,
kwargs...,
"apikey"=>key(client)
)
uri = _build_uri(client.scheme, client.host, "query", params)
data = retry(_get_request, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))(uri)
p = _parser(parser, datatype)
return p(data)
end
export $fname
end
end
| AlphaVantage | https://github.com/ellisvalentiner/AlphaVantage.jl.git |
|
[
"MIT"
] | 0.4.1 | 893a38118dc5a7554a52bbbc58d6de591e58f7b6 | code | 2752 | function time_series_intraday_extended(symbol::String, interval::String="60min", slice::String="year1month1"; client = GLOBAL[], parser = "default")
@argcheck in(interval, ["1min", "5min", "15min", "30min", "60min"])
sliceMatch = match(r"year(?<year>\d+)month(?<month>\d+)", slice)
@argcheck !Compat.isnothing(sliceMatch)
@argcheck parse(Int, sliceMatch["year"]) > 0
@argcheck parse(Int, sliceMatch["year"]) < 3
@argcheck parse(Int, sliceMatch["month"]) > 0
@argcheck parse(Int, sliceMatch["month"]) < 13
params = Dict(
"function"=>"TIME_SERIES_INTRADAY_EXTENDED",
"symbol"=>symbol,
"interval"=>interval,
"slice"=>slice,
"apikey"=>key(client)
)
uri = _build_uri(client.scheme, client.host, "query", params)
data = retry(_get_request, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))(uri)
p = _parser(parser, "csv")
return p(data)
end
function time_series_intraday(symbol::String, interval::String="1min"; client = GLOBAL[], outputsize::String="compact", datatype::Union{String, Nothing}=nothing, parser = "default")
@argcheck in(interval, ["1min", "5min", "15min", "30min", "60min"])
@argcheck in(outputsize, ["compact", "full"])
@argcheck in(datatype, ["json", "csv", nothing])
params = Dict(
"function"=>"TIME_SERIES_INTRADAY",
"symbol"=>symbol,
"interval"=>interval,
"outputsize"=>outputsize,
"datatype"=>datatype,
"apikey"=>key(client)
)
uri = _build_uri(client.scheme, client.host, "query", params)
data = retry(_get_request, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))(uri)
p = _parser(parser, datatype)
return p(data)
end
for func in (:daily, :daily_adjusted, :weekly, :weekly_adjusted, :monthly, :monthly_adjusted)
x = "time_series_$(func)"
fname = Symbol(x)
@eval begin
function ($fname)(symbol::String; client = GLOBAL[], outputsize::String="compact", datatype::Union{String, Nothing}=nothing, parser = "default")
@argcheck in(outputsize, ["compact", "full"])
@argcheck in(datatype, ["json", "csv", nothing])
params = Dict(
"function"=>uppercase($x),
"symbol"=>symbol,
"outputsize"=>outputsize,
"datatype"=>isnothing(datatype) ? "csv" : datatype,
"apikey"=>key(client)
)
uri = _build_uri(client.scheme, client.host, "query", params)
data = retry(_get_request, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))(uri)
p = _parser(parser, datatype)
return p(data)
end
export $fname
end
end
| AlphaVantage | https://github.com/ellisvalentiner/AlphaVantage.jl.git |
|
[
"MIT"
] | 0.4.1 | 893a38118dc5a7554a52bbbc58d6de591e58f7b6 | code | 1906 | """
Internal function that wraps HTTP.get
"""
function _get_request(uri::String)
resp = HTTP.get(uri)
_check_api_limit(resp)
_check_status_code(resp)
return resp
end
"""
Internal function to check whether the response contains
'Note' that indicates the API limit was reached
"""
function _check_api_limit(resp::HTTP.Messages.Response)
content_type = HTTP.Messages.header(resp.headers, "Content-Type")
if content_type == "application/json"
body = _parse_response(resp, "json")
if haskey(body, "Note")
error("API limit exceeded")
end
end
end
"""
Internal function to check response status code
"""
function _check_status_code(resp::HTTP.Messages.Response)
if resp.status != 200
error("Expected status code 200 but received $resp.status")
end
end
"""
Internal function that parses the response
"""
function _parse_response(data, datatype::Union{String, Nothing})
if datatype == "csv"
return readdlm(data.body, ',', header=true)
elseif datatype == "json"
body = copy(data.body) # TODO: re-write to avoid copying
return JSON.Parser.parse(String(body))
else
raw = readdlm(data.body, ',', header=true)
return AlphaVantageResponse(raw)
end
end
"""
Internal function to build the request URI
"""
function _build_uri(scheme::String, host::String, path::String, params::Dict)
@argcheck in(scheme, ["https", "http"])
params = filter(p -> !isnothing(p.second), params)
params = collect(pairs(params))
query = join(map(p -> "$(p.first)=$(p.second)", params), "&")
return "$(scheme)://$(host)/$(path)?$(query)"
end
_parser(p, datatype) = p
function _parser(p::AbstractString, datatype)
if p == "default"
return x -> _parse_response(x, datatype)
else
# if parser is unknown, then return raw data
return identity
end
end
| AlphaVantage | https://github.com/ellisvalentiner/AlphaVantage.jl.git |
|
[
"MIT"
] | 0.4.1 | 893a38118dc5a7554a52bbbc58d6de591e58f7b6 | code | 522 | module TestClient
using AlphaVantage
using Test
client = AlphaVantage.GLOBAL[]
@testset "Client" begin
client = AlphaVantageClient(scheme="http", key="demo", host="www.alphavantage.co")
@test isa(client, AlphaVantageClient)
@test !isempty(client.scheme)
@test !isempty(client.key)
@test !isempty(client.host)
old_key = client.key;
client.key = "demo"
@test client.key === "demo"
client.key = ""
@test_logs (:warn, "No API key found") key(client)
client.key = old_key;
end
end
| AlphaVantage | https://github.com/ellisvalentiner/AlphaVantage.jl.git |
|
[
"MIT"
] | 0.4.1 | 893a38118dc5a7554a52bbbc58d6de591e58f7b6 | code | 1292 | module TestDigitalCurrency
using AlphaVantage
using Test
TEST_SLEEP_TIME = parse(Float64, get(ENV, "TEST_SLEEP_TIME", "15"))
MAX_TESTS = parse(Int64, get(ENV, "MAX_TESTS", "1"))
@testset "Digital Currencies" begin
for f in (:digital_currency_daily, :digital_currency_weekly, :digital_currency_monthly, :digital_currency_intraday)
@eval begin
testname = string($f)
@testset "$testname" begin
@testset "AlphaVantageResponse" begin
data = $f("MSFT")
@test isa(data, AlphaVantageResponse)
end
sleep(TEST_SLEEP_TIME + 2*rand())
@testset "JSON" begin
data = $f("BTC", datatype = "json")
@test typeof(data) === Dict{String,Any}
@test length(data) === 2
end
sleep(TEST_SLEEP_TIME + 2*rand())
@testset "CSV" begin
data = $f("BTC", datatype = "csv")
@test typeof(data) === Tuple{Array{Any, 2}, Array{AbstractString, 2}}
@test length(data) === 2
end
end
end
sleep(TEST_SLEEP_TIME + 2*rand()) #as to not overload the API
end
end
end # module
| AlphaVantage | https://github.com/ellisvalentiner/AlphaVantage.jl.git |
|
[
"MIT"
] | 0.4.1 | 893a38118dc5a7554a52bbbc58d6de591e58f7b6 | code | 797 | module TestEconmicIndicators
using AlphaVantage
using Test
TEST_SLEEP_TIME = parse(Float64, get(ENV, "TEST_SLEEP_TIME", "15"))
MAX_TESTS = parse(Int64, get(ENV, "MAX_TESTS", "1"))
@testset "Economic Indicators" begin
@testset "Real GDP" begin
res = real_gdp()
@test length(res.names) == 2
end
@testset "Treasury Yield" begin
res = treasury_yield("monthly", "3month")
@test length(res.names) == 2
end
@testset "Federal Fund Rate" begin
res = federal_fund_rate("weekly")
@test length(res.names) == 2
end
@testset "CPI" begin
res = cpi("semiannual")
@test length(res.names) == 2
end
@testset "Inflation" begin
res = inflation()
@test length(res.names) == 2
end
end
end | AlphaVantage | https://github.com/ellisvalentiner/AlphaVantage.jl.git |
|
[
"MIT"
] | 0.4.1 | 893a38118dc5a7554a52bbbc58d6de591e58f7b6 | code | 1352 | module TestForeignExchangeCurrency
using AlphaVantage
using Test
TEST_SLEEP_TIME = parse(Float64, get(ENV, "TEST_SLEEP_TIME", "15"))
MAX_TESTS = parse(Int64, get(ENV, "MAX_TESTS", "1"))
@testset "Foreign Exchange Currency" begin
@testset "currency_exchange_rate" begin
data = currency_exchange_rate("BTC", "USD")
@test typeof(data) === Dict{String,Any}
@test length(data) === 1
sleep(TEST_SLEEP_TIME + 2*rand()) #as to not overload the API
end
@testset "fx_intraday" begin
data = fx_intraday("EUR", "USD", datatype="json")
@test typeof(data) === Dict{String,Any}
@test length(data) === 2
sleep(TEST_SLEEP_TIME + 2*rand())
end
@testset "fx_daily" begin
data = fx_daily("EUR", "USD", datatype="json")
@test typeof(data) === Dict{String,Any}
@test length(data) === 2
sleep(TEST_SLEEP_TIME + 2*rand())
end
for f in (:fx_weekly, :fx_monthly)[1:MAX_TESTS]
@eval begin
testname = string($f)
@testset "$testname" begin
data = $f("EUR", "USD", datatype="json")
@test typeof(data) === Dict{String,Any}
@test length(data) === 2
end
end
sleep(TEST_SLEEP_TIME + 2*rand()) #as to not overload the API
end
end
end # module
| AlphaVantage | https://github.com/ellisvalentiner/AlphaVantage.jl.git |
|
[
"MIT"
] | 0.4.1 | 893a38118dc5a7554a52bbbc58d6de591e58f7b6 | code | 1109 | module TestFundamentalValues
using AlphaVantage
using Test
TEST_SLEEP_TIME = parse(Float64, get(ENV, "TEST_SLEEP_TIME", "15"))
MAX_TESTS = parse(Int64, get(ENV, "MAX_TESTS", "1"))
@testset "Fundamental Values" begin
vals = rand([AlphaVantage.INCOME_STATEMENT_KEYS;
AlphaVantage.CASH_FLOW_KEYS;
AlphaVantage.BALANCE_SHEET_KEYS;
AlphaVantage.EARNINGS_KEYS_Q;
AlphaVantage.EARNINGS_KEYS_A], MAX_TESTS)
for val in vals
@testset "$val" begin
@testset "Annual" begin
fnameA = Symbol(val * "_" * "annuals")
@eval begin
aRes = $(fnameA)("AAPL", datatype="json")
@test length(aRes) == 2
end
end
sleep(TEST_SLEEP_TIME + 2*rand())
@testset "Quarterly" begin
fnameQ = Symbol(val * "_" * "quarterlys")
@eval begin
qRes = $(fnameQ)("AAPL", datatype="json")
@test length(qRes) == 2
end
end
end
sleep(TEST_SLEEP_TIME + 2*rand()) #as to not overload the API
end
end
end # module
| AlphaVantage | https://github.com/ellisvalentiner/AlphaVantage.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.