Update a Twilio number properties with a dictionary programatically - python

I have a Twilio number and a dictionary full of params that I want to set up. The only way I know to set number properties is by passing them into the number.update() function, so this is kinda annoying.
If the dictionary keys have the same name as the inputs I'm trying to pass to the update function, is there a cleaner way to do this?
or, can I do better than this?
params = {
'voice_url':'http://endpoint.co',
'friendly_name':'call a dinosaur'
}
number.update(voice_url=params['voice_url'], friendly_name=params['friendly_name']

Twilio developer evangelist here.
To do this you can use the unpacking operator ** like this:
number.update(**params)
** unpacks a dictionary into keyword arguments.

Related

Create Flask endpoint using a Loop

I want to create multiple Flask endpoints I read from my Config. Is it possible to make a for or while loop to create them? The Endpoints Address would be variable, but there would be no limit on how many I would need.
My Idea was:
for x in myList:
#app.route(var, ...)
def route():
do smt ...
Thanks for your help
You can use
app.add_url_rule(rule, endpoint=None, view_func=None, provide_automatic_options=None, **options)
to achieve this.
For example:
for endpoint in endpoint_list:
app.add_url_rule(endpoint['route'], view_func=endpoint['view_func'])
Check out the docs.
Note that the endpoint_list contains records of endpoints. It should be a list of dictionaries, for example:
endpoint_list = [
{
"route": "/",
"view_func": index
},
.....
]
Avoid using "list" as the variable name. It would override Python's default list function.

I am a beginner in python where is the error

#python
sql="UPDATE bebliothequee SET title=:titl,author=:autho,ISBN=:ISB WHERE oid='{}'.format(oid.get())",title='{}'.format(title_editor.get()),author='{}'.format(author_editor.get()),ISBN='{}'.format(ISBN_editor.get()),oid='{}'.format(record_id.get())
Your first mistake is that you didn't read Stackoverflow documentation how to create good question. So you didn't add all details in question - and we can't read in your mind - and we can't help it.
Next mistake: you put code in comment but you should put it in question so it would be more readalbe but what is more important: all people could see it and help you.
Code shows that you try to create sql =... with all arguments for execute() and later use it in execute() but it doesn't work this way. You can't assing positional and named values to variable and later put it in function. You should use it directly in execute() or you should create list/tuple with positional variables and dictionary with named variables.
BTW: you don't need '{}'.format() to convert it to strings. You could use str() but I think execute() should convert it automatically.
query = "UPDATE bebliothequee SET title=:title, author=:author, ISBN=:ISBN WHERE oid=:oid"
execute(query, title=title_editor.get(), author=author_editor.get(), ISBN=ISBN_editor.get(), oid=record_id.get())
Other problem is that you use :titl but you should use full name :title like in argument title=....
You have also oid='{}'.format(oid.get() inside query which is totally useless.
BTW: Eventually you can create dictionary
args = {
'title': title_editor.get(),
'author', author_editor.get(),
'ISBN': ISBN_editor.get(),
'oid': record_id.get(),
}
and then you can use ** to unpack it as named arguments
execute(query, **args)

Pass kwargs into Django Filter

When viewing model entries from within Django Admin, you can specify filters. How can I mimic this behavior? Not to familiar with kwargs but something similar to this:
foo = Model.objects.filter(**__exact='**')
where the first set of ** would be a field in the model and the second set would be an entry. Basically making the queries variable, based on what the user chooses on the front end. How would I send that variable sort option to the view, and then return it back to the webpage. What about using a dictionary? Please help
This SO question has proven to be a little helpful, but still cannot grasp it completely.
You can unpack a python dict as your filter parameters using **
your_filters = {
'field_1__exact': value_1,
'field_2__gte': value_2,
}
Model.objects.filter(**your_filters)
Said that, you can built your query filters(a python dict) dynamically based on an user input.

Benefit of initializing dictionary in function call

I was looking at this code on the Google Map API website:
import simplejson, urllib
GEOCODE_BASE_URL = 'http://maps.googleapis.com/maps/api/geocode/json'
def geocode(address,sensor, **geo_args):
geo_args.update({
'address': address,
'sensor': sensor
})
url = GEOCODE_BASE_URL + '?' + urllib.urlencode(geo_args)
result = simplejson.load(urllib.urlopen(url))
print simplejson.dumps([s['formatted_address'] for s in result['results']], indent=2)
if __name__ == '__main__':
geocode(address="San+Francisco",sensor="false")
I noticed that in the geocode function, when we actually apply the function we don't use the geo_args dictionary when we call the function, but we instead use it to initialize a dictionary we update in the next lines. What is the benefit of using this, as opposed to initializing the dictionary within the function itself? It makes the code a bit less clear so I assume there is a reason for doing it.
geo_args is used. The literal dictionary
{
'address': address,
'sensor': sensor
}
updates geo_args, not the other way around.
The reason it's like this looks to me that address and sensor are required arguments. This structure allows the function to enforce that requireness, and also allow them to be passed positionally. The .update() is just there to consolidate all the arguments into one so they can be given to urllib.urlencode.
Not clear? This is the normal behaviour of **kwargs (the keyword argument dictionary).
So when you see something with **, a bunch of named parameters or keyword arguments will be passed.
Seeing the other answers. I probably misunderstood your question. I agree with the other answers: address and sensor are required.

tornado maps GET and POST arguments to lists. How can I disable this "feature"?

The HTTPRequest class in the tornado* web framework helpfully maps GET and POST arguments to lists. I understand why -- in case a given argument name is used multiple times. But for some RequestHandlers, this is a pain. For instance, if I want to pass a json object and parse it as-is on the server.
What's the most straightforward way to disable the map-to-list behavior so that I can send unaltered json to a tornado/cyclone server?
*Cyclone, actually, in case there's an implementation difference here.
Instead of accessing self.request.arguments directly you should use the accessor functions:
self.get_argument("ID", default=None, strip=False)
This returns a single item.
If you want to turn the arguments into a JSON object you can quite easily do so:
json.dumps({ k: self.get_argument(k) for k in self.request.arguments })
I'm going to go with "you're out of luck." You could re-write the class in question (looks like that would not be fun), but aside from that I don't see many options.
I would just use a dict comprehension.
{k:''.join(v) for k,v in self.request.arguments.iteritems()}

Categories

Resources