picasa api - How to get a specific album with an album id? - python

How do I get a specific album from the picasa api?
Currently I am doing something like this:
def album(gd_client, album_id, user):
all_albums = albums(gd_client,user)
for album in all_albums:
if album.service_id == album_id:
return album
Which means I get all the albums and filter out the one I need.
But there must be an easier and more efficient way.
Thanks!

In Google Data Protocol version 2.0 there is experimental support for PartialResponse, which allows you to filter responses at the server by passing in a fields parameter.
Unfortunately only the Java API supports 2.0, but you can easily add it to the Python API yourself.

It looks like you want "entry" API. Here is how I can get AlbumEntry for a public album (do not want to deal with auth):
base = "https://picasaweb.google.com";
user = "101405741057659770470" # myself
albumid = "6333524051829767505"
# must be inside of a function to use locals()
url = "%(base)s/data/entry/api/user/%(user)s/albumid/%(albumid)s" % locals()
gd_client = gdata.photos.service.PhotosService()
entry = gd_client.GetEntry(url)
assert isinstance(entry, gdata.photos.AlbumEntry)
Similar in Java:
String baseURL = "https://picasaweb.google.com";
String userId = "101405741057659770470" // myself
String albumid = "6333524051829767505"
String albumUrl = String.format(
"%s/data/entry/api/user/%s/albumid/%s", baseURL, userId, albumId);
// myService is defined here: https://developers.google.com/picasa-web/docs/2.0/developers_guide_java
AlbumEntry entry = myService.getEntry(new URL(albumUrl), AlbumEntry.class, (DateTime) null /* modified since*/);

Related

How to include a variable in api call in python?

I am trying to implement a searchbar in django. I am getting the search input as movie_title from the html form. Now, how do i include it in my api call ? I tried with curly braces. Here's is the code
def searchbar(request):
if request.method == 'GET':
movie_title = request.GET.get('movie_title')
searched_movie = requests.get(
'http://www.omdbapi.com/?apikey=9a63b7fd&t={movie_title}')
You can create the url as an object using f-strings (one of the ways) and pass that to the get() method:
url = f'http://www.omdbapi.com/?apikey=9a63b7fd&t={movie_title}'
searched_movie = requests.get(url)
Note: You don't need to create a different object and can directly use:
searched_movie = requests.get(f'http://www.omdbapi.com/?apikey=9a63b7fd&t={movie_title}')
The above approach helps with readability when there are several dynamic attributes involved.
If you want to use { and } in your query string you can simply write
searched_movie = requests.get('http://www.omdbapi.com/?apikey=9a63b7fd&t={'+movie_title+'}')
Otherwise you can write
searched_movie = requests.get('http://www.omdbapi.com/?apikey=9a63b7fd&t='+movie_title)

How to fetch arrayfield data in django with postgres

I'm trying to fetch users list based on their language(from ArrayField). A single user can have multiple languages. When i passed single language{'Hindi'}, it fetches all the records except user with multiple languages, but if passed parameters {'Hindi','bangla','kannada'} then it gives me a specific record,how can i fetch the users list with hindi and other than hindi as well . I have tried with .all also but it didn't worked for me.
Any help would be appreciated.
models.py
# DESCRIPTION: This function gets the drivers list by lang.
#classmethod
def get_driver_by_lang(cls, driver_lang):
try:
driver_details = cls.objects.filter(language = driver_lang)
data = serializers.serialize("json", driver_details)
data = json.loads(data)
return data
except :
return False
How about this:
driver_details = cls.objects.filter(language__contains = driver_lang)

Python-requests + Django changing the parameters structure in URL

Basicly, I've done with Python-requests and Django search feature through Google Books API with single q parameter (as shown in link below)
https://developers.google.com/books/docs/v1/using#WorkingVolumes
and after submiting form I'm getting list of dicts in json as I want with this single parameter, and I'm getting in json data where appers keyword "Hobbit" and URL looks like this
http://127.0.0.1:8000/api?books=hobbit
but when I'm trying to add special keywords provided by Google Books API like,
intitle, inauthor, inpublisher, subject, etc.
and trying to search for it I'm getting URL
http://127.0.0.1:8000/api?books=hobbit&intitle=&inauthor=&inpublisher=&isbn=&lccn=&oclc=
which only returns the data of single q parameter, because the correct URL for special keywords in Google Books API looks like this
https://www.googleapis.com/books/v1/volumes?q=flowers+inauthor:keyes+subject:somesubject
So as you see then correct URL got signs
+ against & and : against =
so the Correct URL that I want to get would look like this
http://127.0.0.1:8000/api?books=hobbit+intitle:something+inauthor:something+inpublisher:something+isbn:something+lccn:something+oclc:something
My question is how to change this structure to correct as Google books API require?
Tried to find this in python-requests docs but there are nothing about this
views.py
def api(request):
books = {
'intitle': 'intitle',
'inauthor': 'inauthor',
'inpublisher': 'inpublisher',
'subject': 'subject',
'isbn': 'isbn',
'lccn': 'lccn',
'oclc': 'oclc'
}
if 'books' in request.GET:
books = request.GET['books']
url = 'https://www.googleapis.com/books/v1/volumes?q=%s' % books
response = requests.get(url)
books = response.json()
print(type(books))
with open("data_file.json", "w") as write_file:
json.dump(books, write_file)
return render(request, 'books/api.html', {'books': books})
You will have to construct the query string manually. Assuming that your request will look like http://127.0.0.1:8000/api?books=hobbit&intitle=a&inauthor=b&inpublisher=c, you can construct the query string like this:
def api(request):
# ...
if 'books' in request.GET:
books = request.GET['books']
query_dict = request.GET.copy()
del query_dict['books']
query = '+'.join([books, *['{}:{}'.format(k, v) for k, v in query_dict.items()]])
url = 'https://www.googleapis.com/books/v1/volumes?q=' + query
# ...
The final google query requires books as the first parameter. So, we need to extract the books value from request.GET. Now, to get all other values, we need to delete the books key. But, request.GET is a QueryDict object, which is immutable. To convert it into a mutable object, request.GET.copy() can be used (which creates a mutable copy).

