I am trying to write a facebook app where user can see the status history of his friends.
Everything seems to work fine until I try to save the status information in my DB.
here is code :
class UserStatus(models.Model):
facebookid = models.IntegerField()
time = models.IntegerField()
status_msg = models.CharField(max_length = 2000)
#facebook.require_login()
def canvas(request):
# Get the User object
user, created = FacebookUser.objects.get_or_create(id = request.facebook.uid)
user_lastname = request.facebook.users.getInfo([request.facebook.uid], ['last_name'])[0]['last_name']
query = "SELECT time,message FROM status WHERE uid=%s" % request.facebook.uid
result = request.facebook.fql.query(query)
So result give me all the information of the status.
so my problem is its give error when I try to save it.
userstatus = UserStatus()
for item in result:
userstatus.facebookid = request.facebook.uid
userstatus.time = item.time
userstatus.msg = item.message
userstatus.save()
error:
Errors while loading page from application
Received HTTP error code 500 while loading
So how can I fix this.
thanks.
First you should check if you are getting results from this,
result = request.facebook.fql.query(query)
Make sure that the results are in correct format required by your model ( uid is integer, time is integer and message is string.
Again make sure that result is a valid python object and not a JSON string/Object.
Remember python is not fully compatible with JSON so if result is JSON then do this to convert it to python Object,
import simplejson
result = simpljson.loads(result) # if result was a JSON string
result = simpljson.loads(simplejson.dumps(result)) # if result was a JSON object
Check if now result is a list of dictionaries { "time" : 123456, "messaage": "xyz"}.
for item in result:
userstatus = UserStatus()
userstatus.facebookid = request.facebook.uid
userstatus.time = item["time"]
userstatus.msg = item["message"]
userstatus.save()
And you should not have any errors now.
Related
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.
I am stuck with a silly problem.
I have a json data and trying to save it in my model.
Here is the code.
response = response.json() #this gives json data
response = json.loads(response) #loads string to json
json_string = response #ready to get data from list
modelfielda = json_string.get("abc") # this works fine
modelfieldb = json_string.get('["c"]["d"]["e"]') #this does not give data though data is present.
My json data comes like this:
{
"abc":"AP003",
"c":[
{
"d":{
"e":"some data",
"f":"some data"
}
}
]
}
So my question is how to get data inside c.
Try this for e:bnm = json_string.get('c').get('d').get('e') or with list:
bnm = json_string.get('c')[0].get('d').get('e')
By using multiple .gets:
bnm = json_string.get('c')[0].get('d').get('e') # bnm = 'some data'
Or perhaps better (since it will error in case the key does not exists):
bnm = json_string['c'][0]['d']['e'] # bnm = 'some data'
Since you converted it to a Python dictionary, you basically work with a dictionary, and you can obtain the value corresponding to a key by using some_dict[some_key]. Since we here have a cascade of dictionaries, we thus obtain the subdictionary for which we again obtain the corresponding value. The value corresponding to c is a list, and we can obtain the first element by writing [0].
I am getting result from BigQuery using the following code:
from google.oauth2 import service_account
from google.cloud import bigquery
credential = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE)
scoped_credential = credential.with_scopes(BIG_QUERY_SCOPE)
client = bigquery.Client(project="XX-XX",credentials=scoped_credential)
query_results = client.run_sync_query(query_detail)
query_results.use_legacy_sql = False
query_results.run()
iterator = query_results.fetch_data()
rows = iterator.query_result.rows
But it only returns up-to 50000 rows. I tried to paginate while fetching data, but failed to figure out how to do it:
page_token = query_results.page_token
iterator = query_results.fetch_data(max_results=500, page_token=page_token)
I could not find out how to get the updated page_token.
Thanks,
I think you are close. Try running this code now:
data = list(query_results.fetch_data()) # changed from `iterator` to `data` the variable name
The management of page tokens is done automatically for you.
I am trying to access POP3 email server. I will be polling messages and downloading attachments for each one of them. I can successfully login and get the messages but cannot figure out how to actually get the attachment, which I would need to parse later.
I'm thinking I could save to tmp dir until I process it.
Here's what I got so far:
pop = poplib.POP3_SSL(server)
pop.user(usr)
pop.pass_(pwd)
f = open(file_dir, 'w')
num_msgs = len(pop.list()[1])
for msg_list in range(num_msgs):
for msg in pop.retr(msg_list+1)[1]:
mail = email.message_from_string(msg)
for part in mail.walk():
f.write(part.get_payload(decode=True))
f.close()
This is code I pieced together from the examples I found online but no solid example of actually getting the attachment. The file I'm writing to is empty.
What am I missing here?
Please see a complete example below.
Import poplib and parser
import poplib from email import parser
A function to return a connection to the pop server:
def mail_connection(server='pop.mymailserver.com'):
pop_conn = poplib.POP3(server)
pop_conn.user('someuser#server')
pop_conn.pass_('password')
return pop_conn
A function to fetch the mail:
def fetch_mail(delete_after=False):
pop_conn = mail_connection()
messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
messages = ["\n".join(mssg[1]) for mssg in messages]
messages = [parser.Parser().parsestr(mssg) for mssg in messages]
if delete_after == True:
delete_messages = [pop_conn.dele(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
pop_conn.quit()
return messages
Then a function to save the attachments as files. NB, the allowed mimetypes; you could have a list of them, such as:
allowed_mimetypes = ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"]
and so on.
def get_attachments():
messages = fetch_mail()
attachments = []
for msg in messages:
for part in msg.walk():
if part.get_content_type() in allowed_mimetypes:
name = part.get_filename()
data = part.get_payload(decode=True)
f = open(name,'wb')
f.write(data)
f.close()
attachments.append(name)
return attachments
I know this is an old question, but just in case: The value you're passing to email.message_from_string is actually a list of the contents of the email, where each element is a line. You need to join it up to get a string representation of that email:
mail = email.message_from_string("".join(msg))
Is there a way to programmatically log into Yahoo!, providing email id and password as inputs, and fetch the user's contacts?
I've achieved the same thing with Gmail, using BeautifulSoup.py
Yahoo Address book API provides BBAuth, which requires the user to be redirected to Yahoo login page. But I'm looking for a way to authenticate the user with Yahoo without the redirection.
I have tried this :
http://pypi.python.org/pypi/ContactGrabber/0.1
but I am getting this Error:
Warning (from warnings module): File
"C:\Python26\lib\site-packages\contactgrabber-0.1-py2.6.egg\contactgrabber\base.py",
line 31
RuntimeWarning: tempnam is a potential security risk to your program
Invalid UserID/Password
Exception WindowsError: (2, 'The system cannot find the file
specified', 'C:\DOCUME~1\sjain\LOCALS~1\Temp\2') in > ignored
I solved this problem by using Urllib here is the code :
LoginUrl = "https://login.yahoo.com/config/login?"
ExportUrl = "http://address.yahoo.com/"
def import_yahoo_contacts(login,passwd):
try :
form_data = {'login' : login, 'passwd' : passwd}
jar = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar))
form_data = urllib.urlencode(form_data)
resp = opener.open(LoginUrl, form_data)
resp = opener.open(ExportUrl)
page = resp.read()
index = page.find('InitialContacts')
startjson = page.index('[',index)
endjson = page.index(']',index)
Jsondata = page[startjson:endjson+1]
user_contacts = []
data =json.JSONDecoder().decode(Jsondata)
for r in data:
userfriends = []
userfriends.append(r.get('contactName'))
userfriends.append(r.get('email'))
user_contacts.append(userfriends)
except:
return []
return user_contacts
This really work for me :)
You could write one or just use Pinax. Pinax is a collection of tools built on top of Django. They have a application which imports contact imfo (from vCard, Google or Yahoo).
I suggest you use this as you don't have to maintain it plus to avoid reinventing the cycle.