<commit_before>__author__ = 'ievans3024'

#import flask_whooshalchemy as whooshalchemy
import json
from collection_json import Collection, Link
from flask import Flask, render_template, request, abort, Response


# TODO: Learn how to use global object (g)
COLLECTION_JSON = 'application/vnd.collection+json'

app = Flask(__name__)

app.config.from_pyfile('config.py', silent=True)

# this import needs db to exist first
if (not app.config.get('DATABASE_HANDLER')) or (app.config.get('DATABASE_HANDLER') == 'flatfile'):
    from blackbook.database.flatdatabase import FlatDatabase
    db = FlatDatabase(app)
elif app.config.get('DATABASE_HANDLER') in ('sqlite', 'mysql', 'postgresql'):
    from blackbook.database.sqlalchemy import SQLAlchemyDatabase
    db = SQLAlchemyDatabase(app)


def request_accepts(*mimetypes):
    best = request.accept_mimetypes.best_match(mimetypes)
    return request.accept_mimetypes[best] and request.accept_mimetypes[best] >= request.accept_mimetypes['text/html']


@app.route('/')
@app.route('/book/')
def home():
    """Home Page, displays references to all entries"""
    return render_template('base.html')


@app.route('/api/')
def api():
    if not request_accepts(COLLECTION_JSON):
        abort(406)
    response = Collection('/api/')
    response.links.append(Link('/api/entry/', 'index', prompt='List all entries or add an entry'))
    return Response(json.dumps(response.to_dict()), mimetype=COLLECTION_JSON)


@app.route('/api/doc/')
def api_doc():
    return render_template('api.html')


@app.route('/api/entry/', methods=['GET', 'POST'])
def api_entries():
    if not request_accepts(COLLECTION_JSON):
        abort(406)
    if request.method == 'GET':
        # return paginated contact info
        response = db.read(
            page=request.args.get('page') or 1,
            per_page=request.args.get('per_page') or 5
        )
        return Response(json.dumps(response.to_dict()), mimetype=COLLECTION_JSON)
    else:
        if request.mimetype != COLLECTION_JSON:
            abort(415)
        # TODO: Form validation
        created_entry = db.create(json.loads(request.data))
        return Response(json.dumps(created_entry.to_dict()), mimetype=COLLECTION_JSON), 201


@app.route('/api/entry/<int:person_id>/', methods=['GET', 'DELETE', 'PATCH'])
def api_entry(person_id=None):
    if isinstance(person_id, int):<commit_msg>* fixed a problem with response encoding + added try/except block to catch errors and throw 400<commit_after>__author__ = 'ievans3024'

#import flask_whooshalchemy as whooshalchemy
import json
from collection_json import Collection, Link
from flask import Flask, render_template, request, abort, Response


# TODO: Learn how to use global object (g)
COLLECTION_JSON = 'application/vnd.collection+json'

app = Flask(__name__)

app.config.from_pyfile('config.py', silent=True)

# this import needs db to exist first
if (not app.config.get('DATABASE_HANDLER')) or (app.config.get('DATABASE_HANDLER') == 'flatfile'):
    from blackbook.database.flatdatabase import FlatDatabase
    db = FlatDatabase(app)
elif app.config.get('DATABASE_HANDLER') in ('sqlite', 'mysql', 'postgresql'):
    from blackbook.database.sqlalchemy import SQLAlchemyDatabase
    db = SQLAlchemyDatabase(app)


def request_accepts(*mimetypes):
    best = request.accept_mimetypes.best_match(mimetypes)
    return request.accept_mimetypes[best] and request.accept_mimetypes[best] >= request.accept_mimetypes['text/html']


@app.route('/')
@app.route('/book/')
def home():
    """Home Page, displays references to all entries"""
    return render_template('base.html')


@app.route('/api/')
def api():
    if not request_accepts(COLLECTION_JSON):
        abort(406)
    response = Collection('/api/')
    response.links.append(Link('/api/entry/', 'index', prompt='List all entries or add an entry'))
    return Response(json.dumps(response.to_dict()), mimetype=COLLECTION_JSON)


@app.route('/api/doc/')
def api_doc():
    return render_template('api.html')


@app.route('/api/entry/', methods=['GET', 'POST'])
def api_entries():
    if not request_accepts(COLLECTION_JSON):
        abort(406)
    if request.method == 'GET':
        # return paginated contact info
        response = db.read(
            page=request.args.get('page') or 1,
            per_page=request.args.get('per_page') or 5
        )
        return Response(json.dumps(response.to_dict()), mimetype=COLLECTION_JSON)
    else:
        if request.mimetype != COLLECTION_JSON:
            abort(415)
        # TODO: Form validation
        try:
            created_entry = db.create(json.loads(request.data.decode()))
        except (TypeError, ValueError) as e:
            # TODO: Create custom error classes in database code, raise those instead.
            print(e)
            abort(400)
        return Response(json.dumps(created_entry.to_dict()), mimetype=COLLECTION_JSON), 201


@app.route('/api/entry/<int:person_id>/', methods=['GET', 'DELETE', 'PATCH'])
def api_entry(person_id=None):
    if isinstance(person_id, int):
{'fraction_non_alphanumeric': 0.13326732673267327, 'fraction_numerical': 0.008316831683168317, 'mean_word_length': 4.071285140562249, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 7, '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': '313957', 'n_tokens_mistral': 1639, 'n_tokens_neox': 1589, 'n_words': 361}