GithubHelp home page GithubHelp logo

sybrenstuvel / flickrapi Goto Github PK

View Code? Open in Web Editor NEW
155.0 155.0 33.0 1.67 MB

Python Flickr API implementation

Home Page: https://stuvel.eu/flickrapi

License: Other

Python 99.54% HTML 0.22% Shell 0.24%
flickr-api python python-3 python-3-5 python-3-6 python-library

flickrapi's People

Contributors

beaufour avatar bengt avatar codebicycle avatar cyberplant avatar danielhoherd avatar dargad avatar felixonmars avatar hugovk avatar hunterji avatar inirudebwoy avatar jim-easterbrook avatar kurtraschke avatar m-reiter avatar nloadholtes avatar okzach avatar randomcascade avatar sbaechler avatar sybrenstuvel avatar tedd4u avatar thai-nguyen-apollo avatar thijstriemstra avatar timclicks avatar u1735067 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

flickrapi's Issues

Make __data_walker() public

Originally reported by: Anonymous


Just had to duplicate __data_walker, so that I could use it with flickr.photos.recentlyUpdated.

Currently __data_walker() is only being used with flickr.photosets.getPhotos and flickr.photos.search.

A lot more than those 2 supports paging:
http://www.google.com/search?q=site%3Ahttp%3A//www.flickr.com/services/%20per_page

Best regards
Asbjørn Sloth Tønnesen
[email protected]


Store user data from authorization response

Originally reported by: Sybren Stüvel (Bitbucket: sybren, GitHub: sybren)


// Moved from the old bugzilla tracker, original reported by "Chris" //

According to the Flickr documentation, once a user passes their frob, api_key,
and signature through to flickr.auth.getToken
and successfully authenticated, they would receive something like this:

<auth>
    <token>67-76598454353455</token>
    <perms>write</perms>
    <user nsid="12037949754@N01" username="Bees" fullname="Cal H" />
</auth>

I noticed in your client API that you store the auth_token but none of the other variables that get returned. I thought that it would be nice to store information about the auth'd user as soon as they are auth'd suchas username, fullname, nsid, and possibly perms.


Auth with CLI interfaces

Originally reported by: Jeremy Dunlop (Bitbucket: jeremy_dunlop, GitHub: Unknown)


Trying to use FlickrAPI on a Raspberry Pi with no browser. I have searched but am sure if this is possible, can FlickrAPI be set to return a url which can be copied and used on another computer to authenticate and get the token. This is the process that works with flickr_upload search.cpan.org/~cpb/Flickr-Upload/flickr_upload. Is it possible?


Compatibility break: API key and secret must now be Unicode strings

Originally reported by: hugovk (Bitbucket: hugovk, GitHub: hugovk)


With Python 2.7:

import flickrapi
api_key = os.environ['FLICKR_API_KEY']
api_secret = os.environ['FLICKR_SECRET']
flickr = flickrapi.FlickrAPI(api_key, api_secret)

This code works with the last official release. But with the latest flickrapi source from Bitbucket an error occurs:

    flickr = flickrapi.FlickrAPI(args.api_key, args.api_secret)
  File "src/flickrapi/flickrapi/core.py", line 179, in __init__
    self.flickr_oauth = auth.OAuthFlickrInterface(api_key, secret)
  File "src/flickrapi/flickrapi/auth.py", line 155, in __init__
    assert isinstance(api_key, six.text_type), 'api_key must be unicode string'
AssertionError: api_key must be unicode string

Caused by:

        assert isinstance(api_key, six.text_type), 'api_key must be unicode string'
        assert isinstance(api_secret, six.text_type), 'api_secret must be unicode string'

Is there any particular reason for this compatibility break, requiring client code to be rewritten? I don't see a strong reason these particular bits of text must be unicode, I believe they're always alphanumeric. I think flickrapi should allow str or unicode.


Status Code 400 received

Originally reported by: Volker Süß (Bitbucket: volker_s, GitHub: Unknown)


Hello!

I have a problem with flickrapi on ubuntu 14.04.

I get this error when I start from cli:

volker@vs-home:~/workspace/flickrbackup2disk/src$ python picsapple.py

350 350

2014-06-26

No handlers could be found for logger "flickrapi.auth.OAuthFlickrInterface"

Traceback (most recent call last):

File "picsapple.py", line 1096, in

if __name__ == "__main__": sys.exit(main(sys.argv))

File "picsapple.py", line 1087, in main

myAppleTV.checklastupdates() 

File "picsapple.py", line 671, in checklastupdates
,page=seite,per_page=100)

File "build/bdist.linux-x86_64/egg/flickrapi/call_builder.py", line 37, in call

