简体   繁体   中英

Saving photos from instagram api calls to Postgresql?

So I wanted to create an app that makes a get request to the instagram api and grabs a users picture feed WHILE saving the url's of the photos to my postgresql database automatically. I'm assuming it's possible but am having a hard time figuring out how to go about it. I've got the picture feed coming out ok but saving to my DB is where I fail. Here is my instagram controller:

class InstagramController < ApplicationController 

before_action :set_ig_acc_code, only: [:feed, :search]

def instagram
    # Find the access token
    res = HTTParty.post("https://instagram.com/oauth/access_token/",
     {body:{client_id: ENV["IG_CLIENT_ID"],
      client_secret: ENV["IG_CLIENT_SECRET"],
      grant_type:'authorization_code',
      redirect_uri:'http://localhost:3000/instagram',
      code: params[:code]}})
    redirect_to feed_path(acc_token: res.parsed_response["access_token"])
end

def feed
    # Show a feed of pictures
    if params[:user_id] # For a given user
        @feed = HTTParty.get("https://api.instagram.com/v1/users/" + URI::escape(params[:user_id]) + "/media/recent?access_token=" +
        @acc_token)
    else    # This user's folks they follow
        @feed = HTTParty.get("https://api.instagram.com/v1/users/self/feed?access_token=" +
        @acc_token)
    end
end

def search
    # Search users
    @url = "https://api.instagram.com/v1/users/search?q=" + URI::escape(params[
        :search][:query]) + "&access_token=" +
     params[:acc_token]
    @results = HTTParty.get(@url)
end

private
    def set_ig_acc_code
        @acc_token = params[:acc_token]
    end

end

Maybe I should make a photo model with a URL field and save them as they load through my feed somehow??? I'm banging my head against the wall on this one. Thanks in advance.

if i remember correctly, the instagram api has a call to return all sorts of data about an object. try searching the instagram developer site for media url or such. hope this helps.

Not sure why this question was down voted as I thought it was legit but here's a solution I found that might help someone else with the same problem. I added this at the end of my Feed method inside the InstagramController:

        @feed["data"].each do |pic|
            url = pic["images"]["thumbnail"]["url"]
            Photo.find_or_create_by(url:url)
        end

Pending a migration, this saved the URL just fine. Still working on saving the "Tag" data but it should be something similar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM