GQL Queries - Retrieving specific data from query object - python-2.7

I'm building a database using Google Datastore. Here is my model...
class UserInfo(db.Model):
name = db.StringProperty(required = True)
password = db.StringProperty(required = True)
email = db.StringProperty(required = False)
...and below is my GQL Query. How would I go about retrieving the user's password and ID from the user_data object? I've gone through all the google documentation, find it hard to follow, and have spent ages trying various things I've read online but nothing has helped! I'm on Python 2.7.
user_data = db.GqlQuery('SELECT * FROM UserInfo WHERE name=:1', name_in)
user_info = user_data.get()

This is basic Python.
From the query, you get a UserInfo instance, which you have stored in the user_info variable. You can access the data of an instance via dot notation: user_info.password and user_info.email.
If this isn't clear, you really should do a basic Python tutorial before going any further.

You are almost there. Treat the query object like a class.
name = user_info.name
Documentation on queries here gives some examples

There are some python tips that might help you
dir(user_info)
help(user_info)
you can also print almost anything, like
print user_info[0]
print user_info[0].name
Setup logging for your app
Logging and python etc

Related

How do you perform a filtered database lookup in views?

I'm working with a database in Django. I'm familiar with the Django database API but am wondering how to interact with the data base inside views.py. Here's the relevant model:
class SlotFilling(models.Model):
originator = models.CharField(max_length=20)
empty_slot = models.BooleanField(default=False)
I'm trying to write an If statment in my program to check if empty_slot is True for a given originator. I'm thinking I might be able to use filter() to accomplish this. Any experience with the most efficient way to implement this?
If you are looking to query for originator all empty slots you can do something as following
SlotFilling.objects.filter(empty_slot=True, originator='someoriginator')
#comment code
Assuming originator is unique
originator_slot = SlotFlling.objects.get(originator='originator')
slot_value = originator_slot.empty_slot
You can use filter instead if originator is not unique, which would list you back all rows for particular originator
originator_slots = SlotFlling.objects.filter(originator='originator')
for originator_slot in originator_slots:
print originator_slot.empty_slot
Also please check out retrieving objects in DB API documentation as saying that you are familiar with it would be big overstatement :)

Tweepy API search doesn't have keyword

