File size: 1,273 Bytes
6250353
 
 
e09af88
 
 
 
 
 
6250353
e09af88
 
6250353
 
e09af88
 
 
6250353
e09af88
6250353
e09af88
 
6250353
3c81231
 
 
 
6250353
e09af88
 
 
 
6250353
 
e09af88
 
6250353
e09af88
 
 
 
 
 
 
 
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
import os
import json
import datetime
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from huggingface_hub import HfApi

app = FastAPI()

# 1. 必须配置:允许你的 HTML 页面跨域提交数据
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"], 
    allow_methods=["*"],
    allow_headers=["*"],
)

# 2. 必须配置:从 Secret 获取 Token
TOKEN = os.getenv("HF_TOKEN")
DATASET_ID = "liuhuohuo/user_study_data" # 请修改此处
api = HfApi()

# 基础示例的保留(用于测试 Space 是否存活)
@app.get("/")
def greet_json():
    return {"status": "API is running", "timestamp": str(datetime.datetime.now())}

# 你的核心业务逻辑
@app.post("/submit")
async def collect_data(request: Request):
    data = await request.json()
    
    # 格式化文件名:record_20260208_120000.json
    filename = f"record_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
    content = json.dumps(data, indent=2).encode("utf-8")
    
    # 上传到数据集的 results 文件夹下
    api.upload_file(
        path_or_fileobj=content,
        path_in_repo=f"results/{filename}",
        repo_id=DATASET_ID,
        repo_type="dataset",
        token=TOKEN
    )
    return {"status": "success"}