Pyral Cannot Parse Parent Object returned - python-2.7

I am trying to get the Parent Epic / Feature for particular User Stories in Rally. However I am only getting the parent object and I am not sure how to parse it. I have tried dict and dir(object) to get field values but it did not work. I have also tried as following, but I keep on getting something like this instead of fields/values in Parent Object
pyral.entity.PortfolioItem_Capability object at 0x7ff848273850
CODE:
def get_hierarchy(server,username,password,workspace,project,release):
rally = Rally(server, username, password, workspace=workspace, project=project)
criterion = 'Release.Name = "'+release+'" AND Parent != None'
response = rally.get('HierarchicalRequirement',fetch="ObjectID,FormattedID,Name,AcceptedDate,Project,Release,ScheduleState,Parent,Description",query=criterion,limit=5000)
return response
for item in get_hierarchy("rally1.rallydev.com","some.email#address.com","Somepassword","Some Workspace Name","PROJECT NAME","Release Version"):
print item.FormattedID, item.Name, item.ScheduleState, item.Description, item.Parent.Name

The parent is also an object and you have to parse the parent similar to the user story. For a simplistic solution, keep using the dot format. Here is a code snippet that does something similar to the above that should give you a start.
queryString = '(Iteration.StartDate > "2017-08-31")'
entityName = 'HierarchicalRequirement'
response = rally.get(entityName, fetch=True, projectScopeDown=True, query=queryString)
for item in response:
print(item.FormattedID,
item.PortfolioItem.FormattedID,
item.PortfolioItem.Parent.FormattedID,
item.PlanEstimate)
I'm using Python 3.x but I don't see any reason it wouldn't translate to 2.7.

Related

Why is Django Paramaterized query not working

I have been struggling with this simple query in django. I have checked a lot over internet. I tried using similar syntax - yet no luck.
In my application on html page I need to display some specific record. And for that i want to use parameterized select statement. But the query is not working..
I have checked id2 is getting correct value from previous html page..
And I know I can use APIs but for my databases classes I need to use raw queries in my application.
Can someone please help me here...
def details(request, id2):
temp = 'test3'
data = Posts.objects.raw('''select * from posts_posts where posts_posts.id = %s ''', id2)
context ={
'post' : data,
If you run that code you will see an error, since that is not the correct format for a call to raw. If you can't see the error output anywhere, then you have yet another problem for another post.
The correct format for raw is: .raw(sql, iterable-values), like this:
posts = Posts.objects.raw("select * ..", [id2, ]) # or use (id2,) for a tuple
<RawQuerySet: select * from ... where id = 5>
To get the actual list, since that just gives you a Query, you need to evaluate it somehow:
posts_list = list(posts)
first_post = posts[0]
Be careful, if you don't evaluate the QuerySet then it can be re-run a second time. Please convert it to a list() before doing further operations on it.

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 )

How should I get Open Graph JSON object to pass in facepy class

I am trying to configure Open Graph in my app such that, when ever a person click a "link" in it, the app should "post" it on his feeds/ timeline/ activity. (I created open graph actions for these features and successfully added meta tags in the page).
So, I am using fandjango and facepy to do this job.
This is how my code looks..
from facepy import GraphAPI
#csrf_exempt
#facebook_authorization_required(permissions=["publish_actions"])
def ViewPage (request):
access_token = request.facebook.user.oauth_token
profile_id = request.facebook.user.facebook_id
path = "/%d/feed" %profile_id
# How should I get the OpenGraph JSON obj
og_data = ??
graph = GraphAPI(access_token)
graph.post(path, og_data)
...
return render_to_response("view.html", context)
How should I get the open graph JSON obj to pass in the above graph object as parameter so as to post data in feeds/ timeline/ activity?
If this is not the way, how should I do it?
Edit 1:
when I tried
graph = GraphAPI(request.facebook.user.oauth_token)
graph.post("me/namespace:action")
It showed me `OAuthError`
Error Loc: C:\Python27\lib\site-packages\facepy\graph_api.py in _parse, line 274
graph = GraphAPI(request.facebook.user.oauth_token)
graph.post("me/namespace:action", "object type")
It showed me `TypeError`
loc: same as previous
Edit 2:
Instead to using request.facebook.user.oauth_token, I directly used my access token and the code worked..
graph = GraphAPI (my-hard-coded-access-token)
graph.post("me/feed", message = "working!")
However, when I tried
graph.post("me/news.reads", article="working")
It showed me error.
I created open graph actions
You shouldn't be using me/feed then
The OpenGraph calls are as follows
me/[app_namespace]:[action_type]?[object_type]=[OBJECT_URL]
So, to achieve the same just set the path to me/[app_namespace]:[action_type]
graph.post(
path = 'me/[app_namespace]:[action_type]',
[object_type] = '[OBJECT_URL]'
)
og_data is not a parameter in the call. So if your object_type is recipe then it would be
graph.post(path, recipe)
If you want to continue to use me/feed then it should be
graph.post(path, link)
as described at http://developers.facebook.com/docs/reference/api/user/#posts
You cannot do customs read actions like that, the proper call should be
graph.post(
path = 'me/news.reads',
article = 'http://yourobjecturl/article.html'
)
Please read the documentation http://developers.facebook.com/docs/opengraph/actions/builtin/#read
You're getting an OAuthError because you're initializing the Graph API client with an instance of a class instead of a string.
Try this:
graph = GraphAPI(request.facebook.user.oauth_token.token)
Alternatively, you could use the graph propery of the Fandjango's User model to get a preinitialized instance of the Graph API client:
request.facebook.user.graph

