Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

base.py 5.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. # -*- coding: utf-8 -
  2. #
  3. # This file is part of gunicorn released under the MIT license.
  4. # See the NOTICE for more information.
  5. from __future__ import print_function
  6. import os
  7. import sys
  8. import traceback
  9. from gunicorn._compat import execfile_
  10. from gunicorn import util
  11. from gunicorn.arbiter import Arbiter
  12. from gunicorn.config import Config, get_default_config_file
  13. from gunicorn import debug
  14. class BaseApplication(object):
  15. """
  16. An application interface for configuring and loading
  17. the various necessities for any given web framework.
  18. """
  19. def __init__(self, usage=None, prog=None):
  20. self.usage = usage
  21. self.cfg = None
  22. self.callable = None
  23. self.prog = prog
  24. self.logger = None
  25. self.do_load_config()
  26. def do_load_config(self):
  27. """
  28. Loads the configuration
  29. """
  30. try:
  31. self.load_default_config()
  32. self.load_config()
  33. except Exception as e:
  34. print("\nError: %s" % str(e), file=sys.stderr)
  35. sys.stderr.flush()
  36. sys.exit(1)
  37. def load_default_config(self):
  38. # init configuration
  39. self.cfg = Config(self.usage, prog=self.prog)
  40. def init(self, parser, opts, args):
  41. raise NotImplementedError
  42. def load(self):
  43. raise NotImplementedError
  44. def load_config(self):
  45. """
  46. This method is used to load the configuration from one or several input(s).
  47. Custom Command line, configuration file.
  48. You have to override this method in your class.
  49. """
  50. raise NotImplementedError
  51. def reload(self):
  52. self.do_load_config()
  53. if self.cfg.spew:
  54. debug.spew()
  55. def wsgi(self):
  56. if self.callable is None:
  57. self.callable = self.load()
  58. return self.callable
  59. def run(self):
  60. try:
  61. Arbiter(self).run()
  62. except RuntimeError as e:
  63. print("\nError: %s\n" % e, file=sys.stderr)
  64. sys.stderr.flush()
  65. sys.exit(1)
  66. class Application(BaseApplication):
  67. def get_config_from_filename(self, filename):
  68. if not os.path.exists(filename):
  69. raise RuntimeError("%r doesn't exist" % filename)
  70. cfg = {
  71. "__builtins__": __builtins__,
  72. "__name__": "__config__",
  73. "__file__": filename,
  74. "__doc__": None,
  75. "__package__": None
  76. }
  77. try:
  78. execfile_(filename, cfg, cfg)
  79. except Exception:
  80. print("Failed to read config file: %s" % filename, file=sys.stderr)
  81. traceback.print_exc()
  82. sys.stderr.flush()
  83. sys.exit(1)
  84. return cfg
  85. def get_config_from_module_name(self, module_name):
  86. return util.import_module(module_name).__dict__
  87. def load_config_from_module_name_or_filename(self, location):
  88. """
  89. Loads the configuration file: the file is a python file, otherwise raise an RuntimeError
  90. Exception or stop the process if the configuration file contains a syntax error.
  91. """
  92. if location.startswith("python:"):
  93. module_name = location[len("python:"):]
  94. cfg = self.get_config_from_module_name(module_name)
  95. else:
  96. if location.startswith("file:"):
  97. filename = location[len("file:"):]
  98. else:
  99. filename = location
  100. cfg = self.get_config_from_filename(filename)
  101. for k, v in cfg.items():
  102. # Ignore unknown names
  103. if k not in self.cfg.settings:
  104. continue
  105. try:
  106. self.cfg.set(k.lower(), v)
  107. except:
  108. print("Invalid value for %s: %s\n" % (k, v), file=sys.stderr)
  109. sys.stderr.flush()
  110. raise
  111. return cfg
  112. def load_config_from_file(self, filename):
  113. return self.load_config_from_module_name_or_filename(location=filename)
  114. def load_config(self):
  115. # parse console args
  116. parser = self.cfg.parser()
  117. args = parser.parse_args()
  118. # optional settings from apps
  119. cfg = self.init(parser, args, args.args)
  120. # Load up the any app specific configuration
  121. if cfg and cfg is not None:
  122. for k, v in cfg.items():
  123. self.cfg.set(k.lower(), v)
  124. if args.config:
  125. self.load_config_from_file(args.config)
  126. else:
  127. default_config = get_default_config_file()
  128. if default_config is not None:
  129. self.load_config_from_file(default_config)
  130. # Lastly, update the configuration with any command line
  131. # settings.
  132. for k, v in args.__dict__.items():
  133. if v is None:
  134. continue
  135. if k == "args":
  136. continue
  137. self.cfg.set(k.lower(), v)
  138. def run(self):
  139. if self.cfg.check_config:
  140. try:
  141. self.load()
  142. except:
  143. msg = "\nError while loading the application:\n"
  144. print(msg, file=sys.stderr)
  145. traceback.print_exc()
  146. sys.stderr.flush()
  147. sys.exit(1)
  148. sys.exit(0)
  149. if self.cfg.spew:
  150. debug.spew()
  151. if self.cfg.daemon:
  152. util.daemonize(self.cfg.enable_stdio_inheritance)
  153. # set python paths
  154. if self.cfg.pythonpath and self.cfg.pythonpath is not None:
  155. paths = self.cfg.pythonpath.split(",")
  156. for path in paths:
  157. pythonpath = os.path.abspath(path)
  158. if pythonpath not in sys.path:
  159. sys.path.insert(0, pythonpath)
  160. super(Application, self).run()