File "build/bdist.linux-x86_64/egg/flickrapi/core.py", line 314, in do_flickr_call

File "build/bdist.linux-x86_64/egg/flickrapi/core.py", line 376, in _wrap_in_parser

File "build/bdist.linux-x86_64/egg/flickrapi/core.py", line 354, in _flickr_call

File "build/bdist.linux-x86_64/egg/flickrapi/auth.py", line 249, in do_request

flickrapi.exceptions.FlickrError: do_request: Status code 400 received

When I start from eclipse with pydev all works fine!

I installed flickrapi 1.4.4 and python-requests 2.3

I have no idea what happen. Can anyone help?

Thx!


add a twisted asynchronous, deferred based version of flickrapi

Originally reported by: Anonymous


flickrapi can nicely be adapted to use twisted's getPage() and return deferred results instead of blocking. Unfortunately, three private mthods have to be overridden and there is a lot of code duplication. (https://launchpad.net/eyefi)

#!python

# The original code has the following license/copyright:
# 
# This code is subject to the Python licence, as can be read on
# http://www.python.org/download/releases/2.5.2/license/
#
# For those without an internet connection, here is a summary. When this
# summary clashes with the Python licence, the latter will be applied.
#
# 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.


from twisted.web.client import getPage
from twisted.internet.defer import succeed

from flickrapi import FlickrAPI, rest_parsers, LOG, FlickrError


# FIXME: bad, bad, bad: we are overriding private methods here
# FIXME: the actual changes are some 20 lines only, the rest is
# duplicated code

class TwistedFlickrAPI(FlickrAPI):
    def _FlickrAPI__flickr_call(self, **kwargs):
        LOG.debug("Calling %s" % kwargs)
        post_data = self.encode_and_sign(kwargs)
        if self.cache and self.cache.get(post_data):
            return defer.succeed(self.cache.get(post_data))
        url = "http://" + FlickrAPI.flickr_host + FlickrAPI.flickr_rest_form
        reply = getPage(url, method="POST", postdata=post_data, headers={
            "Content-Type": "application/x-www-form-urlencoded"})
        if self.cache is not None:
            reply.addCallback(self._add_to_cache, post_data)
        return reply

    def _add_to_cache(self, reply, post_data):
        self.cache.set(post_data, reply)
        return reply

    def _FlickrAPI__wrap_in_parser(self, wrapped_method,
            parse_format, *args, **kwargs):
        if parse_format in rest_parsers and 'format' in kwargs:
            kwargs['format'] = 'rest'
        LOG.debug('Wrapping call %s(self, %s, %s)' % (wrapped_method, args,
            kwargs))
        data = wrapped_method(*args, **kwargs)
        if parse_format not in rest_parsers:
            return data
        parser = rest_parsers[parse_format]
        return data.addCallback(lambda resp: parser(self, resp))

    def _FlickrAPI__send_multipart(self, url, body, progress_callback=None):
        assert not progress_callback, \
            "twisted upload/replace does not support progress callbacks yet"
        # would be like
        # http://twistedmatrix.com/pipermail/twisted-web/2007-January/003253.html
        LOG.debug("Uploading to %s" % url)
        reply = getPage(url, method="POST", postdata=str(body),
                headers=dict([body.header()]))
        return reply

    def trait_names(self):
        """
        ipython introspection needs to be synchornous, disable it
        """
        return None

    def get_token_part_one(self, perms="read"):
        token = succeed(self.token_cache.token)
        @token.addCallback
        def check(token):
            if not token:
                return None # need new one
            LOG.debug("Trying cached token '%s'" % token)
            rsp = self.auth_checkToken(auth_token=token, format='xmlnode')
            @rsp.addCallback
            def check_get(rsp):
                tokenPerms = rsp.auth[0].perms[0].text
                if tokenPerms == "read" and perms != "read":
                    return None # need new
                elif tokenPerms == "write" and perms == "delete":
                    return None # need new
                return token # is good
            @rsp.addErrback
            def check_err(err):
                err.trap(FlickrError)
                LOG.debug("Cached token invalid")
                self.token_cache.forget()
                return None # need new
            return rsp # automatic deferred chaining
        @token.addCallback
        def need_new(token):
            if token:
                return token, None # good token, no new frob
            LOG.debug("Getting frob for new token")
            rsp = self.auth_getFrob(auth_token=None, format='xmlnode')
            @rsp.addCallback
            def valid_frob(rsp):
                frob = rsp.frob[0].text
                self.validate_frob(frob, perms)
                return token, frob
            return rsp # automatic deferred chaining
        return token

    def get_token(self, frob):
        rsp = self.auth_getToken(frob=frob, auth_token=None, format='xmlnode')
        @rsp.addCallback
        def extract_token(rsp):
            token = rsp.auth[0].token[0].text
            LOG.debug("get_token: new token '%s'" % token)
            # store the auth info for next time
            self.token_cache.token = token
            return token
        return rsp

    def authenticate_console(self, perms='read'):
        d = self.get_token_part_one(perms)
        @d.addCallback
        def wait(arg):
            token, frob = arg
            if not token:
                # raw_inputs message gets swallowed by log
                print "Press ENTER after you authorized this program" 
                raw_input()
            return token, frob
        d.addCallback(self.get_token_part_two)
        return d


