Fred808 commited on
Commit
646fbf3
·
verified ·
1 Parent(s): 7c278df

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -22
app.py CHANGED
@@ -1,15 +1,29 @@
 
1
  import instaloader
 
 
2
 
3
- def fetch_instagram_posts(username: str, max_posts: int = 10):
 
 
 
 
 
 
 
 
 
 
 
4
  """
5
  Fetch Instagram posts from a public profile.
6
 
7
  Args:
8
  username (str): The username of the Instagram profile.
9
- max_posts (int): The maximum number of posts to fetch.
10
 
11
  Returns:
12
- None
13
  """
14
  # Initialize Instaloader
15
  L = instaloader.Instaloader()
@@ -19,20 +33,22 @@ def fetch_instagram_posts(username: str, max_posts: int = 10):
19
  print(f"Fetching posts for user: {username}")
20
  profile = instaloader.Profile.from_username(L.context, username)
21
 
 
 
 
22
  # Counter to limit the number of posts
23
  count = 0
24
 
25
  # Loop through the posts
26
  for post in profile.get_posts():
27
- print(f"\nPost {count + 1}:")
28
- print(f"Caption: {post.caption or 'No Caption'}")
29
- print(f"Likes: {post.likes}")
30
- print(f"Comments: {post.comments}")
31
- print(f"Posted on: {post.date_utc}")
32
- print(f"Image URL: {post.url}")
33
-
34
- # Save the post image locally
35
- L.download_post(post, target=profile.username)
36
 
37
  # Increment the counter
38
  count += 1
@@ -40,19 +56,16 @@ def fetch_instagram_posts(username: str, max_posts: int = 10):
40
  break
41
 
42
  print(f"\nFetched {count} posts for user: {username}.")
 
43
 
44
  except instaloader.exceptions.ProfileNotExistsException:
45
- print(f"Error: Profile '{username}' does not exist.")
46
  except instaloader.exceptions.ConnectionException:
47
- print("Error: Unable to connect to Instagram. Check your internet connection.")
48
  except Exception as e:
49
- print(f"Unexpected error: {e}")
50
-
51
 
 
52
  if __name__ == "__main__":
53
- # Hardcode the username and number of posts to fetch
54
- username = "bionsdesignco" # Replace with the desired Instagram username
55
- max_posts = 5 # Replace with the desired number of posts to fetch
56
-
57
- # Fetch posts
58
- fetch_instagram_posts(username, max_posts)
 
1
+ from fastapi import FastAPI, HTTPException
2
  import instaloader
3
+ from pydantic import BaseModel
4
+ from typing import List, Dict
5
 
6
+ app = FastAPI()
7
+
8
+ # Pydantic model for the response
9
+ class PostResponse(BaseModel):
10
+ caption: str
11
+ likes: int
12
+ comments: int
13
+ posted_on: str
14
+ image_url: str
15
+
16
+ @app.get("/fetch-posts", response_model=List[PostResponse])
17
+ async def fetch_instagram_posts(username: str, max_posts: int = 10):
18
  """
19
  Fetch Instagram posts from a public profile.
20
 
21
  Args:
22
  username (str): The username of the Instagram profile.
23
+ max_posts (int): The maximum number of posts to fetch (default is 10).
24
 
25
  Returns:
26
+ List[PostResponse]: A list of posts with caption, likes, comments, posted_on, and image_url.
27
  """
28
  # Initialize Instaloader
29
  L = instaloader.Instaloader()
 
33
  print(f"Fetching posts for user: {username}")
34
  profile = instaloader.Profile.from_username(L.context, username)
35
 
36
+ # List to store posts
37
+ posts = []
38
+
39
  # Counter to limit the number of posts
40
  count = 0
41
 
42
  # Loop through the posts
43
  for post in profile.get_posts():
44
+ post_data = {
45
+ "caption": post.caption or "No Caption",
46
+ "likes": post.likes,
47
+ "comments": post.comments,
48
+ "posted_on": post.date_utc.strftime("%Y-%m-%d %H:%M:%S"),
49
+ "image_url": post.url,
50
+ }
51
+ posts.append(post_data)
 
52
 
53
  # Increment the counter
54
  count += 1
 
56
  break
57
 
58
  print(f"\nFetched {count} posts for user: {username}.")
59
+ return posts
60
 
61
  except instaloader.exceptions.ProfileNotExistsException:
62
+ raise HTTPException(status_code=404, detail=f"Profile '{username}' does not exist.")
63
  except instaloader.exceptions.ConnectionException:
64
+ raise HTTPException(status_code=503, detail="Unable to connect to Instagram. Check your internet connection.")
65
  except Exception as e:
66
+ raise HTTPException(status_code=500, detail=f"Unexpected error: {e}")
 
67
 
68
+ # Run the FastAPI app
69
  if __name__ == "__main__":
70
+ import uvicorn
71
+ uvicorn.run(app, host="0.0.0.0", port=8000)