2026년 7월 21일 화요일

main.py



import asyncio

import rust_curl
from fastapi import FastAPI, HTTPException

app = FastAPI()


@app.get("/fetch-data")
async def fetch_data(target_url: str):
  try:
    # 러스트 비동기 함수를 FastAPI 내부에서 호출
    status, text = await rust_curl.curl_async(target_url)

    if status != 200:
      raise HTTPException(status_code=status, detail="External fetch failed")

    return {"status": "success", "length": len(text), "data_preview": text[:100]}

  except Exception as e:
    raise HTTPException(status_code=500, detail=str(e))


async def main():
  # 1. 일반적인 구글 시트 CSV 다운로드 (기본 GET)
  sheet_url = "https://google.com"

  print("⏳ 구글 시트 요청 중...")
  status, csv_data = await rust_curl.curl_async(sheet_url)
  print(f"[{status}] CSV 데이터 일부:\n{csv_data[:200]}\n")

  # 2. 만약 인증 헤더가 필요한 비공개 API나 다른 서버에 POST를 날릴 때 (curl -X POST -H ... -d ...)
  api_url = "https://httpbin.org"
  custom_headers = {"Authorization": "Bearer MySecretToken123", "Content-Type": "application/json"}
  json_body = '{"name": "rust_paser", "type": "async"}'

  print("⏳ 외부 API로 POST 요청 중...")
  status, response_text = await rust_curl.curl_async(url=api_url, method="POST", headers=custom_headers, body=json_body)
  print(f"[{status}] 응답 결과:\n{response_text}")


if __name__ == "__main__":
  asyncio.run(main())


database.py

import os from contextlib import contextmanager # contextmanager 임포트 from typing import Generator from dotenv...