<commit_before>import contextlib
import json
import logging
import os

from flask import Flask, request, render_template
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.sslify import SSLify
from flask.ext.wtf import Form
import sendgrid
import sys
from wtforms import StringField
from wtforms.fields.html5 import EmailField
from wtforms.validators import DataRequired, EqualTo

from bluemix_promocodes import defaults


def import_cloudfoundry_config(config):
    if 'VCAP_SERVICES' in os.environ:
        services = json.loads(os.getenv('VCAP_SERVICES'))
        for service in services['sqldb']:
            if service['name'] == config['SQLDB_SERVICE']:
                uri = "db2+ibm_db://{username}:{password}@{host}:{port}/{db}"
                config['SQLALCHEMY_DATABASE_URI'] = uri.format(**service['credentials'])
        for service in services['sendgrid']:
            if service['name'] == config['SENDGRID_SERVICE']:
                config['SENDGRID_USERNAME'] = service['credentials']['username']
                config['SENDGRID_PASSWORD'] = service['credentials']['password']


app = Flask(__name__)
handler = logging.StreamHandler(stream=sys.stderr)
handler.setLevel(logging.WARNING)
app.logger.addHandler(handler)
app.config.from_object(defaults)
try:
    from bluemix_promocodes import config
except ImportError:
    config = None
else:
    app.config.from_object(config)


import_cloudfoundry_config(app.config)
db = SQLAlchemy(app)
sslify = SSLify(app, permanent=True)


class User(db.Model):
    id = db.Column(db.Integer(), primary_key=True, nullable=False)
    email = db.Column(db.String(255), unique=True, nullable=False)
    first_name = db.Column(db.String(255), nullable=False)
    last_name = db.Column(db.String(255), nullable=False)
    ip = db.Column(db.String(39), nullable=False)
    created_at = db.Column(db.DateTime(), nullable=False, default=db.func.now())


class Code(db.Model):
    id = db.Column(db.Integer(), primary_key=True, nullable=False)
    value = db.Column(db.String(64), unique=True, nullable=False)
    user_id = db.Column(db.Integer(), db.ForeignKey(User.id), unique=True, nullable=True)
    user = db.relationship(User, backref=db.backref('code', uselist=False))


def get_sendgrid_client():
    client = sendgrid.SendGridClient(app.config['SENDGRID_USERNAME'], app.config['SENDGRID_PASSWORD'],<commit_msg>Read SENDGRID_API_KEY in addition to username<commit_after>import contextlib
import json
import logging
import os

from flask import Flask, request, render_template
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.sslify import SSLify
from flask.ext.wtf import Form
import sendgrid
import sys
from wtforms import StringField
from wtforms.fields.html5 import EmailField
from wtforms.validators import DataRequired, EqualTo

from bluemix_promocodes import defaults


def import_cloudfoundry_config(config):
    if 'VCAP_SERVICES' in os.environ:
        services = json.loads(os.getenv('VCAP_SERVICES'))
        for service in services['sqldb']:
            if service['name'] == config['SQLDB_SERVICE']:
                uri = "db2+ibm_db://{username}:{password}@{host}:{port}/{db}"
                config['SQLALCHEMY_DATABASE_URI'] = uri.format(**service['credentials'])
        for service in services['sendgrid']:
            if service['name'] == config['SENDGRID_SERVICE']:
                config['SENDGRID_USERNAME'] = service['credentials']['username']
                config['SENDGRID_PASSWORD'] = service['credentials']['password']


app = Flask(__name__)
handler = logging.StreamHandler(stream=sys.stderr)
handler.setLevel(logging.WARNING)
app.logger.addHandler(handler)
app.config.from_object(defaults)
try:
    from bluemix_promocodes import config
except ImportError:
    config = None
else:
    app.config.from_object(config)


import_cloudfoundry_config(app.config)
db = SQLAlchemy(app)
sslify = SSLify(app, permanent=True)


class User(db.Model):
    id = db.Column(db.Integer(), primary_key=True, nullable=False)
    email = db.Column(db.String(255), unique=True, nullable=False)
    first_name = db.Column(db.String(255), nullable=False)
    last_name = db.Column(db.String(255), nullable=False)
    ip = db.Column(db.String(39), nullable=False)
    created_at = db.Column(db.DateTime(), nullable=False, default=db.func.now())


class Code(db.Model):
    id = db.Column(db.Integer(), primary_key=True, nullable=False)
    value = db.Column(db.String(64), unique=True, nullable=False)
    user_id = db.Column(db.Integer(), db.ForeignKey(User.id), unique=True, nullable=True)
    user = db.relationship(User, backref=db.backref('code', uselist=False))


def get_sendgrid_client():
    if 'SENDGRID_API_KEY' in app.config:
        username = app.config['SENDGRID_API_KEY']
        password = None
    else:
        username = app.config['SENDGRID_USERNAME']
        password = app.config['SENDGRID_PASSWORD']
    client = sendgrid.SendGridClient(username, password,
{'fraction_non_alphanumeric': 0.12578109252166902, 'fraction_numerical': 0.006047167909695626, 'mean_word_length': 4.581552305961755, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '99382', 'n_tokens_mistral': 1633, 'n_tokens_neox': 1570, 'n_words': 313}