I am working with Tweepy (python's REST API client) and I'm trying to find tweets by several keywords and without url included in tweet.
But search results are not up to our satisfaction. Looks like query has erros and was stopped. Additionally we had observed that results were returned one-by-one not (as previously) in bulk packs of 100.
Could you please tell me why this search does not work properly?
We wanted to get all tweets mentioning 'Amazon' without any URL links in the text.
We used search shown below. Search results were still containing tweets with URLs or without 'Amazon' keyword.
Could you please let us know what we are doing wrong?
auth = tweepy.AppAuthHandler(consumer_key, consumer_secret)
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
searchQuery = 'Amazon OR AMAZON OR amazon filter:-links' # Keyword
new_tweets = api.search(q=searchQuery, count=100,
result_type = "recent",
max_id = sinceId,
lang = "en")
The minus sign should be put before "filter", not before "links", like this:
searchQuery = 'Amazon OR AMAZON OR amazon -filter:links'
Also, I doubt that the count = 100 option is a valid one, since it is not listed on the API documentation (which may not be very up-to-date, though). Try to replace that with rpp = 100 to get tweets in bulk packs.
I am not sure why some of the tweets you find do not contain the "Amazon" keyword, but a possibility is that "Amazon" is contained within the username of the poster. I do not know if you can filter that directly in the query, or even if you would want to filter it, since it would mean you would reject tweets from the official Amazon accounts. I would suggest that, for each tweet the query returns, you check it to make sure it does contain "Amazon".

Pulling data from datastore and converting it in Json in python(Google Appengine)

I am creating an apllication using google appengine, in which i am fetching a data from the website and storing it in my Database (Data store).Now whenever user hits my application url as "application_url\name =xyz&city= abc",i am fetching the data from the DB and want to show it as json.Right now i am using a filter to fetch data based on the name and city but getting output as [].I dont know how to get data from this.My code looks like this:
class MainHandler(webapp2.RequestHandler):
def get(self):
commodityname = self.request.get('veg',"Not supplied")
market = self.request.get('market',"No market found with this name")
self.response.write(commodityname)
self.response.write(market)
query = commoditydata.all()
logging.info(commodityname)
query.filter('commodity = ', commodityname)
result = query.fetch(limit = 1)
logging.info(result)
and the db structure for "commoditydata" table is
class commoditydata(db.Model):
commodity= db.StringProperty()
market= db.StringProperty()
arrival= db.StringProperty()
variety= db.StringProperty()
minprice= db.StringProperty()
maxprice= db.StringProperty()
modalprice= db.StringProperty()
reporteddate= db.DateTimeProperty(auto_now_add = True)
Can anyone tell me how to get data from the db using name and market and covert it in Json.First getting data from db is the more priority.Any suggestions will be of great use.
If you are starting with a new app, I would suggest to use the NDB API rather than the old DB API. Your code would look almost the same though.
As far as I can tell from your code sample, the query should give you results as far as the HTTP query parameters from the request would match entity objects in the datastore.
I can think of some possible reasons for the empty result:
you only think the output is empty, because you use write() too early; app-engine doesn't support streaming of response, you must write everything in one go and you should do this after you queried the datastore
the properties you are filtering are not indexed (yet) in the datastore, at least not for the entities you were looking for
the filters are just not matching anything (check the log for the values you got from the request)
your query uses a namespace different from where the data was stored in (but this is unlikely if you haven't explicitly set namespaces anywhere)
In the Cloud Developer Console you can query your datastore and even apply filters, so you can see the results with-out writing actual code.
Go to https://console.developers.google.com
On the left side, select Storage > Cloud Datastore > Query
Select the namespace (default should be fine)
Select the kind "commoditydata"
Add filters with example values you expect from the request and see how many results you get
Also look into Monitoring > Log which together with your logging.info() calls is really helpful to better understand what is going on during a request.
The conversion to JSON is rather easy, once you got your data. In your request handler, create an empty list of dictionaries. For each object you get from the query result: set the properties you want to send, define a key in the dict and set the value to the value you got from the datastore. At the end dump the dictionary as JSON string.
class MainHandler(webapp2.RequestHandler):
def get(self):
commodityname = self.request.get('veg')
market = self.request.get('market')
if commodityname is None and market is None:
# the request will be complete after this:
self.response.out.write("Please supply filters!")
# everything ok, try query:
query = commoditydata.all()
logging.info(commodityname)
query.filter('commodity = ', commodityname)
result = query.fetch(limit = 1)
logging.info(result)
# now build the JSON payload for the response
dicts = []
for match in result:
dicts.append({'market': match.market, 'reporteddate': match.reporteddate})
# set the appropriate header of the response:
self.response.headers['Content-Type'] = 'application/json; charset=utf-8'
# convert everything into a JSON string
import json
jsonString = json.dumps(dicts)
self.response.out.write( jsonString )

Retrieve extra fields with Graph API using PHP

I'm trying to create some social dashboard and therefore I want to retrieve my posts from my page. When I use this one to fetch my posts, it doesn't return me all the information I need (e.g 'picture', 'full_picture', 'attachments')
$user_posts = $facebook->api('/me/posts', 'GET');
print_r($user_posts);
But when I try next one, it still doesn't return me my required information:
$user_posts = $facebook->api('/me/posts?{created_time,id,message,full_picture,picture,attachments{url,subattachments},likes{name},comments{from,message,comment_count,user_likes,likes{name}}}', 'GET');
print_r($user_posts);
Anyone ideas??
I know that this has been asked a long time ago, but maybe useful for someone:
After - me/posts? - you need to make sure to put fields= and then a list of fields required.
So this would be:
$user_posts = $facebook->api('/me/posts?fields={created_time,id,message,full_picture,picture,attachments{url,subattachments},likes{name},comments{from,message,comment_count,user_likes,likes{name}}}', 'GET');
print_r($user_posts);

Python - Lotus Notes (Sending Email)

I am trying to use Python 2.7.3.2 to send an email through Lotus Notes 8.5.
There are plenty of examples on how to do this in other languages, and I've done it myself in VBA, but having difficulties with Python.
self.db = self.session.getDatabase(server, dbfile)
# ...
mailDoc = self.db.CreateDocument
mailDoc.Form = "Memo"
mailDoc.sendto = recipientList
mailDoc.subject = subject
mailDoc.Body = bodytext
Error returned: AttributeError: Property 'CreateDocument.Form' can not be set.
I have attempted to skip setting the form, but it also fails on setting any of these attributes.
Would anyone have code on this, or suggestions on what to try to resolve it.
I know nothing about Python, but my guess is that the shorthand notation document.item = "foo" for setting an item value is not supported. Most likely, you need to do this:
mailDoc.AppendItemValue("Form","Memo")
(You can also use ReplaceItemValue, which is equivalent for a newly created document, and also works for updating existing documents, so many people prefer to just remember the one method name.)