Skip to content

Instantly share code, notes, and snippets.

@DanielBeckstein
Last active January 21, 2021 16:24
Show Gist options
  • Save DanielBeckstein/1315d96dc52b0692dce1057e57c1e8f5 to your computer and use it in GitHub Desktop.
Save DanielBeckstein/1315d96dc52b0692dce1057e57c1e8f5 to your computer and use it in GitHub Desktop.
Python script - that uses flickr rest api - to handle some flickr api calls (get images for keywords, get only images with certain licenses) for more details check out the awesome official flickr-api documentation: https://www.flickr.com/services/api/ - how to get your api key: https://www.flickr.com/services/apps/create/apply/
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (c) 2016 Daniel Beckstein
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
# license information: https://opensource.org/licenses/MIT - MIT License
from __future__ import unicode_literals
import requests
import json
import os
import errno
import urllib
# you might want to moving this function into a seperate util (util.py)
def mkdir(path):
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
# you might want to moving this class into a seperate file (FlickrApiWrapper.py)
class FlickrApiWrapper():
"""
Documentation of Flickr API:
https://www.flickr.com/services/api/
"""
def __init__(self):
self.dir_json_info = "json_info"
# create this dir
mkdir(self.dir_json_info)
self.url_base = "https://api.flickr.com/services/rest/"
self.url_api = self.url_base
self.api_key = self.get_api_key()
self.extras = self.get_default_extras()
self.format = "json"
# downloads the names of all available licenses from flickr into a json file
self.helper_func_download_stored_info_licenses()
def helper_func_download_stored_info_licenses(self):
# this function is not very clean,
params = {}
params.update( {"method":"flickr.photos.licenses.getInfo"} )
r = self.search(params)
print "url", r.url
content = r.text
jso = json.loads(content.decode("utf-8"))
js = json.dumps(jso, indent=4, sort_keys=True) # for flickr
with open(self.dir_json_info+"/"+"stored_info_licenses.json","w") as f:
f.write(js.encode("utf8"))
# prints a json object formatted nicely
def print_nice(self, jso):
print json.dumps(jso, indent=4, sort_keys=True)
def get_api_key(self):
"""
with open(self.dir_json_info+"/"+"api_keys.json","r") as f:
api_keys = json.load(f)
key = api_keys["flickr"]["key"]
"""
key = "qiw2oh4......."
raise ValueError("put your key into this code (line above), then delete this line")
#how to get your api key: https://www.flickr.com/services/apps/create/apply/
return key
def get_default_extras(self):
extras = []
extras.append( "views" )
extras.append( "license" )
#extras.append( "original_format" )
extras.append( "tags" )
#extras.append( "machine_tags" )
extras.append( "owner_name" )
extras.append( "url_s" )
extras.append( "url_m" )
extras.append( "url_l" )
extras.append( "url_q" )
extras.append( "url_o" )
#extras.append( "description" )
# list of possible values
e = """description, license, date_upload, date_taken, owner_name, icon_server,
original_format, last_update, geo, tags, machine_tags,
o_dims, views, media, path_alias, url_sq, url_t, url_s, url_q, url_m, url_n, url_z, url_c, url_l, url_o"""
return extras
def get_info_license_by_id(self, id):
id_str = str(id)
if id_str.isdigit():
id_int = int(id)
if not ( id_int >= 0 and id_int <= 10 ):
raise ValueError("id is not in range [0...10]")
id_str = str(id_int)
else:
raise ValueError("id is not integer or digit formatted as string")
with open(self.dir_json_info+"/"+"stored_info_licenses.json","r") as f:
json_licenses = json.load(f)
licenses = json_licenses["licenses"]["license"]
license = None
for l in licenses:
if l["id"] == id_str:
license = l
break
return license
def search(self, params):
params.update( {"format":self.format} )
params.update( {"api_key":self.api_key} )
params.update( {"extras": ",".join(self.extras)} )
# nojsoncallback fixes weird invalid json - objects in the response from twitter
params.update( {"nojsoncallback":"1"} )
return requests.get(self.url_api, params=params)
def main():
flag_search_by_text = False
flickr = FlickrApiWrapper()
params = {}
# get info about licenses
if 0:
params.update( {"method":"flickr.photos.licenses.getInfo"} )
# get a list of public photos
if 0:
params.update( {"method":"flickr.people.getPublicPhotos"} )
params.update( {"user_id":"112616056@N08"} )
# get sizes of photo
if 1:
params.update( {"method":"flickr.photos.getSizes"} )
params.update( {"photo_id":"31083960980"} )
# get info of photo
if 0:
params.update( {"method":"flickr.photos.getInfo"} )
params.update( {"photo_id":"31083960980"} )
# search by text
if 1:
flag_search_by_text = True
params.update( {"method":"flickr.photos.search"} )
#https://www.flickr.com/services/api/flickr.photos.licenses.getInfo.html
# limit photos to certain licenses
params.update( {"license":"4,5,6,7,8,9,10"} )
params.update( {"text":"mountains"} )
params.update( {"per_page":"4"} )
"""
date-posted-asc, date-posted-desc, date-taken-asc, date-taken-desc
interestingness-desc, interestingness-asc, and relevance.
"""
params.update( {"sort":"relevance"} )
#params.update( {"sort":"interestingness-desc"} )
r = flickr.search(params)
print "url", r.url
content = r.text
print content.decode("utf-8")[:70]
with open(flickr.dir_json_info+"/"+"response.html","w") as f: #xml
f.write(content)
#content_formatted = content.replace( "jsonFlickrApi(","")
#content_formatted = content_formatted.replace( "})","}")
content_formatted = content
jso = json.loads(content_formatted.decode("utf-8"))
# log and print
js = json.dumps(jso, indent=4, sort_keys=True) # for flickr
with open(flickr.dir_json_info+"/"+"json_response.json","w") as f:
f.write(js.encode("utf8"))
print js[:400]
######################
if flag_search_by_text:
flickr.print_nice(jso["photos"])
print "showing per_page", jso["photos"]["perpage"]
print "total photos found", jso["photos"]["total"]
photos = jso["photos"]["photo"]
for p in photos:
#flickr.print_nice( p )
print p["ownername"]
print p["tags"]
print p["title"]
print p["views"]
print p["height_s"]
print p["url_s"]
print flickr.get_info_license_by_id(p["license"])
#print p["url_m"]
return photos
if 0:
license_info = flickr.get_info_license_by_id(2)
print license_info
# bug - you might want to return something
return None
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment