Facebook get AdImage url from image_hash - python

My code (python-business-sdk):
account = AdAccount(ad_account_id)
img = account.get_ad_images(params={'hashes': ['6b709f0275d0bdf18fb78ef08492ee79'})[0]
print(img['url']) # doesnt work
primt(img[AdImage.Field.url]) # doesnt work
I do the request but get only id and hash in my img var (AdImage obj):
'{..., _json': {'hash': '6b709f0275d0bdf18fb78ef08492ee79', 'id': '36246837:6b709f0275d0bdf18fb78ef08492ee79'}}}
But i need the url of image, here's documentation with the fields (url is there) but i don't receive those or don't know how to get..
https://developers.facebook.com/docs/marketing-api/reference/ad-image#examples_read

Just add fields argument to get_ad_images

Related

How can I access Json attribute and check if (key)exist in payload or not using python

This is my UI
End user can able to update Summary or my_story one at a time, This is my endpoint URL http:localhost:3000/api/account/profile, once user update any one of the field, the URL will work
This is Request payload for summary field
If the user update the Summary field the above endpoint URL will work.
This is Request payload for my_story field
If the user update the my_story field the above endpoint URL will work.
My code(Once the user update anyone of the field. I want to check which field is updated, for this how can I check whether the user is updated Summary or my_story,after accessing the field I want to sanitize the field and send it to response below one is my code):
from lxml.html import clean
def account_update():
data = json.loads(request.data)
cleaner = clean.Cleaner()
if data['other_details']['summary']:
clean_overview = (data['other_details']['summary'])
sanitized_html = cleaner.clean_html(clean_overview)
else:
clean_overview = (data['other_details']['my_story'])
sanitized_html = cleaner.clean_html(clean_overview)
return jsonify({"account": data})
Guys , in the above code I am getting the request payload as data, after that I am accessing the summary and my_story fields as data['other_details']['summary'] and data['other_details']['summary'], here I wrote if condition to check if the user update summary field if condition will work suppose user update my_story field it will goes to else part, but in my case if I update my_story field getting error.
Error:
if data['other_details']['summary']:
KeyError: 'summary'
NOTE:
Sanitizing the field is working fine (I mean cleaner = clean.Cleaner() and sanitized_html = cleaner.clean_html(clean_overview), I just want to know which field the user is updating. Please help me guys.
Most likely, the request.data doesn't always have the summary field in data['other_details'].
This means, you have to check for it in you if-else block before trying to access it.
Best to check for other_details as well.
Here is one way of doing this:
from lxml.html import clean
def account_update():
data = json.loads(request.data)
cleaner = clean.Cleaner()
if 'other_details' in data:
other_details = data['other_details']
if 'summary' in other_details:
clean_overview = other_details['summary']
sanitized_html = cleaner.clean_html(clean_overview)
elif 'my_story' in other_details:
clean_overview = other_details['my_story']
sanitized_html = cleaner.clean_html(clean_overview)
return jsonify({"account": data})
What i see your program just can't find summary atribute.
Solution 1
Im not sure this will work but function getattr() can help you.
Change this line
data['other_details']['summary']
To this
getattr(getattr(data,'other_details'),'summary', False)
Here you can learn more about getattr()
What is getattr() exactly and how do I use it?
Solution 2
Just use some try: and except:

Django HTTP request to api

So i been trying to get this to work but at the same time i do not understand some of these code means. I'm sorry for making the question so long but i want to understand how these works.
I am trying to make a HTTP request to another API to do POST and GET method using django. Based on the website code example, which is this url: https://www.twilio.com/blog/2014/11/build-your-own-pokedex-with-django-mms-and-pokeapi.html
As i wanted to use HTTP Request on my API to call other API, therefore i wanted to get a better understanding of how these works and how to use it.
The code is at the bottom of the website. But i will just provide the code here so it is easier for you.
website code
from django_twilio.views import twilio_view
from twilio.twiml import Response
import requests
import json
BASE_URL = 'http://pokeapi.co'
def query_pokeapi(resource_uri):
url = '{0}{1}'.format(BASE_URL, resource_uri)
response = requests.get(url)
if response.status_code == 200:
return json.loads(response.text)
return None
#twilio_view
def incoming_message(request):
twiml = Response()
body = request.POST.get('Body', '')
body = body.lower()
pokemon_url = '/api/v1/pokemon/{0}/'.format(body)
pokemon = query_pokeapi(pokemon_url)
if pokemon:
sprite_uri = pokemon['sprites'][0]['resource_uri']
description_uri = pokemon['descriptions'][0]['resource_uri']
sprite = query_pokeapi(sprite_uri)
description = query_pokeapi(description_uri)
message = '{0}, {1}'.format(pokemon['name'], description['description'])
image = '{0}{1}'.format(BASE_URL, sprite['image'])
frm = request.POST.get('From', '')
if '+44' in frm:
twiml.message('{0} {1}'.format(message, image))
return twiml
twiml.message(message).media(image)
return twiml
twiml.message("Something went wrong! Try 'Pikachu' or 'Rotom'")
return twiml
My question is:
i have read about the request.POST and request.POST.get but i still don't get it. Isn't request.POST = POST method/create function ?
what does body.lower mean ? Cant seems to find anything about it.
I am very confuse about this part
sprite_uri = pokemon['sprites'][0]['resource_uri']
description_uri = pokemon['descriptions'][0]['resource_uri']
sprite = query_pokeapi(sprite_uri)
description = query_pokeapi(description_uri)
is pokemon['sprites'] refers to the sprites field in the api ?
What does this even means ?
frm = request.POST.get('From', '')
if '+44' in frm:
twiml.message('{0} {1}'.format(message, image))
return twiml
twiml.message(message).media(image)
return twiml
request.POST.get('From', '') Isn't POST where user enter data ? Where does 'From' come from? And what does this means ? if '+44' in frm: if +44 is found in frm ?
ALL The questions are based on very basic python concepts, I recommend you go through python docs here Python Docs
Diff in request.POST and request.POST.get()
Ex request.post has following dict {'abc_key': 'abc_value'}
than request.POST['abc_key'] will give 'abc_value'
but request.POST['xyz_key'] will throw error
so we use default value to escape this error
request.POST.get('xyz_key', "default_value")
this will not give error if xyz_key is not found
body.lower
This method returns a copy of the string in which all case-based
characters have been lowercased.
check this link lower()
pokemon['sprites'][0]['resource_uri']
this is serching in pokemon (which have dictionary values)
Ex. pokemon = {'sprites':[{'resource_uri': 'res_value'}, 1, 2, 3 ]}
so pokemon['sprites'][0]['resource_uri'] will give 'res_value'
frm = request.POST.get('From', '') same as i said in 1st point
if '+44' in frm:
this will return True if string '+44' is substring in frm
variable(string)

Changing '?' to '&' in address bar

For example, in my web-app I have a link with url www.example.com/profile?name=name. When I click to that link, I'm getting a page, where I can change profile's information, BUT after clicking to that link, url in adress bar turns into www.example.com/profile&name=name.
More interesting: when I make some changes and click SAVE - url reverts to www.example.com/profile?name=name.
If I don't click SAVE, just refresh page, i'm getting error 404.
How can it be possible?
P.S My view function
#check_document_access_permission()
def notebook(request, is_embeddable=False):
if not SHOW_NOTEBOOKS.get():
return serve_403_error(request)
notebook_id = request.GET.get('notebook', request.GET.get('editor'))
is_yarn_mode = False
try:
from spark.conf import LIVY_SERVER_SESSION_KIND
is_yarn_mode = LIVY_SERVER_SESSION_KIND.get()
except:
LOG.exception('Spark is not enabled')
return render('notebook.mako', request, {
'editor_id': notebook_id or None,
'notebooks_json': '{}',
'is_embeddable': request.GET.get('is_embeddable', False),
'options_json': json.dumps({
'languages': get_ordered_interpreters(request.user),
'session_properties': SparkApi.get_properties(),
'is_optimizer_enabled': has_optimizer(),
'is_navigator_enabled': has_navigator(request.user),
'editor_type': 'notebook'
}),
'is_yarn_mode': is_yarn_mode,
})
I found error.
In frontend was JS function, which incorrectly changed url.

python self.session doesn't save data correctly

I'm developing a webapp using Google App Engine and Python.
I'm facing a strange problem and i don't know how to solve it and what causes it.
When I fill a form I send the data for checking them. If they aren't complete and some fields are missed the server send the form back with an advice "FILL ALL THE FIELDS!".
That's work pretty well.
What I'm trying to do is sending the form back with the "description" and "title" fields filled with what the user has written before submitting the form, so he must to fill only the unfilled fields (and he doesn't need to rewrite everything from the beginning).
That's the code:
class SaleAnnCheck(BaseHandler):
def post(self):
title = self.request.POST.get('title')
cat = self.request.POST.get('cat')
description = self.request.POST.get('description')
AcqOpt = self.request.POST.get('AcqOpt')
lat = self.request.POST.get('lat')
lng = self.request.POST.get('lng')
image1 = self.request.POST.get("file1", None)
image2 = self.request.POST.get("file2", None)
image3 = self.request.POST.get("file3", None)
logging.info("info sale announcment")
logging.info(title)
logging.info(cat)
logging.info(description)
logging.info(AcqOpt)
logging.info(lat)
logging.info(lng)
logging.info(image1)
logging.info(image2)
logging.info(image3)
self.session["ECommerceUser"]["description"]=description
self.session["ECommerceUser"]["title"]=title
logging.info('session')
logging.info(self.session["ECommerceUser"])
if title == '' or cat == None or description == '' or AcqOpt == None or lat == '' or lng == '':
error = 'empty'
urlR='/CreateSaleAnn?'+urllib.urlencode({'error':'empty'})
self.redirect(urlR)
class Create(BaseHandler):
def get(self):
error = self.request.get('error')
if error == 'empty':
logging.info('sbagliato')
logging.info(self.session["ECommerceUser"])
template = JINJA_ENVIRONMENT.get_template('templates/CreateAnnouncement.html')
w = self.response.write
w(template.render({'error':'FILL ALL THE MANDATORY FIELDS!', 'description': self.session["ECommerceUser"]["description"], 'title': self.session["ECommerceUser"]["title"]}))
else:
logging.info('giusto')
logging.info(self.session["ECommerceUser"])
template = JINJA_ENVIRONMENT.get_template('templates/CreateAnnouncement.html')
w = self.response.write
w(template.render({'description': self.session["ECommerceUser"]["description"], 'title': self.session["ECommerceUser"]["title"]}))
When I submit the form the content is checked by making an HTTP post request to a certain URL, handled by SaleAnnCheck.
Description and Title are saved in the session correctly (i checked it by printing the content of self.session["ECommerceUser"] in the logs). Then, if a field isn't filled, the server redirect again to the form page, by a GET request to a related URL.
The requests to that URL is handled by Create. But when i try to render the HTML template of the form (using jinja2) with the previous typed values of Description and Title the related text areas are not filled with that values.
It happens because self.session["ECommerceUser"]["description"] and self.session["ECommerceUser"]["title"] are empty, but they weren't when i checked them before (in SaleAnnCheck).
Why it happens? Any explanation? It's a weird problem and there aren't any tips or suggestion about on internet
This is because 'self.session' is not a Session, it's just a class variable and will not be readable outside the class. If you really want to use persistent sessions for storing variables, try something like this:
From the docs:
http://docs.python-requests.org/en/master/user/advanced/
s = requests.Session()
s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
r = s.get('http://httpbin.org/cookies')

Django AngularJS JSONResponse view in rendering json output

i am developing one of my site with the python django where i have been using angularjs in one of my page where i have given the user option to search (specific request). Here is my model..
class Request(models.Model):
description = models.TextField(blank=True,null=True)
category = models.ForeignKey(Category)
sub_category = models.ForeignKey(SubCategory)
In my views I am returning through the following code:
def some(code, x):
exec code
return x
def search_request(request):
page = request.GET.get('page')
term = request.GET.get('term')
i = 0
terms = "x = Request.objects.filter("
for t in term.split(" "):
i=i+1
if(len(term.split(" "))>i):
terms = terms +"Q(name__icontains='"+t+"')|"
else:
terms = terms +"Q(name__icontains='"+t+"'))"
junk = compile(terms,'<string>', 'exec')
spit = Request.objects.filter(name__icontains=term)
requests = some(junk,spit)
output = HttpResponse()
output['values']=[{'requests':r,'category':r.category,'subcategory':r.sub_category} for r in requests]
return JSONResponse(output['values'])
In my HTML code when I return using AngularJS:
$scope.search = function(){
$scope.results = $http.get("{% url 'search-requests-show' %}?term="+$scope.term).then(
function(result){
return result.data;
}
);
}
The result on the HTML Output comes as in {[{results}]}:
"[{'category': <Category: The New Category>, 'requests': <Request: Need a Table>, 'subcategory': <SubCategory: Testsdfsdfsad>}]"
The problem is that I am not being able to access using results.category because the output is in "string", so the ng-repeat="result in results" brings the result as
[ { ' c a .....
I am probably doing something wrong in view. If anybody has any suggestion then please answer.
JSONResponse is probably using standard python json encoder, which doesn't really encode the object for you, instead it outputs a string representation (repr) of it, hence the <Category: The New Category> output.
You might need to use some external serializer class to handle django objects, like:
http://web.archive.org/web/20120414135953/http://www.traddicts.org/webdevelopment/flexible-and-simple-json-serialization-for-django
If not, you should then normalize object into simple python types inside the view (dict, list, string.., the kind that json module has no problem encoding). So instead doing:
'category':r.category
you could do:
'category': {'name': r.category.name}
Also as a sidenote: using exec is super bad idea. Don't use it in production!
You should return json strings for Angular:
import json
def resource_view(request):
# something to do here
return HttpResponse(json.dumps(your_dictionary))
for better usage i recommend djangorestframework.
Off Topic:
$http.get("{% url 'search-requests-show' %}?term="+$scope.term);
you can pass 'param' object:
$http.get("{% url 'search-requests-show' %}", {param : {term:$scope.term}});

Categories

Resources