File size: 15,225 Bytes
5980447
1
2
{"repo": "radremedy/radremedy", "pull_number": 125, "instance_id": "radremedy__radremedy-125", "issue_numbers": "", "base_commit": "5e153bae3b2658fa2e6e193cd4b87c50c4405710", "patch": "diff --git a/remedy/admin.py b/remedy/admin.py\n--- a/remedy/admin.py\n+++ b/remedy/admin.py\n@@ -24,6 +24,8 @@ class ResourceView(ModelView):\n         'email', 'phone', 'url', \n         'source', 'last_updated')\n \n+    column_default_sort = 'name'\n+\n     column_searchable_list = ('name',)\n \n     form_excluded_columns = ('date_created', 'last_updated', \n@@ -43,6 +45,8 @@ class UserView(ModelView):\n     column_list = ('username', 'email', \n         'admin', 'active', 'date_created')\n \n+    column_default_sort = 'username'\n+\n     column_searchable_list = ('username', 'email',)\n \n     form_excluded_columns = ('password', 'date_created', 'reviews',\n@@ -136,6 +140,8 @@ class CategoryView(ModelView):\n     column_list = ('name', 'description', \n         'visible', 'date_created')\n \n+    column_default_sort = 'name'\n+\n     column_searchable_list = ('name', 'description',)\n \n     form_excluded_columns = ('resources', 'date_created')\n@@ -150,6 +156,8 @@ class ReviewView(ModelView):\n     \"\"\"\n     column_select_related_list = (Review.resource, Review.user)\n \n+    column_default_sort = 'date_created'\n+\n     column_list = ('rating', 'resource.name', 'user.username', 'visible', 'date_created')\n     column_labels = {\n         'rating': 'Rating', \ndiff --git a/remedy/bootstrap.py b/remedy/bootstrap.py\n--- a/remedy/bootstrap.py\n+++ b/remedy/bootstrap.py\n@@ -7,9 +7,9 @@\n from rad.models import Category\n from radremedy import db\n from get_save_data import run as run_scrapers\n-from data_importer.data_importer import seconds, open_dict_csv, open_csv, minus_key, data_dir\n+from data_importer.data_importer import seconds, open_dict_csv, open_csv, minus_key, rename_key, data_dir\n from radrecord import rad_record\n-\n+import sys\n \n def strap(application):\n     \"\"\"\n@@ -19,23 +19,29 @@ def strap(application):\n \n     with application.app_context():\n \n-        # create all the different categories for the providers\n-        # we do this separately for clarity but we don't have to\n-        # they would automatically be created when importing\n-        # the rest of the data\n-        categories = seconds(open_csv(data_dir('rad_resource.csv')))\n-\n-        # we commit on every record because they have to be unique\n-        map(lambda c: add_get_or_create(db, Category, name=c) and db.session.commit(),\n-            categories)\n-\n-        # load all the resources' data, but we drop the id\n-        # column because our database will assign them on its own\n-        raw_resources = map(lambda row: minus_key(row, 'id'),\n+        # Try a sample join to make sure that our\n+        # data_dir is good and add a helpful error message\n+        # when it's not.\n+        try:\n+            data_dir('rad_resource.csv')\n+        except:\n+            sys.exit('The source data directory is missing or invalid. ' \\\n+                'This is typically due to a missing RAD_DATA_BASE environment variable.')\n+\n+        # Load all the resources' data, but we drop the id\n+        # column because our database will assign them on its own.\n+        # We also want to attempt to rename the \"category\" row, if provided,\n+        # to \"category_name\", as that's consistent with the RadRecord format.\n+        raw_resources = map(lambda row: rename_key(minus_key(row, 'id'), \n+                                'category', 'category_name'),\n                             open_dict_csv(data_dir('rad_resource.csv')))\n \n-        # then we save every record\n-        map(lambda row: get_or_create_resource(db, rad_record(**row)),\n+        # Now save every record. To support multiple delimited\n+        # categories in the category_name field, we invoke\n+        # convert_category_name() on the raw rad_record\n+        # generated from the data row.\n+        map(lambda row: get_or_create_resource(db, \n+            rad_record(**row).convert_category_name()),\n             raw_resources)\n \n         db.session.commit()\ndiff --git a/remedy/data_importer/data_importer.py b/remedy/data_importer/data_importer.py\n--- a/remedy/data_importer/data_importer.py\n+++ b/remedy/data_importer/data_importer.py\n@@ -5,7 +5,7 @@\n \"\"\"\n \n from toolz import unique, partial\n-import csv\n+import unicodecsv\n import os\n \n # force python lazy functions to act\n@@ -14,9 +14,17 @@\n \n def open_csv(file_path, skip_head=True):\n     \"\"\"\n-    TODO: write this docstring \n+    Opens a CSV file and returns a reader.\n+\n+    Args:\n+        file_path: The path to the CSV file.\n+        skip_head: Indicates if the first row in the file\n+            should be skipped, such as when it has a header.\n+    \n+    Returns:\n+        A reader for the CSV file.\n     \"\"\"\n-    f = csv.reader(open(file_path, 'r'))\n+    f = unicodecsv.reader(open(file_path, 'r'))\n \n     if skip_head:\n         next(f)\n@@ -26,19 +34,50 @@ def open_csv(file_path, skip_head=True):\n \n def open_dict_csv(file_path):\n     \"\"\"\n-    TODO: write this docstring \n+    Opens a CSV file and returns a dictionary reader.\n+\n+    Args:\n+        file_path: The path to the CSV file.\n+\n+    Returns:\n+        A dictionary reader for the CSV file.\n     \"\"\"\n-    return csv.DictReader(open(file_path, 'r'))\n+    return unicodecsv.DictReader(open(file_path, 'r'))\n \n \n def minus_key(d, k):\n     \"\"\"\n-    TODO: write this docstring\n+    Removes a key/value pair from a dictionary.\n+\n+    Args:\n+        d: The dictionary to update.\n+        k: The key of the value to remove.\n+\n+    Returns:\n+        The updated dictionary.\n     \"\"\"\n     d.pop(k)\n     return d\n \n \n+def rename_key(d, oldkey, newkey):\n+    \"\"\"\n+    Renames a key/value pair in a dictionary.\n+\n+    Args:\n+        d: The dictionary to update.\n+        oldkey: The old key to rename.\n+        newkey: The new name of the key.\n+\n+    Returns:\n+        The updated dictionary.\n+    \"\"\"\n+    if oldkey in d:\n+        value = d.pop(oldkey)\n+        d[newkey] = value\n+\n+    return d\n+\n def unique_from_column(n, columns):\n     \"\"\"\n     TODO: write this docstring \ndiff --git a/remedy/rad/db_fun.py b/remedy/rad/db_fun.py\n--- a/remedy/rad/db_fun.py\n+++ b/remedy/rad/db_fun.py\n@@ -9,6 +9,21 @@\n \n \n def get_or_create(session, model, **kwargs):\n+    \"\"\"\n+    Determines if a given record already exists in the database.\n+\n+    Args:\n+        session: The database session.\n+        model: The model for the record.\n+        **kwargs: The properties to set on the model. The first\n+            specified property will be used to determine if\n+            the model already exists.\n+\n+    Returns:\n+        Two values. The first value is a boolean\n+        indicating if this item is a new record. The second\n+        value will be the created/retrieved model.\n+    \"\"\"\n     instance = session.query(model).filter_by(**kwargs).first()\n     if instance:\n         return False, instance\n@@ -18,20 +33,46 @@ def get_or_create(session, model, **kwargs):\n \n \n def add_get_or_create(database, model, **kwargs):\n+    \"\"\"\n+    Gets or creates an record based on if it already exists.\n+    If it does not already exist, it will be created.\n+\n+    Args:\n+        session: The database session.\n+        model: The model to get or create.\n+        **kwargs: The properties to set on the model. The first\n+            specified property will be used to determine if\n+            the model already exists.\n+\n+    Returns:\n+        Two values. The first value is a boolean\n+        indicating if this item is a new record. The second\n+        value will be the created/retrieved model.\n+    \"\"\"\n     new_record, record = get_or_create(database.session, model, **kwargs)\n-    database.session.add(record)\n+\n+    if new_record:\n+        database.session.add(record)\n \n     return new_record, record\n \n \n def get_or_create_resource(database, rad_record, lazy=True):\n     \"\"\"\n-    Checks to see if a record already exists in the database. If not, the new record is added. \n+    Checks to see if a resource already exists in the database\n+    and adds it if it does not exist (or is forced to by use of\n+    the lazy argument).\n \n     Args: \n-        database: copy of the database in the current contect \n-        rad_record: the record to be added. Must be in the RAD record format\n-        lazy: if false, forces record to be added, even if it is a duplicate. Defaults to true\n+        database: The current database context. \n+        rad_record: The RadRecord to be added.\n+        lazy: If false, forces the record to be added even if it is a duplicate. \n+            Defaults to true.\n+\n+    Returns:\n+        Two values. The first value is a boolean\n+        indicating if a new record was created. The second\n+        value will be the created/updated model.\n     \"\"\"\n \n     new_record, record = get_or_create(database.session, Resource, name=rad_record.name.strip())\n@@ -98,5 +139,11 @@ def get_or_create_resource(database, rad_record, lazy=True):\n \n         database.session.add(record)\n \n+        # Flush the session because otherwise we won't pick up\n+        # duplicates with UNIQUE constraints (such as in category names) \n+        # until we get an error trying to commit such duplicates\n+        # (which is bad)\n+        database.session.flush()\n+\n     return new_record, record\n \ndiff --git a/remedy/rad/resourceservice.py b/remedy/rad/resourceservice.py\n--- a/remedy/rad/resourceservice.py\n+++ b/remedy/rad/resourceservice.py\n@@ -8,7 +8,7 @@\n \"\"\"\n \n from sqlalchemy import *\n-from models import Resource\n+from models import Resource, Category, resourcecategory\n import geoutils\n \n def search(database, search_params=None, limit=0, order_by='last_updated desc'):\n@@ -33,8 +33,6 @@ def search(database, search_params=None, limit=0, order_by='last_updated desc'):\n     # Set up our\n     query = database.session.query(Resource)\n \n-    # TODO: Add in category/tag stuff once that's all properly sorted\n-\n     # Make sure we have some searching parameters!\n     if search_params is not None and len(search_params) > 0:\n \n@@ -53,6 +51,11 @@ def search(database, search_params=None, limit=0, order_by='last_updated desc'):\n                 Resource.organization.like(search_like_str),\n                 Resource.category_text.like(search_like_str)))\n \n+        # Category filtering - ensure at least one has been provided\n+        if 'categories' in search_params and len(search_params['categories']) > 0:\n+            query = query.filter(Resource.categories.any(\n+                Category.id.in_(search_params['categories'])))\n+\n         # Location parameters (\"lat\", \"long\", \"dist\") - proximity filtering\n         if 'dist' in search_params and \\\n             search_params['dist'] > 0 and \\\ndiff --git a/remedy/rad/searchutils.py b/remedy/rad/searchutils.py\n--- a/remedy/rad/searchutils.py\n+++ b/remedy/rad/searchutils.py\n@@ -52,6 +52,44 @@ def add_int(search_params, key, value, min_value=None, max_value=None):\n     except ValueError:\n         return\n \n+def add_int_set(search_params, key, value_list, min_value=None, max_value=None):\n+    \"\"\"\n+    Adds a set of integer values to the provided search parameters\n+    dictionary if any can be converted.\n+\n+    Args:\n+        search_params: The parameter dictionary to update.\n+        key: The key to use.\n+        value_list: The list of values to normalize and use in the dictionary as appropriate.\n+        min_value: The minimum value to validate against, if any.\n+        max_value: The maximum value to validate against, if any.\n+    \"\"\"\n+    if value_list is None:\n+        return\n+\n+    # Initialize an empty set\n+    int_set = set()\n+\n+    # Now iterate over the list of values and validate each in turn\n+    for int_str in value_list:\n+        try:\n+            value_int = int(int_str)\n+\n+            # Validation against ranges, if specified\n+            if min_value is not None and value_int < min_value:\n+                continue\n+\n+            if max_value is not None and value_int > max_value:\n+                continue\n+\n+            int_set.add(value_int)\n+        except ValueError:\n+            pass\n+\n+    # If we had any valid values, set the search params key\n+    if len(int_set) > 0:\n+        search_params[key] = int_set\n+\n def add_float(search_params, key, value, min_value=None, max_value=None):\n     \"\"\"\n     Adds a floating-point value to the provided search parameters\ndiff --git a/remedy/remedyblueprint.py b/remedy/remedyblueprint.py\n--- a/remedy/remedyblueprint.py\n+++ b/remedy/remedyblueprint.py\n@@ -7,7 +7,7 @@\n \n from flask import Blueprint, render_template, redirect, url_for, request, abort, flash\n from flask.ext.login import login_required, current_user\n-from rad.models import Resource, Review, db\n+from rad.models import Resource, Review, Category, db\n from pagination import Pagination\n import rad.resourceservice\n import rad.searchutils\n@@ -97,6 +97,16 @@ def latest_reviews(n):\n     return Review.query.order_by(Review.date_created.desc()).limit(n).all()\n \n \n+def active_categories():\n+    \"\"\"\n+    Returns all active categories in the database.\n+\n+    Returns:\n+        A list of categories from the database.\n+    \"\"\"\n+    return Category.query.filter(Category.visible == True).order_by(Category.name).all()\n+\n+\n def resource_with_id(id):\n     \"\"\"\n     Returns a resource from the database or aborts with a\n@@ -128,7 +138,8 @@ def decorated_function(*args, **kwargs):\n def index():\n     return render_template('index.html', \n         recently_added=latest_added(3),\n-        recent_discussion=latest_reviews(20))\n+        recent_discussion=latest_reviews(20),\n+        categories=active_categories())\n \n \n @remedy.route('/resource/')\n@@ -210,9 +221,15 @@ def resource_search(page):\n         search_params.pop('lat', None)\n         search_params.pop('long', None)\n \n+    # Categories - this is a MultiDict so we need to use GetList\n+    rad.searchutils.add_int_set(search_params, 'categories', request.args.getlist('categories'))\n+\n     # All right - time to search!\n     providers = rad.resourceservice.search(db, search_params=search_params)\n \n+    # Load up available categories\n+    categories = active_categories()\n+\n     # Set up our pagination and render out the template.\n     count, paged_providers = get_paged_data(providers, page)\n     pagination = Pagination(page, PER_PAGE, count)\n@@ -220,7 +237,8 @@ def resource_search(page):\n     return render_template('find-provider.html',\n         pagination=pagination,\n         providers=paged_providers,\n-        search_params=search_params\n+        search_params=search_params,\n+        categories=categories\n     )\n \n \n", "test_patch": "", "problem_statement": "", "hints_text": "", "created_at": "2014-10-06T04:20:40Z"}