def main():
    from twisted.internet import reactor
    from twisted.python import log
    import logging
    log.PythonLoggingObserver().start()
    logging.getLogger().setLevel(level=logging.DEBUG)
    LOG.setLevel(level=logging.DEBUG)

    api_key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    api_secret = "XXXXXXXXXXXX"

    flickr = TwistedFlickrAPI(api_key, api_secret)

    #flickr.authenticate_console("write"
    #    ).addCallback(log.msg, "<- got token"
    #    ).addBoth(lambda _: reactor.callLater(0, reactor.stop)
    #    )

    #flickr.upload("test.jpg", is_public="0"
    #    ).addBoth(log.msg
    #    ).addBoth(lambda _: reactor.callLater(0, reactor.stop)
    #    )

    flickr.photos_search(user_id='73509078@N00', per_page='10'
        ).addBoth(log.msg
        ).addBoth(lambda _: reactor.callLater(0, reactor.stop)
        )

    reactor.run()


if __name__ == '__main__':
    main()

KeyError: 'fullname' in get_access_token()

Originally reported by: eme pe (Bitbucket: emepe, GitHub: emepe)


Hi Sybren.

Seems that some Flickr users does not have "fullname" so I get this error when that users tries to auth.

--- cut here ---
File "/home/ubuntu/django_app/local/lib/python2.7/site-packages/flickrapi-2.0_beta0-py2.7.egg/flickrapi/auth.py", line 379, in get_access_token
access_token_resp['fullname'],

KeyError: 'fullname'
--- cut here ---

Maybe changing that line from:

access_token_resp['fullname']

to:

access_token_resp.get('fullname', '') helps?


Cache's key issue at the flickr api call function.

Originally reported by: eme pe (Bitbucket: emepe, GitHub: emepe)


Hi Sybren.
I'm starting to use version 2 and I think maybe I found an issue with the cache's key in the flickr api call function.

In the 1.x version you've:

_flickr_call(self, **kwargs) (init.py):

#!python

        post_data = self.encode_and_sign(kwargs)

        # Return value from cache if available
        if self.cache and self.cache.get(post_data):
            return self.cache.get(post_data)

and in this case post_data is allways a str type, and in 2.x version you have:

_flickr_call(self, **kwargs) (core.py):

#!python

        # Return value from cache if available
        if self.cache and self.cache.get(kwargs):
            return self.cache.get(kwargs)

and the Memcached module crashes raising "MemcachedKeyCharacterError: Control characters not allowed" because in my Django project I was converting the key into a str with this:

#!python
def make_key(key, key_prefix, version):
    #return str(':'.join([key_prefix, str(version), key])[:250])

Now I fixed the issue "sanitazing" the dict into a plain string:

#!python
def make_key(key, key_prefix, version):
    return smart_str(''.join([c for c in str(key) if ord(c) > 32 and ord(c) != 127]))[:250]

It would be better to only uses strings as keys in the cache like in 1.x versions?
Regards


Drop use of distribute

Originally reported by: wzzrd (Bitbucket: wzzrd, GitHub: wzzrd)


Considering the pending merger of distribute and setuptools, would you consider dropping the dependency on distribute in new releases?

A little background might be in order. I maintain the python-flickrapi RPM for Fedora.

Fedora has moved to setuptools 0.9.6 for Fedora 20, which triggers distribute to try and download a distribute tarball during build. Fedora packaging guidelines do not allow this, so I patched out the distribute code and thus moved back to plain setuptools. Just patching out distribute allowed me to build an RPM from the latest stable release just fine. I was able to install the RPM and use the library.

In case you're interested, the build logs are here for the successful patched build and here for the failed build with distribute.

I understand Debian and Ubuntu use distribute instead setuptools, and might not have plans to move back soon, so it might not be this simple. However, my fork of the repo has setuptools instead of distribute at e028ed7, so I can send you a pull request if you want.


Library is setting log level.

Originally reported by: Jim Easterbrook (Bitbucket: jim_easterbrook, GitHub: Unknown)


My application sets the logging level according to user preferences, so I was surprised to get INFO level messages from flickrapi. My understanding (which may be wrong) is that libraries shouldn't do any configuration of the logger so I'm surprised at the number of setLevel() calls.


Can not authenticate in python 3.4.1

Originally reported by: Cristian Viorel Pasat (Bitbucket: thebestpessimist, GitHub: thebestpessimist)


Hello,

i am trying to authorize my app using oauth_test_4 (though none of the tests work!), by using the method authenticate_via_browser but i get this error.

#!log
Creating FlickrAPI object
Step 1: authenticate
INFO:flickrapi.auth.OAuthTokenHTTPServer:Creating HTTP server at ('localhost', 1798)
INFO:requests.packages.urllib3.connectionpool:Starting new HTTPS connection (1): www.flickr.com
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 58775)
Traceback (most recent call last):
  File "C:\Python34\lib\socketserver.py", line 305, in _handle_request_noblock
    self.process_request(request, client_address)
  File "C:\Python34\lib\socketserver.py", line 331, in process_request
    self.finish_request(request, client_address)
  File "C:\Python34\lib\socketserver.py", line 344, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "C:\Python34\lib\socketserver.py", line 665, in __init__
    self.handle()
  File "C:\Python34\lib\http\server.py", line 398, in handle
    self.handle_one_request()
  File "C:\Python34\lib\http\server.py", line 386, in handle_one_request
    method()
  File "D:\personal works\flickrapi\flickrapi\auth.py", line 37, in do_GET
    oauth_token = url_vars['oauth_token'][0]
KeyError: 'oauth_token'
----------------------------------------
Traceback (most recent call last):
  File "D:\personal works\flickrapi\oauth_test_4.py", line 17, in <module>
    flickr.authenticate_via_browser(perms='delete')
  File "D:\personal works\flickrapi\flickrapi\core.py", line 119, in decorated
    method(self, *args, **kwargs)
  File "D:\personal works\flickrapi\flickrapi\core.py", line 587, in authenticate_via_browser
    self.flickr_oauth.auth_via_browser(perms=perms)
  File "D:\personal works\flickrapi\flickrapi\auth.py", line 388, in auth_via_browser
    self.verifier = self.auth_http_server.wait_for_oauth_verifier()
  File "D:\personal works\flickrapi\flickrapi\auth.py", line 197, in verifier
    assert isinstance(new_verifier, six.text_type), 'verifier must be unicode text type'
AssertionError: verifier must be unicode text type

I am trying to dig into the code understand the problem and then fix it, although your assistance would be appreciated.


HTTP compression

Originally reported by: dandar3 (Bitbucket: dandar3, GitHub: dandar3)


Hi,

I made a change to __flickr_call to call a new __http_post method I wrote that uses HTTP compression, proving better performance for server replies.

Changed from:

#!python

        flicksocket = urllib2.urlopen(url, post_data)
        reply = flicksocket.read()
        flicksocket.close()

to

#!python

        reply = self.__http_post(FlickrAPI.flickr_host, FlickrAPI.flickr_rest_form, post_data )

My new method below (feel free to change, not hugely in Python :-)

#!python

import gzip
import StringIO
import zlib
import httplib

    def __http_post(self, host, url, params ):
        """Make a compressed HTTP call (if possible).
        """

        headers     = { "Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain", "Accept-Encoding" : "gzip" }
        connection  = httplib.HTTPConnection("%s:80" % host)

        connection.request( "POST", url, params, headers )
        response = connection.getresponse()

        # Compressed (gzip) response...
        if response.getheader( "content-encoding" ) == "gzip" :
            htmlGzippedData = response.read()
            stringIO        = StringIO.StringIO( htmlGzippedData )
            gzipper         = gzip.GzipFile( fileobj = stringIO )
            htmlData        = gzipper.read()
            print len(htmlData)
        # Plain text response...
        else :
            htmlData = response.read()

        # Cleanup
        connection.close()

        # Return value
        return htmlData 

HTH,
Dan


Using cache gives errors

Originally reported by: Cristian Viorel Pasat (Bitbucket: thebestpessimist, GitHub: thebestpessimist)


This is the code:

#!python
flickr = flickrapi.FlickrAPI(api_key=api_key, secret=api_secret, username=user_tbp_dev, cache=True)
flickr.cache = flickrapi.SimpleCache(timeout=100, max_entries=200)
photos = flickr.photos.search(user_id=user_tbp_dev, per_page=10)
print(ET.dump(photos))

And this is the stack trace

