-
Notifications
You must be signed in to change notification settings - Fork 3
/
text_utils.py
63 lines (51 loc) · 1.55 KB
/
text_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import base64
def string_to_file(
text: str,
filename: str = "myfile",
download_text: str = "Download File",
) -> str:
"""
>>> string_to_file(
text: str,
filename: str = "myfile",
download_text: str = "Download File"
) -> str
Generates a downloadable text file containing the given text.
Parameters
----------
text : str
Text to be downloaded
filename : str, optional
Name of the download file. Defaults to `"myfile"`.
download_text : str, optional
Text to be displayed as the download link. Defaults to `"Download File"`.
Returns
-------
* `str` :
HTML download link
Raises
------
* `TypeError` :
If the input text is not a string.
Examples
--------
**Default usage**:
>>> download_link = msc.string_to_file("Hello World")
>>> return {"download_link": download_link}
**Custom Filename and Download Text**:
>>> download_link = msc.string_to_file(
"Hello World",
filename="mytextfile",
download_text="Download File Here"
)
>>> return {"download_link": download_link}
"""
if not isinstance(text, str):
raise TypeError("text must be a string")
if filename.endswith(".txt"):
filename = filename[:-4]
# Encode to a text file
encoded_text = base64.b64encode(text.encode()).decode()
mime_type = "data:text/plain;base64,"
encoded_file = mime_type + encoded_text
return f"<a href='{encoded_file}' download='{filename}.txt'>{download_text}</a>"