newTest / main.py
Songyou's picture
Update main.py
95e9a58 verified
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import os
import gradio as gr
import requests
# 创建FastAPI应用
app = FastAPI()
# 定义POST请求的JSON格式
class RequestData(BaseModel):
content: str
# POST请求:创建test.txt文件并写入内容
@app.post("/create_file")
async def create_file(data: RequestData):
try:
with open("test.txt", "w") as file:
file.write(data.content)
return {"message": "File created successfully."}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# GET请求:读取test.txt文件内容
@app.get("/read_file")
async def read_file():
try:
if not os.path.exists("test.txt"):
raise HTTPException(status_code=404, detail="File not found.")
with open("test.txt", "r") as file:
content = file.read()
return {"content": content}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# 使用Gradio创建UI界面
def api_request(url: str, request_type: str, json_data: str = None):
try:
if request_type == "POST":
# 如果是POST请求,解析JSON数据并发送
data = eval(json_data) if json_data else {}
response = requests.post(url, json=data)
else:
# 如果是GET请求,直接发送GET请求
response = requests.get(url)
# 返回响应内容
return response.json() if response.ok else f"Error: {response.status_code} - {response.text}"
except Exception as e:
return str(e)