#!log

Traceback (most recent call last):
  File "D:\personal works\flickrWorks\flickr_derpage.py", line 128, in <module>
    photos = flickr.photos.search(user_id=user_tbp_dev, per_page=10)
  File "C:\Python34\lib\site-packages\flickrapi-2.0_beta0-py3.4.egg\flickrapi\call_builder.py", line 37, in __call__
  File "C:\Python34\lib\site-packages\flickrapi-2.0_beta0-py3.4.egg\flickrapi\core.py", line 314, in do_flickr_call
  File "C:\Python34\lib\site-packages\flickrapi-2.0_beta0-py3.4.egg\flickrapi\core.py", line 376, in _wrap_in_parser
  File "C:\Python34\lib\site-packages\flickrapi-2.0_beta0-py3.4.egg\flickrapi\core.py", line 358, in _flickr_call
  File "C:\Python34\lib\site-packages\flickrapi-2.0_beta0-py3.4.egg\flickrapi\cache.py", line 36, in locked
  File "C:\Python34\lib\site-packages\flickrapi-2.0_beta0-py3.4.egg\flickrapi\cache.py", line 68, in set
TypeError: unhashable type: 'dict'
[Finished in 2.4s]

I am using python 3.4.1 and i have built the head of your main branch.


upload callback function not being called

Originally reported by: Anonymous


Python 2.7.1, Kubuntu 11.04, flickrapi 1.4.2

My upload progress callback function doesn't get called unless I change line 639 of flickrapi/init.py from
response = reportinghttp.urlopen(request, __upload_callback)
to
response = reportinghttp.urlopen(request, progress_callback)
I'm guessing something about my setup means there is no need to filter out the header progress.


Upload files with unicode characters

Originally reported by: Alain Boue (Bitbucket: aboue, GitHub: aboue)


Hello,

I've been using your API these last weeks with good results (browsing in my photosets, getting lists of photos, uploading etc...): thanks a lot for your work which is very helpful.

However, I don't know whether this is an issue in the API or just me messing around with unicode and strings but I just can't upload a file with unicode characters in its name.

In both attachements, the file to be uploaded exists (I've tried with the same name without unicode character, i.e. Joel.jpg and it works fine).

In the first attachement, my idea was to follow your advice : "Flickr expects every text to be encoded in UTF-8. The Python Flickr API can help you in a limited way. If you pass a unicode string, it will automatically be encoded to UTF-8 before it's sent to Flickr. This is the preferred way of working". But this is what I get when I run IssueUnicode1.py:

"C:\Program Files\Python 2.7.7\python.exe" D:/Photos/LightRoom/Utilities/FlickrList/Essais/IssueUnicode1.py
Traceback (most recent call last):
File "D:/Photos/LightRoom/Utilities/FlickrList/Essais/IssueUnicode1.py", line 13, in
Response = SessionFlickr.upload(filename=photo_file, is_public="0", is_family="1", is_friend="0", format='etree')
File "C:\Program Files\Python 2.7.7\lib\site-packages\flickrapi-1.4.4-py2.7.egg\flickrapi__init__.py", line 545, in upload
filename, callback, *kwargs)
File "C:\Program Files\Python 2.7.7\lib\site-packages\flickrapi-1.4.4-py2.7.egg\flickrapi__init
_.py", line 613, in upload_to_form
url, body, callback)
File "C:\Program Files\Python 2.7.7\lib\site-packages\flickrapi-1.4.4-py2.7.egg\flickrapi__init
.py", line 436, in _wrap_in_parser
data = wrapped_method(args, **kwargs)
File "C:\Program Files\Python 2.7.7\lib\site-packages\flickrapi-1.4.4-py2.7.egg\flickrapi__init
.py", line 623, in send_multipart
request.add_data(str(body))
File "C:\Program Files\Python 2.7.7\lib\site-packages\flickrapi-1.4.4-py2.7.egg\flickrapi\multipart.py", line 100, in __str

return '\r\n'.join(lines)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)

Process finished with exit code 1

In the second example, IssueUnicode2.py, I just changed the filename encoding in the call. And this is what I got:
"C:\Program Files\Python 2.7.7\python.exe" D:/Photos/LightRoom/Utilities/FlickrList/Essais/IssueUnicode2.py
Traceback (most recent call last):
File "D:/Photos/LightRoom/Utilities/FlickrList/Essais/IssueUnicode2.py", line 13, in
Response = SessionFlickr.upload(filename=photo_file.encode('utf-8'), is_public="0", is_family="1", is_friend="0", format='etree')
File "C:\Program Files\Python 2.7.7\lib\site-packages\flickrapi-1.4.4-py2.7.egg\flickrapi__init__.py", line 545, in upload
filename, callback, **kwargs)
File "C:\Program Files\Python 2.7.7\lib\site-packages\flickrapi-1.4.4-py2.7.egg\flickrapi__init__.py", line 609, in upload_to_form
filepart = FilePart({'name': 'photo'}, filename, 'image/jpeg')
File "C:\Program Files\Python 2.7.7\lib\site-packages\flickrapi-1.4.4-py2.7.egg\flickrapi\multipart.py", line 62, in __init

