Fred808 commited on
Commit
68f1b21
·
verified ·
1 Parent(s): e13c8f2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -7
app.py CHANGED
@@ -1,6 +1,6 @@
1
  # api/main.py
2
  from fastapi import FastAPI, HTTPException, Depends
3
- from pydantic import BaseModel
4
  from typing import List, Dict
5
  import logging
6
  import requests
@@ -39,19 +39,37 @@ class AnalyzePostRequest(BaseModel):
39
  hashtags: str
40
  image_url: str
41
 
 
 
 
42
  @app.post("/fetch-posts")
43
  async def fetch_posts(user: UserRequest):
44
  """
45
  Fetch posts from a given Instagram profile (public data only).
46
  """
 
 
47
  username = user.username
48
- logging.info(f"Fetching posts for user: {username}")
 
 
 
 
 
 
 
 
 
49
 
50
  try:
51
  # Fetch user's posts
52
  user_posts = fetch_user_posts(username)
53
  if not user_posts:
54
- raise HTTPException(status_code=404, detail="No posts found for the user.")
 
 
 
 
55
 
56
  # Fetch competitors' posts
57
  competitors_posts = fetch_competitors_data(username)
@@ -60,12 +78,29 @@ async def fetch_posts(user: UserRequest):
60
  all_posts = user_posts + competitors_posts
61
 
62
  # Save data to the database
63
- save_to_db(all_posts)
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
- return {"status": "success", "data": all_posts}
 
 
66
  except Exception as e:
67
- logging.error(f"Error fetching posts: {e}")
68
- raise HTTPException(status_code=500, detail=str(e))
 
 
 
69
 
70
  @app.post("/analyze")
71
  async def analyze(user: UserRequest, db: Session = Depends(get_db)):
 
1
  # api/main.py
2
  from fastapi import FastAPI, HTTPException, Depends
3
+ from pydantic import BaseModel, constr
4
  from typing import List, Dict
5
  import logging
6
  import requests
 
39
  hashtags: str
40
  image_url: str
41
 
42
+ RATE_LIMIT_DELAY = 5 # Delay in seconds between API calls
43
+ LAST_REQUEST_TIME = 0
44
+
45
  @app.post("/fetch-posts")
46
  async def fetch_posts(user: UserRequest):
47
  """
48
  Fetch posts from a given Instagram profile (public data only).
49
  """
50
+ global LAST_REQUEST_TIME
51
+
52
  username = user.username
53
+ logger.info(f"Fetching posts for user: {username}")
54
+
55
+ # Rate limiting
56
+ current_time = time.time()
57
+ if current_time - LAST_REQUEST_TIME < RATE_LIMIT_DELAY:
58
+ raise HTTPException(
59
+ status_code=status.HTTP_429_TOO_MANY_REQUESTS,
60
+ detail="Please wait a few seconds before making another request."
61
+ )
62
+ LAST_REQUEST_TIME = current_time
63
 
64
  try:
65
  # Fetch user's posts
66
  user_posts = fetch_user_posts(username)
67
  if not user_posts:
68
+ logger.warning(f"No posts found for user: {username}")
69
+ raise HTTPException(
70
+ status_code=status.HTTP_404_NOT_FOUND,
71
+ detail="No posts found for the user."
72
+ )
73
 
74
  # Fetch competitors' posts
75
  competitors_posts = fetch_competitors_data(username)
 
78
  all_posts = user_posts + competitors_posts
79
 
80
  # Save data to the database
81
+ if not save_to_db(all_posts):
82
+ logger.error("Failed to save data to the database.")
83
+ raise HTTPException(
84
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
85
+ detail="Failed to save data to the database."
86
+ )
87
+
88
+ # Return success response
89
+ return {
90
+ "status": "success",
91
+ "data": all_posts,
92
+ "message": f"Successfully fetched {len(all_posts)} posts."
93
+ }
94
 
95
+ except HTTPException as e:
96
+ # Re-raise HTTPException to return specific error messages
97
+ raise e
98
  except Exception as e:
99
+ logger.error(f"Unexpected error fetching posts: {e}")
100
+ raise HTTPException(
101
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
102
+ detail="An unexpected error occurred. Please try again later."
103
+ )
104
 
105
  @app.post("/analyze")
106
  async def analyze(user: UserRequest, db: Session = Depends(get_db)):