Plotly Texto da nota: codificação Hash (#character) em uma URL

0

Pergunta

Em um plotly traço app, eu tenho uma anotação de texto com um link que tem um hash nele.

topic = "Australia"  # might contain spaces
hashtag = "#" + topic

annotation_text=f"<a href=\"https://twitter.com/search?q={urllib.parse.quote_plus(hashtag)}&src=typed_query&f=live\">{topic}</a>"

Eu preciso de html de saída para conter "https://twitter.com/search?q=%23Australia&src=typed_query&f=live" mas eu não posso obter o caractere "#" para codificar corretamente. Ele obtém o dobro codificado para %2523.


O Mínimo De Trabalho De Exemplo:

import dash
from dash.dependencies import Input, Output
import plotly.express as px
import urllib.parse

df = px.data.gapminder()
all_continents = df.continent.unique()

app = dash.Dash(__name__)

app.layout = dash.html.Div([
    dash.dcc.Checklist(
        id="checklist",
        options=[{"label": x, "value": x}
                 for x in all_continents],
        value=all_continents[4:],
        labelStyle={'display': 'inline-block'}
    ),
    dash.dcc.Graph(id="line-chart"),
])


@app.callback(
    Output("line-chart", "figure"),
    [Input("checklist", "value")])
def update_line_chart(continents):
    mask = df.continent.isin(continents)
    fig = px.line(df[mask],
                  x="year", y="lifeExp", color='country')
    annotations = []
    df_last_value = df[mask].sort_values(['country', 'year', ]).drop_duplicates('country', keep='last')
    for topic, year, last_lifeExp_value in zip(df_last_value.country, df_last_value.year, df_last_value.lifeExp):
        hashtag = "#" + topic
        annotations.append(dict(xref='paper', x=0.95, y=last_lifeExp_value,
                                xanchor='left', yanchor='middle',
                                text=f"<a href=\"https://twitter.com/search?q={urllib.parse.quote_plus(hashtag)}&src=typed_query&f=live\">{topic}</a>",
                                # text=f"<a href=\"https://twitter.com/search?q=#{urllib.parse.quote_plus(topic)}&src=typed_query&f=live\">{topic}</a>",

                                font=dict(family='Arial',
                                          size=16),
                                showarrow=False))

    fig.update_layout(annotations=annotations)
    return fig


app.run_server(debug=True)

Quando você executar este e clique no texto "Austrália" no final do gráfico de linha, ele deve abrir um twitter página de pesquisa para o #Austrália.


O que eu tentei:

  1. usando apenas um simples caractere"#": text=f"<a href=\"https://twitter.com/search?q=#{urllib.parse.quote_plus(topic)}&src=typed_query&f=live\">{topic}</a>"

Aqui, o caractere # não é codificado como %23 na saída, o que resulta em um link quebrado para o twitter.

https://twitter.com/search?q=#mytopic&amp;src=typed_query&amp;f=live link

  1. usando quote_plus na hashtag text=f"<a href=\"https://twitter.com/search?q=#{urllib.parse.quote_plus(hashtag)}&src=typed_query&f=live\">{topic}</a>"

Aqui, o %23 (codificado caractere#) é codificado novamente, resultando em %2523 na saída.

https://twitter.com/search?q=%2523mytopic&amp;src=typed_query&amp;f=livelink


Como eu faço para codificar corretamente a # (a %23) então, eu tenho a

href="https://twitter.com/search?q=%23mytopic&amp;src=typed_query&amp;f=live

flask plotly plotly-dash python
2021-11-24 04:05:26
1

Melhor resposta

1

É um bug conhecido: plotly/plotly.js#4084

Linha ofensiva em plotly.js:

nodeSpec.href = encodeURI(decodeURI(href));
  • decodeURI não decodificar %23 (decodeURIComponent faz).
  • encodeURI não codificar # mas codifica % (encodeURIComponent não tanto).

Mais sobre isso: Qual é a diferença entre decodeURIComponent e decodeURI?

Solução alternativa

Você pode substituir o built-in encodeURI para reverter a codificação de % no %23:

app._inline_scripts.append('''
_encodeURI = encodeURI;
encodeURI = uri => _encodeURI(uri).replace('%2523', '%23');
''')
2021-12-03 07:04:19

Em outros idiomas

Esta página está em outros idiomas

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................