问题
I have a bunch of string and integer constants that I use at various places in my app. I am planning to put them up in a centralized location, so that it is easier to change them in the future. I could think of the following approaches:
1) Have them as individual variables, stored in the model db.py
settings_title = "My Amazing App"
settings_ver = 2.0
settings_desc = "Moar and Moar cats"
2) Have them as a dict, stored in db.py
settings = { "title": "My Amazing App",
"ver" = 2.0,
"desc" = "Moar and Moar cats"
}
- Is it a good idea to use the model
db.py
? I've heard that it is evaluated for every request. Could putting settings there have a noticeable overhead? - Is there any difference, performance-wise between the two approaches?
- Is there a better way of doing this?
回答1:
Your db.py model file will be executed on every request in any case, so adding a few setting assignments to the code will add negligible overhead. Instead of putting the settings in db.py, for better organization you might consider creating a separate model file. Note, model files are executed in alphabetical order, so if the settings have to be available in subsequent model files, name the settings file something like 0_settings.py to ensure it is executed before any other model files.
If you prefer, you can instead put the settings in a module (e.g., settings.py) in the application's /modules folder and import the settings object in your application code wherever you need it (in that case, the module will only be loaded once by the interpreter). If any of the settings need to be set dynamically based on the incoming request, though, you are probably better off keeping the settings in a model file.
Finally, rather than a standard dictionary, you might consider using a web2py Storage
object, which is like a dictionary but allows you to access values as attributes and returns None rather than a KeyError if you try to access a key/attribute that doesn't exist:
from gluon.storage import Storage
settings = Storage()
settings.title = 'My Amazing App'
or
settings = Storage({'title': 'My Amazing App'})
Note, the web2py request
, response
, and session
objects are all instances of the Storage
class.
回答2:
You can directly put your config variable in .py
file and use that file by import in your module as django used setting.py
. If you want to combine the variable on some section bases then you can use ConfigParser which can ready the .cfg
file.
回答3:
Django, for instance, uses a file settings.py.
It's not a model, but just a collection of variables of all types, strings/ints/dicts/whatever, and you import settings
or from settings import *
in every module that needs access to them.
Since it is not a single model, there's no overhead on access.
来源:https://stackoverflow.com/questions/9736769/storing-configuration-details