Pylons routing, what is the location attribute? - python

I'm looking at the reddit source code and ran into a route that looks like the following:
mc('/prefs/:location', controller='forms', action='prefs', location='options')
Searching the documentation here, I can't find anything related to the location attribute:
https://thejimmyg.github.io/pylonsbook/en/1.0/urls-routing-and-dispatch.html
What is location='options' supposed to do for this route?

routes.Mapper.connect() takes *args and **kwargs as arguments. Since locations='options' is a valid **kwargs entry and in a valid location, it will be accepted as a valid passed variable. I don't have the source code available, so I don't know what connect() will do with this variable. I'm guessing it simply attaches the extra name=value pairs to the created URLs.
You can find more documentation here: http://routes.readthedocs.io/en/latest/modules/mapper.html#routes.mapper.Mapper.connect

Related

Dialogflow Python API Required Parameter

I am trying to create a parameter that is required using the Python Dialogflow API v2. My current code is as follows:
parts.append(Intent.TrainingPhrase.Part(text=value,
alias=value,
entity_type='#' + value))
This works to create the parameter, but it is not required. The obvious first attempt was to add a required=True param, but that was not expected by the function call.
Looking at their docs (https://googleapis.dev/python/dialogflow/latest/gapic/v2/types.html) there does not seem to be any required/mandatory field.
I started to dig a little into their code, and found similar - there does not seem to be a required or mandatory field, except when creating the parameter?
https://github.com/googleapis/dialogflow-python-client-v2/blob/7bf592684b4d5df0cd1f66dd414efe2350d0461e/dialogflow_v2/proto/intent.proto
Ah, got it. My mistake was that you can create parameters for an intent as I was doing above, and it will add the parameter, but not required. You can explicitly specify a parameter as well, which is what has the mandatory field. Like this:
if len(parameters) > 0:
for parameter in parameters:
intent_parameter = Intent.Parameter(
display_name=parameter.name,
value=parameter.name,
entity_type_display_name='#' + parameter.name,
mandatory=True
)
intent.parameters.extend([intent_parameter])

Sphinx revealing my (mailgun) password

I have a simple function
import config
def send_message(mailgunkey=config.MAILGUNKEY):
"""
send an email
"""
It relies on a variable defined in my config.py file. I read the variables from local files on all my machines as I don't want to have my keys etc. in any repository. However, I recently got into the habit of using Sphinx. When generating the html docs the expression config.MAILGUNKEY is getting evaluated and the actual key is revealed in the html file. Is there an option to stop this kind of undesired action?
Consider using this approach:
import config
def send_message(mailgunkey=None):
"""
send an email
"""
if mailgunkey is None:
mailgunkey = config.MAILGUNKEY
In general, this approach gives you some important advantages:
lets your users pass None as the default;
allows changes to config.MAILGUNKEY even if your module has already been imported;
solves the problem of mutable default arguments (not your case, but still it's something to be aware of).
The second point is, in my opinion, something very important, as I would be very surprised to see that changes to a configuration variable at runtime have no effects.
Another option would be to mock the module that has your secrets.
This avoids needing to change your code to generate documentation.
Assuming you are using autodoc; add the below to your conf.py:
autodoc_mock_imports = ["config","secrets",]
https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html?highlight=autodoc_mock_imports%20#confval-autodoc_mock_imports
The autodoc_preserve_defaults configuration option was added in Sphinx 4.0.
The problem is solved by setting this option to True in conf.py. Default argument values of functions will not be evaluated and shown in the generated output.

Django reverse routes - two optional parameters

I have a question about Django and it's routing system. I believe that it can be powerfull, but right now I am struggling with one issue I don't experience when working in other frameworks and I can't seem to get a grip on it. Worth to mention that I don't have much experience with Django at this point.
The issue is simple - I have a view which takes two optional parameters, defined like this
def test_view(id=None, grid=None):
Both parameters are optional and frequently are not passed. Id can only be an integer and grid will never be an integer (it is a special string to control datagrid when I don't want to use sessions). I have a route defined like this:
url(a(r'^test_view (\/(?P<id>\d+))? (\/(?P<grid>[^\/]+))? \/?$'), views.test_view, name='test_view'),
This works great and I am not having trouble with using one-way routes. But when I try to use the reverse function or url template tag, following error occurs:
Reverse for 'test_view' with arguments '('20~id~desc~1',)' and keyword arguments '{}' not found.
In this example I tried to find reverse without the id, just with the grid parameter. I have tried various methods of passing parameters to the reverse function:
(grid, )
(None, grid)
('', grid)
{id=None, grid=grid}
All of them result in same error or similliar one.
Is there a way to implement this in django? Maybe just disable the cool URL for the grid parameter. That is how I do it in for example Nette framework for PHP, isntead of having an url like this: 'localhost/test_view/1/20~id~desc~1' I have url like this: 'localhost/test_view/1?grid=20~id~desc~1'. This would be completely sufficient, but I have no idea how to achive this in Django.
As you note in your question, the best way to achieve this is to use standard GET query parameters, rather than doing it in the path itself. In Django you do that exclusively in the view; the URL itself is then just
url(r'^test_view$', views.test_view, name='test_view'),
and you request it via localhost/test_view?id=1&grid=20~id~desc~1. You get the params from request.GET, which is a dictionary-like object; you can use .get so that it does not raise a KeyError when the key is not provided.
def test_view(request):
id = request.GET.get('id')
grid = request.GET.get('grid')

Linkedin API for python

I used this library to make API requests and got the access tokens successfully.
But the documentation does not explain how _access_token and _access_token_secret should be used afterwards future. I suppose that there should be a method like:
set_access_token(_access_token, _access_token_secret)
but I could't find a method like that in this code or documentation.
Please help me to solve this problem.
I have not used this particular library or API, but a common pattern in these cases is that you pass the token as an argument to subsequent calls. Looking at the source, I can see a function called get_user_profile in __init__.py:
def get_user_profile(self, access_token, selectors=None, headers=None, **kwargs):
"""
Get a user profile. If keyword argument "id" is not supplied, this
returns the current user's profile, else it will return the profile of
the user whose id is specificed. The "selectors" keyword argument takes
a list of LinkedIn compatible field selectors.
"""
So I'd guess you just want to pass the token as the first argument (in this instance).

pyramid_handlers not working

I'm currently moving a project from Pylons 1.0 to Pyramid.
My problem so far is how to use restful routes in Pyramid. I'm currently using pyramid_handlers since it seemed like a good start. I'm using Akhet.
So here is the two important lines in my route:
config.add_handler("new_account", "/accounts/new", "sproci2.handlers.accounts:Accounts")
# or
config.add_handler("new_account", "/accounts/new", "sproci2.handlers.accounts:Accounts", action="new")
My action:
#action(name="new_account", renderer='accounts/new.mako', request_method='GET')
The errors:
TypeError: 'Accounts' object is not callable
or
ValueError: Could not convert view return value "{}" into a response Object.
Accounts... so far so good, it is easy to understand that pyramid_handlers doesn't seem to register normally or handle name as it should... that said in request.matched_route, I do have "new_account".
If I add "action='new'" in the route definition, it will find the function but it will not listen to the action definition. In other words, it will fail to find a renderer and expect a response object. The request_method parameter doesn't actually do anything yet, so removing it doesn't change any results.
In short, the #action(name="..." doesn't work. Pyramid fails to find the function by itself and if the function name is defined it fails to execute the action statement.
No idea what I'm doing wrong.
Correct way to do it.
config.add_handler("new_account", "/accounts/new", "sproci2.handlers.accounts:Accounts", action="new_account")
EDIT
route_name is probably going to get used by url generator functions. While action is the actual name in #action. As I understood, #action name was the route_name and not the action name. That makes more sense now.
Well a call to add_handler needs an action pattern. So that's either adding {action} to the url pattern, or setting action= as an argument. Those actions must match the names defined in #action decorators. In your example, you named the action new_account, yet you called add_handler with an action of new. Thus they aren't properly connected.

Categories

Resources