PKœœ[G=Ï’¡GGdrf_extra_fields/fields.pyimport base64 import binascii import imghdr import uuid import sys from django.core.exceptions import ValidationError from django.core.files.base import ContentFile from django.utils import six from django.utils.translation import ugettext_lazy as _ from rest_framework.fields import ImageField DEFAULT_CONTENT_TYPE = "application/octet-stream" ALLOWED_IMAGE_TYPES = ( "jpeg", "jpg", "png", "gif" ) EMPTY_VALUES = (None, '', [], (), {}) class Base64ImageField(ImageField): """ A django-rest-framework field for handling image-uploads through raw post data. It uses base64 for en-/decoding the contents of the file. """ def to_internal_value(self, base64_data): # Check if this is a base64 string if base64_data in EMPTY_VALUES: return None if isinstance(base64_data, six.string_types): # Try to decode the file. Return validation error if it fails. try: decoded_file = base64.b64decode(base64_data) except (TypeError, binascii.Error): raise ValidationError(_("Please upload a valid image.")) # Generate file name: file_name = str(uuid.uuid4())[:12] # 12 characters are more than enough. # Get the file name extension: file_extension = self.get_file_extension(file_name, decoded_file) if file_extension not in ALLOWED_IMAGE_TYPES: raise ValidationError(_("The type of the image couldn't been determined.")) complete_file_name = file_name + "." + file_extension data = ContentFile(decoded_file, name=complete_file_name) return super(Base64ImageField, self).to_internal_value(data) raise ValidationError(_('This is not an base64 string')) def to_representation(self, value): # Return url including domain name. return value.name def get_file_extension(self, filename, decoded_file): extension = imghdr.what(filename, decoded_file) extension = "jpg" if extension == "jpeg" else extension return extension PKœœ[Gåݘm““drf_extra_fields/geo_fields.pyimport json from django.contrib.gis.geos import GEOSGeometry from django.contrib.gis.geos.error import GEOSException from django.utils.encoding import smart_str from django.utils import six from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers EMPTY_VALUES = (None, '', [], (), {}) class PointField(serializers.Field): """ A field for handling GeoDjango Point fields as a json format. Expected input format: { "latitude": 49.8782482189424, "longitude": 24.452545489 } """ type_name = 'PointField' type_label = 'point' default_error_messages = { 'invalid': _('Enter a valid location.'), } def to_internal_value(self, value): """ Parse json data and return a point object """ if value in EMPTY_VALUES and not self.required: return None if isinstance(value, six.string_types): try: value = value.replace("'", '"') value = json.loads(value) except ValueError: self.fail('invalid') if value and isinstance(value, dict): try: latitude = value.get("latitude") longitude = value.get("longitude") return GEOSGeometry('POINT(%(longitude)s %(latitude)s)' % { "longitude": longitude, "latitude": latitude} ) except (GEOSException, ValueError): self.fail('invalid') self.fail('invalid') def to_representation(self, value): """ Transform POINT object to json. """ if value is None: return value if isinstance(value, GEOSGeometry): value = { "latitude": smart_str(value.y), "longitude": smart_str(value.x) } return value PKœœ[Gdrf_extra_fields/__init__.pyPKœœ[G¸§¡FÙÙ%drf_extra_fields/runtests/settings.py# Django settings for testproject project. DEBUG = True TEMPLATE_DEBUG = DEBUG DEBUG_PROPAGATE_EXCEPTIONS = True ALLOWED_HOSTS = ['*'] ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'sqlite.db', # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', } } # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'Europe/London' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-uk' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale USE_L10N = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com", "http://example.com/media/" MEDIA_URL = '' # Make this unique, and don't share it with anybody. SECRET_KEY = 'u@x-aj9(hoh#rb-^ymf#g2jx_hp0vj7u5#b@ag1n^seu9e!%cy' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = 'urls' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', # Uncomment the next line to enable the admin: # 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', 'rest_framework', 'rest_framework.authtoken', # 'rest_framework.tests', # 'rest_framework.tests.accounts', # 'rest_framework.tests.records', # 'rest_framework.tests.users', ) # OAuth is optional and won't work if there is no oauth_provider & oauth2 try: import oauth_provider import oauth2 except ImportError: pass else: INSTALLED_APPS += ( 'oauth_provider', ) try: import provider except ImportError: pass else: INSTALLED_APPS += ( 'provider', 'provider.oauth2', ) # guardian is optional try: import guardian except ImportError: pass else: ANONYMOUS_USER_ID = -1 AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', # default 'guardian.backends.ObjectPermissionBackend', ) INSTALLED_APPS += ( 'guardian', ) STATIC_URL = '/static/' PASSWORD_HASHERS = ( 'django.contrib.auth.hashers.SHA1PasswordHasher', 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 'django.contrib.auth.hashers.BCryptPasswordHasher', 'django.contrib.auth.hashers.MD5PasswordHasher', 'django.contrib.auth.hashers.CryptPasswordHasher', ) AUTH_USER_MODEL = 'auth.User' import django if django.VERSION < (1, 3): INSTALLED_APPS += ('staticfiles',) # If we're running on the Jenkins server we want to archive the coverage reports as XML. import os if os.environ.get('HUDSON_URL', None): TEST_RUNNER = 'xmlrunner.extra.djangotestrunner.XMLTestRunner' TEST_OUTPUT_VERBOSE = True TEST_OUTPUT_DESCRIPTIONS = True TEST_OUTPUT_DIR = 'xmlrunner' PKœœ[G±-ÈD!drf_extra_fields/runtests/urls.py""" Blank URLConf just to keep runtests.py happy. """ from rest_framework.compat import patterns urlpatterns = patterns('', ) PKœœ[Gâ$)€€%drf_extra_fields/runtests/runtests.pyimport os import sys sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)) os.environ['DJANGO_SETTINGS_MODULE'] = 'drf_extra_fields.runtests.settings' import django from django.conf import settings from django.test.utils import get_runner def usage(): return """ Usage: python runtests.py [UnitTestClass].[method] You can pass the Class name of the `UnitTestClass` you want to test. Append a method name if you only want to test a specific method of that class. """ def main(): try: django.setup() except AttributeError: pass TestRunner = get_runner(settings) test_runner = TestRunner() if len(sys.argv) == 2: test_case = '.' + sys.argv[1] elif len(sys.argv) == 1: test_case = '' else: print(usage()) sys.exit(1) test_module_name = 'tests' if django.VERSION[0] == 1 and django.VERSION[1] < 6: test_module_name = 'drf_extra_fields.runtests' failures = test_runner.run_tests([test_module_name + test_case]) sys.exit(failures) if __name__ == '__main__': main() PKœœ[G%drf_extra_fields/runtests/__init__.pyPK·œ[G½\‡å å 5django_extra_fields_lab-0.3.dist-info/DESCRIPTION.rstDRF-EXTRA-FIELDS ================ Extra Fields for Django Rest Framework ![https://travis-ci.org/Hipo/drf-extra-fields.svg?branch=master](https://travis-ci.org/Hipo/drf-extra-fields.svg?branch=master) Usage ================ install the package ```bash pip install django-extra-fields ``` **Note:** - Install version 0.1 for Django Rest Framework 2.* - Install version 0.3 for Django Rest Framework 3.* Fields: ---------------- ## Base64ImageField An image representation for Base64ImageField Intherited by `ImageField` **Signature:** `Base64ImageField()` - It takes a base64 image as a string. - a base64 image: `data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7` - Base64ImageField accepts only the part after base64, `R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7` **Example:** ```python # serializer from drf_extra_fields.fields import Base64ImageField class UploadedBase64ImageSerializer(serializers.Serializer): file = Base64ImageField(required=False) created = serializers.DateTimeField() # use the serializer file = 'R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==' serializer = UploadedBase64ImageSerializer(data={'created': now, 'file': file}) ``` ## PointField Point field for GeoDjango **Signature:** `PointField()` - It takes a dictionary contains latitude and longitude keys like below { "latitude": 49.8782482189424, "longitude": 24.452545489 } **Example:** ```python # serializer from drf_extra_fields.geo_fields import PointField class PointFieldSerializer(serializers.Serializer): point = PointField(required=False) created = serializers.DateTimeField() # use the serializer point = { "latitude": 49.8782482189424, "longitude": 24.452545489 } serializer = PointFieldSerializer(data={'created': now, 'point': point}) ``` CONTRIBUTION ================= *TESTS* - Make sure that you add the test for contributed field to test/test_fields.py and run with command before sending a pull request: ```bash $ pip install tox # if not already installed $ tox ``` *README* - Make sure that you add the documentation for the field added to README.md LICENSE ==================== Copyright DRF EXTRA FIELDS HIPO Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. PK·œ[G¸È\zz3django_extra_fields_lab-0.3.dist-info/metadata.json{"classifiers": ["Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "Operating System :: OS Independent", "Programming Language :: Python", "Topic :: Internet :: WWW/HTTP", "Topic :: Internet :: WWW/HTTP :: Dynamic Content"], "extensions": {"python.details": {"contacts": [{"email": "pypi@hipolabs.com", "name": "hipo", "role": "author"}], "document_names": {"description": "DESCRIPTION.rst"}}}, "generator": "bdist_wheel (0.26.0)", "license": "License", "metadata_version": "2.0", "name": "django-extra-fields-lab", "summary": "Additional fields for Django Rest Framework.", "version": "0.3"}PK·œ[G~Pú†3django_extra_fields_lab-0.3.dist-info/top_level.txtdrf_extra_fields PK·œ[G}À‚¼\\+django_extra_fields_lab-0.3.dist-info/WHEELWheel-Version: 1.0 Generator: bdist_wheel (0.26.0) Root-Is-Purelib: true Tag: py3-none-any PK·œ[G+ª.ø ø .django_extra_fields_lab-0.3.dist-info/METADATAMetadata-Version: 2.0 Name: django-extra-fields-lab Version: 0.3 Summary: Additional fields for Django Rest Framework. Home-page: UNKNOWN Author: hipo Author-email: pypi@hipolabs.com License: License Platform: UNKNOWN Classifier: Environment :: Web Environment Classifier: Framework :: Django Classifier: Intended Audience :: Developers Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Topic :: Internet :: WWW/HTTP Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content DRF-EXTRA-FIELDS ================ Extra Fields for Django Rest Framework ![https://travis-ci.org/Hipo/drf-extra-fields.svg?branch=master](https://travis-ci.org/Hipo/drf-extra-fields.svg?branch=master) Usage ================ install the package ```bash pip install django-extra-fields ``` **Note:** - Install version 0.1 for Django Rest Framework 2.* - Install version 0.3 for Django Rest Framework 3.* Fields: ---------------- ## Base64ImageField An image representation for Base64ImageField Intherited by `ImageField` **Signature:** `Base64ImageField()` - It takes a base64 image as a string. - a base64 image: `data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7` - Base64ImageField accepts only the part after base64, `R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7` **Example:** ```python # serializer from drf_extra_fields.fields import Base64ImageField class UploadedBase64ImageSerializer(serializers.Serializer): file = Base64ImageField(required=False) created = serializers.DateTimeField() # use the serializer file = 'R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==' serializer = UploadedBase64ImageSerializer(data={'created': now, 'file': file}) ``` ## PointField Point field for GeoDjango **Signature:** `PointField()` - It takes a dictionary contains latitude and longitude keys like below { "latitude": 49.8782482189424, "longitude": 24.452545489 } **Example:** ```python # serializer from drf_extra_fields.geo_fields import PointField class PointFieldSerializer(serializers.Serializer): point = PointField(required=False) created = serializers.DateTimeField() # use the serializer point = { "latitude": 49.8782482189424, "longitude": 24.452545489 } serializer = PointFieldSerializer(data={'created': now, 'point': point}) ``` CONTRIBUTION ================= *TESTS* - Make sure that you add the test for contributed field to test/test_fields.py and run with command before sending a pull request: ```bash $ pip install tox # if not already installed $ tox ``` *README* - Make sure that you add the documentation for the field added to README.md LICENSE ==================== Copyright DRF EXTRA FIELDS HIPO Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. PK·œ[G ¥Â´´,django_extra_fields_lab-0.3.dist-info/RECORDdjango_extra_fields_lab-0.3.dist-info/DESCRIPTION.rst,sha256=MCXxrZpxxm7ykwyiAdjxyukCZPyzbCRB9FI3QXzrKJ8,2789 django_extra_fields_lab-0.3.dist-info/METADATA,sha256=bEzSa64j8Xzb1d-TyMAH0vHsBqYeHllAFOPyXpqqLsA,3320 django_extra_fields_lab-0.3.dist-info/RECORD,, django_extra_fields_lab-0.3.dist-info/WHEEL,sha256=zX7PHtH_7K-lEzyK75et0UBa3Bj8egCBMXe1M4gc6SU,92 django_extra_fields_lab-0.3.dist-info/metadata.json,sha256=4ukeuKXRlShJljM5MaVC8I_pOhStqXWLM_mUj5REiMU,634 django_extra_fields_lab-0.3.dist-info/top_level.txt,sha256=vbrQ8UIzOu5LGMxweW5CneMeDG42XXNKITirx29OLSo,17 drf_extra_fields/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 drf_extra_fields/fields.py,sha256=HwkwVVWtpsD06DdYGgTqQhglYt9XekO27Sv40Jjjolc,2119 drf_extra_fields/geo_fields.py,sha256=WP7ZkFdJNN95YvwmFRjcP2_UpFKUWU9wgX7zcZ93tn8,1939 drf_extra_fields/runtests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 drf_extra_fields/runtests/runtests.py,sha256=NlDQxTXck7hjTMrdXAWB06qxThomc2mqqgXnY0niBpw,1152 drf_extra_fields/runtests/settings.py,sha256=MI24CL7KkyIYMfP65MtukgHvp2tVce-jx-O8EZzPLf0,5081 drf_extra_fields/runtests/urls.py,sha256=J982nCS0bGmyo8TILaYYqsWZayVrGKVjMVDx5Z5Qm9o,127 PKœœ[G=Ï’¡GGdrf_extra_fields/fields.pyPKœœ[Gåݘm““drf_extra_fields/geo_fields.pyPKœœ[GNdrf_extra_fields/__init__.pyPKœœ[G¸§¡FÙÙ%ˆdrf_extra_fields/runtests/settings.pyPKœœ[G±-ÈD!¤$drf_extra_fields/runtests/urls.pyPKœœ[Gâ$)€€%b%drf_extra_fields/runtests/runtests.pyPKœœ[G%%*drf_extra_fields/runtests/__init__.pyPK·œ[G½\‡å å 5h*django_extra_fields_lab-0.3.dist-info/DESCRIPTION.rstPK·œ[G¸È\zz3 5django_extra_fields_lab-0.3.dist-info/metadata.jsonPK·œ[G~Pú†3k8django_extra_fields_lab-0.3.dist-info/top_level.txtPK·œ[G}À‚¼\\+Í8django_extra_fields_lab-0.3.dist-info/WHEELPK·œ[G+ª.ø ø .r9django_extra_fields_lab-0.3.dist-info/METADATAPK·œ[G ¥Â´´,¶Fdjango_extra_fields_lab-0.3.dist-info/RECORDPK Z´K