Updating DataStore JSON values using endpoints (Python)

I am trying to use endpoints to update some JSON values in my datastore. I have the following Datastore in GAE...
class UsersList(ndb.Model):
UserID = ndb.StringProperty(required=True)
ArticlesRead = ndb.JsonProperty()
ArticlesPush = ndb.JsonProperty()
In general what I am trying to do with the API is have the method take in a UserID and a list of articles read (with an article being represented by a dictionary holding an ID and a boolean field saying whether or not the user liked the article). My messages (centered on this logic) are the following...
class UserID(messages.Message):
id = messages.StringField(1, required=True)
class Articles(messages.Message):
id = messages.StringField(1, required=True)
userLiked = messages.BooleanField(2, required=True)
class UserIDAndArticles(messages.Message):
id = messages.StringField(1, required=True)
items = messages.MessageField(Articles, 2, repeated=True)
class ArticleList(messages.Message):
items = messages.MessageField(Articles, 1, repeated=True)
And my API/Endpoint method that is trying to do this update is the following...
#endpoints.method(UserIDAndArticles, ArticleList,
name='user.update',
path='update',
http_method='GET')
def get_update(self, request):
userID = request.id
articleList = request.items
queryResult = UsersList.query(UsersList.UserID == userID)
currentList = []
#This query always returns only one result back, and this for loop is the only way
# I could figure out how to access the query results.
for thing in queryResult:
currentList = json.loads(thing.ArticlesRead)
for item in articleList:
currentList.append(item)
for blah in queryResult:
blah.ArticlesRead = json.dumps(currentList)
blah.put()
for thisThing in queryResult:
pushList = json.loads(thisThing.ArticlesPush)
return ArticleList(items = pushList)
I am having two problems with this code. The first is that I can't seem to figure out (using the localhost Google APIs Explorer) how to send a list of articles to the endpoints method using my UserIDAndArticles class. Is it possible to have a messages.MessageField() as an input to an endpoint method?
The other problem is that I am getting an error on the 'blah.ArticlesRead = json.dumps(currentList)' line. When I try to run this method with some random inputs, I get the following error...
TypeError: <Articles
id: u'hi'
userLiked: False> is not JSON serializable
I know that I have to make my own JSON encoder to get around this, but I'm not sure what the format of the incoming request.items is like and how I should encode it.
I am new to GAE and endpoints (as well as this kind of server side programming in general), so please bear with me. And thanks so much in advance for the help.
A couple things:
http_method should definitely be POST, or better yet PATCH because you're not overwriting all existing values but only modifying a list, i.e. patching.
you don't need json.loads and json.dumps, NDB does it automatically for you.
you're mixing Endpoints messages and NDB model properties.
Here's the method body I came up with:
# get UsersList entity and raise an exception if none found.
uid = request.id
userlist = UsersList.query(UsersList.UserID == uid).get()
if userlist is None:
raise endpoints.NotFoundException('List for user ID %s not found' % uid)
# update user's read articles list, which is actually a dict.
for item in request.items:
userslist.ArticlesRead[item.id] = item.userLiked
userslist.put()
# assuming userlist.ArticlesPush is actually a list of article IDs.
pushItems = [Article(id=id) for id in userlist.ArticlesPush]
return ArticleList(items=pushItems)
Also, you should probably wrap this method in a transaction.

Unable to view item in browser based on its key in Python GAE

I'm using python GAE with webapp.
I have a form for a user to create a object in the database, something like:
class SpamRecord(db.Model):
author = db.ReferenceProperty(Author, required=True)
text = db.StringProperty()
After it's created, the user is redirected to a page whose URL contains that object's key... using code such as:
spam = SpamRecord(author=author, text=text)
spam.put()
new_spam_key = spam.key()
self.redirect("/view_spam/%s" % new_spam_key)
And this mostly works, with me being able to view items at:
sitename.com/view_spam/ag1waWNreXByZXNlbnRzchQLEgxBbm5vdW5jZW1lbnQYy8oJDA
sitename.com/view_spam/ag1waWNreXByZXNlbnRzchQLEgxBbm5vdW5jZW1lbnQY_boJDA
However, there's an occasional key that won't work. Here are 2 recent examples of pages that won't load and return HTTP 404 not found errors:
sitename.com/view_spam/ag1waWNreXByZXNlbnRzchQLEgxBbm5vdW5jZW1lbnQY-5MJDA
sitename.com/view_spam/ag1waWNreXByZXNlbnRzchQLEgxBbm5vdW5jZW1lbnQY-boJDA
My html-mappings.py contains the following mapping:
(r"/view_spam/(\w+)", ViewSpamPage)
And the ViewSpamPage looks something like:
class ViewSpamPage(webapp.RequestHandler):
def get(self, spam_id):
self.response.out.write("Got here")
Can anyone offer any insight as to why this is occurring and how it may be prevented?
Thanks very much!
In regular expressions, \w doesn't match hyphens. (It will match underscores.) For that second pair of keys, this'll result in only passing part of the key to your handler.
In your URL pattern, try r"/view_spam/(.*)" instead.

Categories