I'm working on learning Pyramid, and I'm trying to use a custom configuration from my development.ini file in one of my views. In this example, "ldap_server".
[app:main]
use = egg:myapp
pyramid.reload_templates = true
pyramid.includes =
pyramid_debugtoolbar
ldap_server = 10.10.10.10
[server:main]
use = egg:waitress#main
listen = 0.0.0.0:6543
I find I'm able to access the value of "ldap_server" from within my main function in myapp/__init__.py
. (The example below will print "The ldap server is 10.10.10.10" upon startup via pserve development.ini
.)
from pyramid.config import Configurator
def main(global_config, **settings):
config = Configurator(settings=settings)
config.include('pyramid_jinja2')
config.include('.routes')
config.add_static_view(name='static', path='myapp:static')
config.scan('.views')
config.scan('.templates')
ldap_server = settings.get('ldap_server')
print('The ldap server is ' + ldap_server)
return config.make_wsgi_app()
That said, I want to use this value in one of my views. I'm struggling to find documentation on how to do this. I've read a couple of documents, but I am still struggling to grasp this.
Documentation: Environment variables and .ini file settings, adding a custom setting
Specifically, I'm trying to understand which Pyramid functions to import in my view, and how to access the 'ldap_server' value I defined in file development.ini.
Here is the current snippet from myapp/views/login.py file:
from pyramid.view import view_config, view_defaults
import ldap
@view_defaults(renderer='../templates/login.jinja2')
class TutorialViews(object):
def __init__(self, request):
self.request = request
self.view_name = 'login'
@view_config(route_name='login')
def login_page(self):
ldap_server = [ get value from development.ini ]
do ldappy stuff...
How can I do it?
This seems like it would be a trivial thing to accomplish. Is there an example of how to do this? Is there some documentation that provides examples?
Below is the working solution (login.py), e.g., for someone new to Pyramid. It is just one line of change. Thanks to Sergey for his explanation in the answer below.
from pyramid.view import view_config, view_defaults
import ldap
@view_defaults(renderer='../templates/login.jinja2')
class TutorialViews(object):
def __init__(self, request):
self.request = request
self.view_name = 'login'
@view_config(route_name='login')
def login_page(self):
ldap_server = self.request.registry.settings['ldap_server']
# <Do ldappy stuff...>
I think you should be able to access it via request.registry.settings
:
If the settings argument is passed, it should be a Python dictionary representing the deployment settings for this application. These are later retrievable using the pyramid.registry.Registry.settings attribute (aka request.registry.settings).
https://docs.pylonsproject.org/projects/pyramid/en/latest/api/config.html