File size: 1,469 Bytes
3caba89
89b19fb
3caba89
89b19fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio
import os

# basic storage using /dat
def store_data(data):
    if not data:
        return "no request", 400
    if not data["filename"]:
        return "no filename", 400
    if not data["content"]:
        # delete the file
        os.remove(f"/dat/{data['filename']}.txt")
        return "file deleted", 200
    with open(f"/dat/{data['filename']}.txt", "w") as f:
        f.write(data["content"])
        return "file saved", 200
    return "error", 500 # should not happen

def load_data(data):
    if not data:
        return "no request", 400
    if not data["filename"]:
        return "no filename", 400
    try:
        with open(f"/dat/{data['filename']}.txt", "r") as f:
            return f.read(), 200
    except FileNotFoundError:
        return "", 404 # file not found, it was last set to empty string
    return "error", 500 # should not happen

# that's it, now we host the API
iface = gradio.Interface(
    fn=store_data,
    inputs=[
        gradio.inputs.Textbox(label="filename"),
        gradio.inputs.Textbox(label="content")
    ],
    outputs=gradio.outputs.Textbox(label="status")
)
iface.launch()

iface = gradio.Interface(
    fn=load_data,
    inputs=[
        gradio.inputs.Textbox(label="filename")
    ],
    outputs=gradio.outputs.Textbox(label="content")
)
iface.launch()

# now you can use the API to store and load data
# POST /store_data {"filename": "test", "content": "hello world"}
# GET /load_data?filename=test