imagefile = open(filename, 'rb')
IOError: [Errno 2] No such file or directory: 'D:\tmp\Jo\xc3\xabl.jpg'

Process finished with exit code 1

Your advice would be much welcome. I suppose I am doing something wrong but what?

Thanks in advance
Alain


upload callback function not being called

Originally reported by: Anonymous


Python 2.7.1, Kubuntu 11.04, flickrapi 1.4.2

My upload progress callback function doesn't get called unless I change line 639 of flickrapi/init.py from
response = reportinghttp.urlopen(request, __upload_callback)
to
response = reportinghttp.urlopen(request, progress_callback)
I'm guessing something about my setup means there is no need to filter out the header progress.


HTTPS support

Originally reported by: Domen Kožar (Bitbucket: iElectric, GitHub: Unknown)


When using flickr in https websites, it needs to operate underl SSL and return pictures with https prefix.

Browers nowadays cry when content is fetched over http even if everything else is using https.


Can't upload a photo with unicode characters in it

Originally reported by: Thomas Erlang (Bitbucket: thomaserlang, GitHub: thomaserlang)


Trying to upload a photo with a unicode character in it fails with: UnicodeDecodeError.
Example: C:\øæå\photo.jpg, fails.

#!python

  File "... \lib\site-packages\flickrapi\multipart.py", line 95, in __str__
    return '\r\n'.join(lines)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 12: ordinal not in range(128)

Incorrect use of logging.basicConfig

Originally reported by: Dave Dexter (Bitbucket: davedex, GitHub: davedex)


Calling logging.basicConfig in __init__.py is incorrect in a library as it adds a default streamhandler to the root logger.

More details available at http://stackoverflow.com/questions/16358512/imported-module-adding-unwanted-logging-how-can-it-be-suppressed

As an aside: I just want to just say thanks for the awesome library. I've been using it in various scripts for a few years and it's proved invaluable.


pip install puts files in wrong location

Originally reported by: Anonymous


Look at the three warnings, these files are written directly in /usr/local , which is very bad :)

#!

sudo pip install flickrapi

Downloading/unpacking flickrapi
  Downloading flickrapi-1.4.2.zip (79Kb): 79Kb downloaded
  Running setup.py egg_info for package flickrapi

Installing collected packages: flickrapi
  Running setup.py install for flickrapi
    warning: install_data: setup script did not provide a directory for 'LICENSE' -- installing right in '/usr/local'

    warning: install_data: setup script did not provide a directory for 'README' -- installing right in '/usr/local'

    warning: install_data: setup script did not provide a directory for 'UPGRADING' -- installing right in '/usr/local'


Successfully installed flickrapi
Cleaning up...


documentation is unclear about how callback is used

Originally reported by: mnieber (Bitbucket: mnieber, GitHub: mnieber)


Hi, I'm trying to use the require_flickr_auth decorator. It's correctly redirecting to the flickr log in page, but after logging in I get an error:

Oops! Flickr can't find a valid callback URL.

I think what should happen is a redirect to the callback function (first line is: log.info('We got a callback from Flickr, store the token'))

I suspect that there is something missing in the decorator (some code to setup the callback function). Or am I doing something wrong?

Thanks!
Maarten


have FlickrError expose its params

Originally reported by: Sybren Stüvel (Bitbucket: sybren, GitHub: sybren)


// Moved from the old Bugzilla tracker, originally posted by Ximin Luo //

currently FlickrError is initialised only with a string argument, which
includes the error code. please could this code be exposed as an int attribute of the exception? e.code would be nice, if that doesn't clash with anything else.


methods will not accept parameters

Originally reported by: Caroline Record (Bitbucket: crecord, GitHub: crecord)


I am attempting to get the timestamp and geolocation out of a list photos for a particular user. Right now the two methods that would give me what I need will not allow me to enter in the necessary parameters. I would like to use flickr.photos.geo.getLocation and or flickr.photos.getInfo, my problem for each is identical:

when I enter the parameters with the following code:
info = flickr.photos_getInfo(api_key,photo_id ='9527480877')

