Is it possible to alter the contents of a view/template based on specific user-defined settings in development.ini or production.ini.
As an example say I am developing a pyramid web-app that lists all the students of the class. The back-end database has only one table – ‘student’. Now I develop an optional script that also adds a table ‘teacher’ to the database. Ideally the web-app should be able to run for both the cases. If teacher table is missing, it will not query it and simply print student details. If teacher table is present, it will print name of the teacher along with the name of the student.
To my mind this can be accomplished in one of the following ways –
- Keep separate routes (URLs) for teacher+student and student only
pages. The problem is that you cannot stop people from actually
calling the former when you only have student info. This will lead
to unnecessary error pages - Use a setting teacher_enabled=true/false in .ini file. The setting can be accessed in __ init __.py file through settings[‘teacher_enabled’]. Configure just a single route (say’home’,’/’) but map it to different views based on whether seeting variable is true/false. This will not allow for use of @view_config decorator and templates for both cases will have to be separate
- Again using the setting variable, pass it to the view somehow. Make only relevant queries in the view. E.g. – If the teacher_enabled is True, query the teacher table else query the student table only. Pass this variable to templates too and there decide if some details are to be displayed (e.g. teacher name).
So my question is which of these approaches should I use? In case settings variables are to be passed to the views, how can that be done? And is there a standard way of dealing with this problem?
Ah, but you can! Combine it with number 2: Add a teacher_enabled=true/false setting to your .ini file, and then you can use some code similar to this:
Number 3 is also feasible. Just remember: It’s easier to ask for forgiveness than permission. So you could do something like this: (Using SQLAlchemy as an example)