Skip to content

Commit

Permalink
Created @filtered decorator
Browse files Browse the repository at this point in the history
  • Loading branch information
vrcmarcos committed Aug 17, 2016
0 parents commit 5dc13df
Show file tree
Hide file tree
Showing 12 changed files with 504 additions and 0 deletions.
246 changes: 246 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,246 @@

# Created by https://www.gitignore.io/api/intellij,linux,osx,pycharm,python

### Intellij ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839

# User-specific stuff:
.idea/
.idea/workspace.xml
.idea/tasks.xml
.idea/dictionaries
.idea/vcs.xml
.idea/jsLibraryMappings.xml

# Sensitive or high-churn files:
.idea/dataSources.ids
.idea/dataSources.xml
.idea/dataSources.local.xml
.idea/sqlDataSources.xml
.idea/dynamic.xml
.idea/uiDesigner.xml

# Gradle:
.idea/gradle.xml
.idea/libraries

# Mongo Explorer plugin:
.idea/mongoSettings.xml

## File-based project format:
*.iws

## Plugin-specific files:

# IntelliJ
/out/

# mpeltonen/sbt-idea plugin
.idea_modules/

# JIRA plugin
atlassian-ide-plugin.xml

# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties

### Intellij Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721

# *.iml
# modules.xml
# .idea/misc.xml
# *.ipr


### Linux ###
*~

# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*

# KDE directory preferences
.directory

# Linux trash folder which might appear on any partition or disk
.Trash-*


### OSX ###
*.DS_Store
.AppleDouble
.LSOverride

# Icon must end with two \r
Icon


# Thumbnails
._*

# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent

# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk


### PyCharm ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839

# User-specific stuff:
.idea/workspace.xml
.idea/tasks.xml
.idea/dictionaries
.idea/vcs.xml
.idea/jsLibraryMappings.xml

# Sensitive or high-churn files:
.idea/dataSources.ids
.idea/dataSources.xml
.idea/dataSources.local.xml
.idea/sqlDataSources.xml
.idea/dynamic.xml
.idea/uiDesigner.xml

# Gradle:
.idea/gradle.xml
.idea/libraries

# Mongo Explorer plugin:
.idea/mongoSettings.xml

## File-based project format:
*.iws

## Plugin-specific files:

# IntelliJ
/out/

# mpeltonen/sbt-idea plugin
.idea_modules/

# JIRA plugin
atlassian-ide-plugin.xml

# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties

### PyCharm Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721

# *.iml
# modules.xml
# .idea/misc.xml
# *.ipr


### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover
.hypothesis/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# IPython Notebook
.ipynb_checkpoints

# pyenv
.python-version

# celery beat schedule file
celerybeat-schedule

# dotenv
.env

# virtualenv
venv/
ENV/

# Spyder project settings
.spyderproject

# Rope project settings
.ropeproject
11 changes: 11 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
language: python
python:
- "2.7"
install:
- pip install -r requirements.txt
- pip install -r requirements_test.txt
- pip install coveralls
script:
make test
after_success:
coveralls
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2016 Marcos Cardoso

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
11 changes: 11 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
install:
@pip install -r requirements.txt

test_install: install
@pip install -r requirements_test.txt

test: test_install
@py.test --cov-report term-missing --cov=flask_filtered_response

upload:
@python setup.py sdist upload
50 changes: 50 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Flask Filtered Response

Add filter capability to JSON responses

[![Build Status](https://travis-ci.org/vrcmarcos/flask-filtered-response.svg?branch=master)](https://travis-ci.org/vrcmarcos/flask-filtered-response) [![Coverage Status](https://coveralls.io/repos/github/vrcmarcos/flask-filtered-response/badge.svg?branch=master)](https://coveralls.io/github/vrcmarcos/flask-filtered-response?branch=master) [![PyPI version](https://badge.fury.io/py/Flask-Filtered-Response.svg)](https://badge.fury.io/py/Flask-Filtered-Response) [![Code Health](https://landscape.io/github/vrcmarcos/flask-filtered-response/master/landscape.svg?style=flat)](https://landscape.io/github/vrcmarcos/flask-filtered-response/master) [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/vrcmarcos/flask-filtered-response/master/LICENSE)

## Instalation

```bash
pip install Flask-Filtered-Response
```

## Usage

To use Flask Filtered Response, decorate your view with *@filtered* decorator:

```python
import json
from flask_filtered_response import filtered

@app.route('/filtered/single_node')
@filtered
def single_node():
response_dict = {
'test_int': 123,
'test_string': 'Hey!',
}
return Response(json.dumps(response_dict))
```

Using *@filtered* decorator, you will enable the ability to use the query string *fields*:

- Request:
```bash
curl -X GET http://localhost:5000/filtered/single_node?fields=test_int
```

- Response:
```json
{
"test_int": 123
}
```

You can filter for multiple fields using **, (comma)**. Nested fields filtering is currently **NOT** supported.

## Changelog

#### 1.0.0:
- **@filtered**: Created **@filtered** decorator
40 changes: 40 additions & 0 deletions flask_filtered_response/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# -*- coding: utf-8 -*-

import json
from functools import wraps

from flask import request


def filtered(f):
@wraps(f)
def decorated(*args, **kwargs):
response = f(*args, **kwargs)
if request.method == 'GET':
if 'fields' in request.args:
required_fields = request.args.get('fields').split(',')
response_obj = json.loads(response.data)

if isinstance(response_obj, list):
filtered_data = __get_filtered_data_for_list(response_obj, required_fields)
else:
filtered_data = __get_filtered_data_for_dict(response_obj, required_fields)
response.data = json.dumps(filtered_data)
return response
return decorated


def __get_filtered_data_for_list(response_obj, required_fields):
filtered_data = list()
for node in response_obj:
filtered_node = __get_filtered_data_for_dict(node, required_fields)
filtered_data.append(filtered_node)
return filtered_data


def __get_filtered_data_for_dict(response_obj, required_fields):
keys = response_obj.keys()
for key in keys:
if key not in required_fields:
response_obj.pop(key, None)
return response_obj
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Flask==0.11.1
3 changes: 3 additions & 0 deletions requirements_test.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
pytest==2.8.2
pytest-cov==2.2.0
pytest-xdist==1.13.1

0 comments on commit 5dc13df

Please sign in to comment.