I get the following error:
TypeError: handler() takes exactly 0 arguments (2 given)

when I enter the code with no parameters I get a flickr exception saying that the photo isn't found. This library seems very helpful and I may be missing something crucial, but I just wanted to report it incase it's a bug.


HTTP Error 403: Forbidden

Originally reported by: Nikolas Moya (Bitbucket: nmoya, GitHub: nmoya)


When executing the minimal example of the documentation. A HTTP 403 Forbidden error appears.
I just created a brand new app, put the key in the variable. On the app settings on flickr website, does not seems to have any kind of configuration to start making requests, besides the app being active. Also, I believe this is a public request, no login or authentication is required, so there is no reason for a 403 error.

http://t.co/aMRGTMERVs


Installing on windows 7

Originally reported by: Pradeep K (Bitbucket: praks411, GitHub: praks411)


Hi
I'm trying to install flickrapi on windows 7. But my installation in failing
in setup.py line 34 print 'creating doc/index.html' with SyntaxError: invalid syntax

I've also tried using easy_install but that too failed on same above line. Also with admin and normal user but no luck.

However when I tried to install on virtual machine running Ubuntu it is working fine.
Please suggest what could be going wrong as I would like to run it on windows 7.
Am I missing some additional dependencies.

I've attached small screenshot of failed installation.

Thanks and Regards,
Pradeep


CI server

Originally reported by: hugovk (Bitbucket: hugovk, GitHub: hugovk)


How about adding a continuous integration server to automatically test builds? This will give confidence that each commit doesn't cause any regressions, and help test the next, big release.

The easiest to use is Drone. https://drone.io/ It's free for public repos.

This works directly with Bitbucket and is very easy to set up. Here's an example build script (for the commands box):

pip install -r requirements.txt --use-mirrors
nosetests tests/test_cache.py tests/test_core.py tests/test_shorturl.py tests/test_xmlnode.py

This runs a subset of the tests. You may know better which tests can be added, those requiring user interaction (e.g. auth tests with the browser) should be avoided. Perhaps a suitable test suite can be defined.

A downside is only one Python language can be set for the build: Python 2.7, 3.2 or 3.3. They're looking into providing multiple builds per language: harness/gitness#6). Still, testing on one is better than none.

Here's an example build on my fork:
https://drone.io/bitbucket.org/hugovk/flickrapi

Alternatively, Travis CI could be used. https://travis-ci.org/ Also free for open source. A benefit is each build can be run on multiple Python versions (2.6, 2.7, 3.2, 3.3, pypy and soon 3.4). The big downside is they only support GitHub so this would involve setting up a GitHub mirror and post-commit hooks to submit there as well.


Trying to limit search/walk results (with [:page_limit]) throws an exception - TypeError: 'generator' object has no attribute '__getitem__'

Originally reported by: Shrikant Joshi (Bitbucket: shrikantjoshi, GitHub: shrikantjoshi)


Here's the sample code:

#!python

f = flickrapi.FlickrAPI(api_key= MY_API_KEY, secret=MY_SECRET)
kwargs = {
    'tag_mode': 'all',
    'media': 'photos', 
    'content-type': 1, 
    'per_page': 5, 
    'tags': 'rainbow',
    }

photos = f.walk(**kwargs)
for photo in photos[:5]: # <-- this is where it throws a TypeError
    print photo.get('title')

The error:

#!python
'generator' object has no attribute '__getitem__'

Going over the source, it seems that the method is supposed to be a lazy construct and as a result it returns a generator object rather than a list. And since there isn't a defined __getitem__ method for slicing the resulting list, it (possibly) throws an Exception?

Of course, removing the [:5] results in proper execution of the API requests and it continues until ALL photo results for the given query are evaluated and listed - which may be as many as 10,000or even more, sometimes. For example, for a search-term as generic/common as 'rainbow', this could result in ~of images!

This, IMHO is a very bad idea. From what I could gather from the source code, it seems the problem stems from line 615 in core.py

