Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also compare across forks.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also compare across forks.
base fork: hdemers/webapp-template
base: f8ab5c1034
...
head fork: hdemers/webapp-template
compare: fea34ad734
  • 2 commits
  • 6 files changed
  • 0 commit comments
  • 1 contributor
View
9 requirements.txt
@@ -1,3 +1,6 @@
-flask
-flask-debugtoolbar
-requests
+fabric==1.5.3
+flask==0.9
+requests==1.1.0
+git+https://github.com/ooda/cloudly.git@v1.1.1#egg=cloudly==1.1.1
+gunicorn==0.17.2
+newrelic==1.10.0.28
View
58 webapp/__init__.py
@@ -1,7 +1,23 @@
-import logging
+"""
+This module instantiates the Flask application and declares the main error
+handling function ``make_json_error``.
+"""
-from flask import Flask
-#from flask_debugtoolbar import DebugToolbarExtension
+__title__ = "Webapp template"
+__version__ = "0.1.0"
+__author__ = "Hugues Demers"
+__copyright__ = "Copyright 2013 Hugues Demers"
+
+import os
+import traceback
+
+from flask import Flask, jsonify, request
+from werkzeug.exceptions import default_exceptions
+from werkzeug.exceptions import HTTPException
+
+from cloudly import logger
+from cloudly.notify import notify
+from webapp.metric import evt
FORMAT = "%(asctime)s] %(levelname)s %(module)s %(funcName)s: %(message)s"
@@ -11,18 +27,32 @@
# Debugging
app.debug = True
app.debug_log_format = FORMAT
-logger = app.logger
-
-# Console handler
-formatter = logging.Formatter(FORMAT)
-console_handler = logging.StreamHandler()
-console_handler.setFormatter(formatter)
-logger.addHandler(console_handler)
+log = logger.init(__name__)
# Set a 'SECRET_KEY' to enable the Flask session cookies
-app.config['SECRET_KEY'] = 'oftg09jW2FtbXfcud9OS'
-
-# Flask debug toolbar
-#toolbar = DebugToolbarExtension(app)
+app.config['SECRET_KEY'] = os.environ.get("WEBAPP_SESSION_SECRET_KEY",
+ 'oftg09jW2FtbXfcud9OS')
+
+
+# Make this app a JSON app.
+# Inspired from cf. http://flask.pocoo.org/snippets/83/
+def make_json_error(ex):
+ log.error(ex)
+ log.error(traceback.format_exc())
+ message = ex.description if isinstance(ex, HTTPException) else str(ex)
+ message = message.replace("<p>", "").replace("</p>", "") if message else ""
+ code = ex.code if isinstance(ex, HTTPException) else 500
+ response = jsonify(message=message, status_code=code)
+ response.status_code = code
+
+ if code in [500]:
+ notify("Webapp exception: {}".format(code),
+ "{}\n\n{}".format(ex, traceback.format_exc(ex)))
+
+ evt("error", {'code': code}, request=request)
+ return response
+
+for code in default_exceptions.iterkeys():
+ app.error_handler_spec[None][code] = make_json_error
import webapp.views
View
12 webapp/config.py
@@ -1,12 +0,0 @@
-import os
-import logging
-
-logfile = "webapp.log"
-
-log_levels = {
- "DEBUG": logging.DEBUG,
- "INFO": logging.INFO,
- "WARNING": logging.WARNING,
-}
-log_level_str = os.environ.get("WEBAPP_LOG_LEVEL", "DEBUG")
-log_level = log_levels.get(log_level_str, logging.WARNING)
View
26 webapp/logger.py
@@ -1,26 +0,0 @@
-import logging
-
-import webapp.config as config
-
-FORMAT = "%(asctime)s] %(levelname)s %(module)s %(funcName)s: %(message)s"
-
-
-def init(name, log_level=config.log_level):
- # Create logger and formatter
- logger = logging.getLogger(name)
- logger.setLevel(log_level)
- formatter = logging.Formatter(FORMAT)
-
- # Console handler
- console_handler = logging.StreamHandler()
- console_handler.setLevel(log_level)
- console_handler.setFormatter(formatter)
- logger.addHandler(console_handler)
-
- # File handler
- file_handler = logging.FileHandler(config.logfile)
- file_handler.setLevel(log_level)
- file_handler.setFormatter(formatter)
- logger.addHandler(file_handler)
-
- return logger
View
22 webapp/metric.py
@@ -0,0 +1,22 @@
+"""
+Log metrics to a [Cube](http://square.github.com/cube/) server.
+
+"""
+import os
+from cloudly.metric import event
+
+LOG_METRICS = os.environ.get("LOG_METRICS", False)
+
+
+def evt(evt_type, data=None, request=None):
+ if not LOG_METRICS:
+ return
+
+ if request:
+ if not data:
+ data = {}
+ data['path'] = request.path
+ data['root'] = request.url_root
+ data['method'] = request.method
+ event(evt_type, data)
+
View
21 webapp/views.py
@@ -1,6 +1,21 @@
-from webapp import app
+"""
+URL routes declarations.
+
+"""
+import os
+
+from webapp import app, make_json_error
from flask import render_template, jsonify
+from cloudly import logger
+
+log = logger.init(__name__)
+
+
+@app.errorhandler(Exception)
+def error_handler(error):
+ return make_json_error(error)
+
@app.route('/')
def index():
@@ -27,3 +42,7 @@ def make_serie(name, serie_id, data):
'id': serie_id,
'data': data
}
+
+
+def in_production():
+ return os.environ.get("IS_PRODUCTION", "").lower() in ['true', 'yes']

No commit comments for this range

Something went wrong with that request. Please try again.