Django, Tastypie and retrieving the new object data

Im playing a little bit with heavy-client app.
Imagine I have this model:
class Category(models.Model):
name = models.CharField(max_length=30)
color = models.CharField(max_length=9)
Im using knockoutjs (but I guess this is not important). I have a list (observableArray) with categories and I want to create a new category.
I create a new object and I push it to the list. So far so good.
What about saving it on my db? Because I'm using tastypie I can make a POST to '/api/v1/category/' and voilĂ , the new category is on the DB.
Ok, but... I haven't refresh the page, so... if I want to update the new category, how I do it?
I mean, when I retrieve the categories, I can save the ID so I can make a put to '/api/v1/category/id' and save the changes, but... when I create a new category, the DB assign a id to it, but my javascript doesn't know that id yet.
in other words, the workflow is something like:
make a get > push the existing objects (with their ids) on a list > create a new category > push it on the list > save the existing category (the category doesnt have the id on the javacript) > edit the category > How I save the changes?
So, my question is, what's the common path? I thought about sending the category and retrieving the id somehow and assign it to my object on js to be able to modify it later. The problem is that making a POST to the server doesn't return anything.
In the past I did something like that, send the object via post, save it, retrieve it and send it back, on the success method retrieve the id and assign it to the js object.
Thanks!
Tastypie comes with an always_return_data option for Resources.
When always_return_data=True for your Resource, the API always returns the full object event on POST/PUT, so that when you create a new object you can get the created ID on the same request.
You can then just read the response from your AJAX and decode the JSON (i dont know about knockout yet).
see the doc : http://readthedocs.org/docs/django-tastypie/en/latest/resources.html?highlight=always_return_data#always-return-data
Hope this helps

Deleting object in django and API call

I am trying to delete a client object in my program and then also delete the object in activeCollab using the API provided. I can delete the object but I keep getting a 404 error when it calls the API. I did a print for c.id and I am getting the correct ID, and if I replace ':company_id' in the req statement with the actual ID of the client, it works.
Here is my code for the delete:
def deleteClient(request, client_id):
c = get_object_or_404(Clients, pk = client_id)
#adding the params for the request to the aC API
params = urllib.urlencode({
'submitted':'submitted',
'company[id]': c.id,
})
#make the request
req = urllib2.Request("http://website_url/public/api.php?path_info=/people /:company_id/delete&token=XXXXXXXXXXXXXXXXXXXX", params)
f = urllib2.urlopen(req)
print f.read()
c.delete()
return HttpResponseRedirect('/clients/')
Thanks everyone.
Oh here is the link to the API documentation for the delete:
http://www.activecollab.com/docs/manuals/developers/api/companies-and-users
From the docs it appears that :company_id is supposed to be replaced by the actual company id. This replacement won't happen automatically. Currently you are sending the company id in the POST parameters (which the API isn't expecting) and you are sending the literal value ':company_id' in the query string.
Try something like:
url_params=dict(path_info="/people/%s/delete" % c.id, token=MY_API_TOKEN)
data_params=dict(submitted=submitted)
req = urllib2.Request(
"http://example.com/public/api.php?%s" % urllib.urlencode(url_params),
urllib.urlencode(data_params)
)
Of course, because you are targeting this api.php script, I can't tell if that script is supposed to do some magic replacement. But given that it works when you manually replace the :company_id with the actual value, this is the best bet, I think.