It needs to be modified to allow the developer to set the maximum number of items they wish to retrieve or they may run the risk of overloading the Flickr API and potentially lose access to it!! :(


use httplib instead of urllib

Originally reported by: Sybren Stüvel (Bitbucket: sybren, GitHub: sybren)


//This bug has been moved from the old Bugzilla tracker.//

please use persistent HTTP requests. example code:

(only FlickrAPI.__init__ and FlickrAPI.__flickr_call need to be changed. I also
suggest not making __flickr_call private so that people can override it.)

#!python


from threading import local as ThreadLocal
from httplib import HTTPConnection, ImproperConnectionState, HTTPException

class FlickrAPI()

        def __init__(self, ... etc ...):
                # ... etc ...

                # Thread-local HTTPConnection, see __flickr_call
                self.thr = ThreadLocal()


        def __flickr_call(self, **kwargs):
                # Use persistent HTTP connections through a thread-local socket
                from flickrapi import LOG

                LOG.debug("Calling %s" % kwargs)

                post_data = self.encode_and_sign(kwargs)

                # Return value from cache if available
                if self.cache and self.cache.get(post_data):
                        return self.cache.get(post_data)

                # Thread-local persistent connection
                try:
                        if "conn" not in self.thr.__dict__:
                                self.thr.conn =
HTTPConnection(FlickrAPI.flickr_host)
                                self.log("connection opened to %s" %
FlickrAPI.flickr_host, 3)

                        self.thr.conn.request("POST",
FlickrAPI.flickr_rest_form, post_data,
                                {"Content-Type":
"application/x-www-form-urlencoded"})
                        reply = self.thr.conn.getresponse().read()

                except ImproperConnectionState, e:
                        self.log("connection error: %s" % e, 3)
                        self.thr.conn.close()
                        del self.thr.conn
                        raise

                # Store in cache, if we have one
                if self.cache is not None:
                        self.cache.set(post_data, reply)

                return reply

Uploaded file is stored in memory twice.

Originally reported by: Sybren Stüvel (Bitbucket: sybren, GitHub: sybren)


// Posted on behalf of Gilad Raphaelli: //

Hello. You may recall that we spoke awhile ago about combining
efforts on producing a python flickr api interface. While I haven't
updated mine much aside from some minor updates, I recently became
interested in uploading some big videos and know that my
implementation didn't do streaming uploads. While I've figured out a
way around that now, I gave v1.3 of FlickrAPI a spin in the meantime
to see what was supported there and wanted to report some findings.
Namely, it seems that file contents are loaded into memory twice for
an upload.

The first load comes, as expected, when attaching the file to the
request when __upload_to_form() builds a FilePart(), as that does a
read() of the whole file (as my implementation also does by default).
Then, this appears to be copied to the urllib2.Request object created
in __send_multipart(). While you're looking at it, you might be
interested in checking out http://pypi.python.org/pypi/poster/ -
that's the library I'm now using to avoid the memory consumption
involved in loading the whole file with that first read().

I hope that helps, please let me know if you need any additional
information.

  • Gilad

JSON format and nojsoncallback param support

Originally reported by: Gonzalo Saavedra (Bitbucket: gonz, GitHub: gonz)


It' seems that the nojsoncallback parameter it's not currently supported:

#!text
If you just want the raw JSON, with no function wrapper, add the parameter nojsoncallback with a value of 1 to your request.

Supporting this for json format requests would allow, for example, to directly feed the response to json.loads which seems to be a very common use case.


Encoding issues

Originally reported by: Anonymous


Sometimes, flickr returns xml with broken encodings and xml tree chockes on them (e.g. photos_getExif (photo_id= 4786671903).

A possibility would be to try to fix the encoding:

--- __init__.py 2010-09-22 16:41:53.813855000 +0200
+++ __init__.py.patched 2010-09-22 16:51:59.944821000 +0200
@@ -270,7 +270,11 @@
                 raise ImportError("You need to install "
                     "ElementTree for using the etree format")

-        rsp = ElementTree.fromstring(rest_xml)
+        try:
+            rsp = ElementTree.fromstring(rest_xml)
+        except:
+            rsp = ElementTree.fromstring(rest_xml.decode('cp1252').encode('utf8'))
+
         if rsp.attrib['stat'] == 'ok':
             return rsp

Uploading a file object

Originally reported by: Arturo Gomez (Bitbucket: arturo_gomez, GitHub: Unknown)


I would like to pass a file object directly from memory (not a file path from disk).

Could you please add an option for passing the file object during an upload?

Reference:
you could replace line 245 of flickrapi/auth.py to not call open() but to pass a file object itself.

Thanks again.


Firefox NoScript extension and flickr.authenticate_via_browser()

Originally reported by: Jim Easterbrook (Bitbucket: jim_easterbrook, GitHub: Unknown)


I have just started experimenting with version 2.0 of Flickrapi. Using the flickr.authenticate_via_browser() method was prevented by NoScript's "Application Boundaries Enforcer" default settings. I'd not seen this before, so it took me a while to work out how to disable it. Most people don't use NoScript so I suspect it's not a serious problem for Flickrapi.
I expect there's nothing you can do in Flickrapi to avoid this. My application will use the "out of band" method - it's what I use for Google Picasa auth so users will be familiar with the process.


Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.