PYTHON   28

app.py

Guest on 3rd June 2021 05:55:47 AM

  1. '''
  2. Main entrypoint file.  To run:
  3.  
  4.  $ python serve.py
  5.  
  6. '''
  7. from flask import Flask
  8. from flask import request
  9. from flask import render_template
  10. from flask import json
  11. from flask import send_from_directory
  12. import importlib
  13. import traceback
  14. import sys
  15. import os
  16.  
  17. #if __name__ == "__main__":
  18. # Add current directory to sys.path
  19. site_dir = os.path.dirname(os.path.abspath(__file__))
  20.          
  21. if site_dir not in sys.path:
  22.     sys.path.append(site_dir)
  23.      
  24. # Set default FLASK_SETTINGS_MODULE for debug mode
  25. if not os.environ.get('FLASK_SETTINGS_MODULE', ''):
  26.     os.environ['FLASK_SETTINGS_MODULE'] = 'core.settings.loc'
  27.  
  28. # Import settings module for the inject_static_url context processor.
  29. settings_module = os.environ.get('FLASK_SETTINGS_MODULE')
  30.  
  31. try:
  32.     importlib.import_module(settings_module)
  33. except ImportError, e:
  34.     raise ImportError(
  35.         "Could not import settings '%s' (Is it on sys.path?): %s" \
  36.         % (settings_module, e))
  37.  
  38. settings = sys.modules[settings_module]
  39.  
  40.  
  41. app = Flask(__name__)
  42.  
  43. build_dir = os.path.join(settings.PROJECT_ROOT, 'build')
  44. source_dir = os.path.join(settings.PROJECT_ROOT, 'source')
  45.  
  46. @app.context_processor
  47. def inject_static_url():
  48.     """
  49.    Inject the variables 'static_url' and 'STATIC_URL' into the templates to
  50.    avoid hard-coded paths to static files. Grab it from the environment
  51.    variable STATIC_URL, or use the default. Never has a trailing slash.
  52.    """
  53.     static_url = settings.STATIC_URL or app.static_url_path
  54.     if static_url.endswith('/'):
  55.         static_url = static_url.rstrip('/')
  56.     return dict(static_url=static_url, STATIC_URL=static_url)
  57.  
  58.  
  59. @app.route('/build/<path:path>')
  60. def catch_build(path):
  61.     """
  62.    Serve /build/... urls from the build directory
  63.    """
  64.     return send_from_directory(build_dir, path)    
  65.  
  66. @app.route('/source/<path:path>')
  67. def catch_source(path):
  68.     """
  69.    Serve /source/... urls from the source directory
  70.    """
  71.     return send_from_directory(source_dir, path)    
  72.  
  73.    
  74.    
  75. @app.route('/')
  76. @app.route('/<path:path>')
  77. def catch_all(path='index.html'):
  78.     """Catch-all function which serves every URL."""
  79.      
  80.     if not os.path.splitext(path)[1]:
  81.         path = os.path.join(path, 'index.html')
  82.     return render_template(path)
  83.    
  84.        
  85. if __name__ == "__main__":
  86.     app.run(host='0.0.0.0', port=5000, debug=True)

Raw Paste


Login or Register to edit or fork this paste. It's free.