Git Product home page Git Product logo

handy's Introduction

Handy

A collection of different tools, shortcuts, decorators, form and model fields to make your django life easier.

Installation

pip install handy

Overview

Here are quick overview of what you can do with handy. You can also read full docs.

Avoid HttpResponse and render_to_response() biolerplate with @render_to() decorator. This one will render result dict to 'app_name/foo.html':

@render_to()
def foo(request):
    return {
        'bar': Bar.objects.all()
        # You can easily override default template, content type,
        # status code and add cookies to response:
        'STATUS': 410,
        'CONTENT_TYPE': 'text/plain'
    }

Easy JSON responders with @render_to_json() decorator:

@render_to_json()
def posts_by_tag(request, tag=None):
    posts = Post.object.values().filter(tag=tag)
    return list(posts)

And higher order @ajax decorator to handle more complex asynchronous actions:

@ajax
@ajax.login_required
@ajax.catch(Post.DoesNotExist)
def enable_post(request):
    post = Post.objects.get(pk=request.GET['id'])

    if post.author != request.user:
        raise ajax.error('permission_denied')

    post.enabled = True
    post.save()

Send emails rendered from templates:

render_to_email(article.author.email, 'approved.html', {'article': article})

A collection of model fields with accompanying form fields and widgets. Most notably different array fields to store array of values or choices:

DAYS = zip(range(7), 'Sun Mon Tue Wed Thu Fri Sat'.split())

class Company(models.Model):
    phones = StringArrayField('Phone numbers', blank=True, default=lambda: [])
    workdays = IntegerArrayField('Work days', choices=DAYS)

company = Company(phones=['234-5016', '516-2314'], workdays=[1,2,3,4])
company.save()

In model form phones field would be represented as CommaSeparatedInput and workdays as multiple checkboxes:

class CompanyForm(forms.ModelForm):
    class Meta:
        model = Company

A handy @cached_property utility:

class UserProfile(models.Model):
    phones = models.ManyToManyField(Phone)

    ...

    @cached_property
    def public_phones(self):
        # this queryset will be constructed only once, thanks to @cached_property
        return self.phones.filter(public=True)

A bunch of database querying utilities to not tinker with cursor() anymore:

best_offer = fetch_val('select max(value) from offers where ...')

for row in fetch_named('select * from blog_post'):
    print row.id, row.title

And a middleware to make your html output slimmer by stripping out unnecessary spaces:

MIDDLEWARE_CLASSES = (
    ...
    'handy.middleware.StripWhitespace',
)

And more:

  • simple logger wrap up
  • CommaSeparatedInput and MultilineInput widgets for array fields
  • JSONField, AdditionalAutoField and BigAutoField
  • and a bunch of database, email, text and debugging utilities

NOTE: functional tools, namely @memoize and @cache, moved to funcy

How you can help

  • give me any feedback. What bits are most useful? What can be added or changed?
  • bring your ideas and/or code that can make all our django experience more fun

TODO

  • docs for text and just utils
  • add support for querysets and models in JSON decorators

handy's People

Contributors

0x2b3bfa0 avatar caxap avatar dizballanze avatar hackprime avatar hayd avatar leliel12 avatar nuklea avatar suor avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

handy's Issues

Remove deprecation warnings

/src/handy/handy/models/fields.py:25: 
DeprecationWarning: A Field class whose get_db_prep_value method hasn't been updated to take `connection` and `prepared` arguments.
  class AdditionalAutoField(models.Field):

/src/handy/handy/models/fields.py:238: 
DeprecationWarning: A Field class whose db_type method hasn't been updated to take a `connection` argument.
  class BigIntegerField(models.IntegerField):

simplejson import

In decorators.py

import simplejson as json

Why don't simply import simplejson from django utils as environments may not have simplejson installed (as mine one) and use simplejson bundled with django:

from django.utils import simplejson as json

Python 3.12 support

With the latest upgrade to Python 3.12, I am getting the error below:

/usr/local/lib/python3.12/site-packages/handy/mail.py:29: SyntaxWarning: invalid escape sequence '\s'
  raise ValueError('Email subject required\nPrepend email content with "Subject:\s<subject>\\n\\n"')
/usr/local/lib/python3.12/site-packages/handy/mail.py:35: SyntaxWarning: invalid escape sequence '\w'
  m = re.search('^text/([\w-]+)', value)

Неверно устанавливается пакет с pypi (pip 1.2)

После pip install handy==0.1.2 получил следующее в системе:

$ find /home/nuklea/.virtualenvs/nazya/lib/python2.7/site-packages/handy
/home/nuklea/.virtualenvs/nazya/lib/python2.7/site-packages/handy
/home/nuklea/.virtualenvs/nazya/lib/python2.7/site-packages/handy/ajax.pyc
/home/nuklea/.virtualenvs/nazya/lib/python2.7/site-packages/handy/db.py
/home/nuklea/.virtualenvs/nazya/lib/python2.7/site-packages/handy/__init__.pyc
/home/nuklea/.virtualenvs/nazya/lib/python2.7/site-packages/handy/logger.py
/home/nuklea/.virtualenvs/nazya/lib/python2.7/site-packages/handy/text.py
/home/nuklea/.virtualenvs/nazya/lib/python2.7/site-packages/handy/funcs.pyc
/home/nuklea/.virtualenvs/nazya/lib/python2.7/site-packages/handy/decorators.py
/home/nuklea/.virtualenvs/nazya/lib/python2.7/site-packages/handy/funcs.py
/home/nuklea/.virtualenvs/nazya/lib/python2.7/site-packages/handy/mail.py
/home/nuklea/.virtualenvs/nazya/lib/python2.7/site-packages/handy/db.pyc
/home/nuklea/.virtualenvs/nazya/lib/python2.7/site-packages/handy/utils.py
/home/nuklea/.virtualenvs/nazya/lib/python2.7/site-packages/handy/middleware.py
/home/nuklea/.virtualenvs/nazya/lib/python2.7/site-packages/handy/decorators.pyc
/home/nuklea/.virtualenvs/nazya/lib/python2.7/site-packages/handy/logger.pyc
/home/nuklea/.virtualenvs/nazya/lib/python2.7/site-packages/handy/mail.pyc
/home/nuklea/.virtualenvs/nazya/lib/python2.7/site-packages/handy/__init__.py
/home/nuklea/.virtualenvs/nazya/lib/python2.7/site-packages/handy/text.pyc
/home/nuklea/.virtualenvs/nazya/lib/python2.7/site-packages/handy/ajax.py
/home/nuklea/.virtualenvs/nazya/lib/python2.7/site-packages/handy/utils.pyc
/home/nuklea/.virtualenvs/nazya/lib/python2.7/site-packages/handy/middleware.pyc

Отсутствуют многие файлы.

Django 1.9 support

It seems that handy doesn't support Django 1.9. If I try to use the package I get the following error:

Traceback (most recent call last):
  File "runtests.py", line 37, in <module>
    runtests(*sys.argv[1:])
  File "runtests.py", line 24, in runtests
    django.setup()
  File "/home/gregor/projects/oTree/otree-core/.tox/py2.7-django1.9-unittest/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/gregor/projects/oTree/otree-core/.tox/py2.7-django1.9-unittest/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate
    app_config = AppConfig.create(entry)
  File "/home/gregor/projects/oTree/otree-core/.tox/py2.7-django1.9-unittest/lib/python2.7/site-packages/django/apps/config.py", line 116, in create
    mod = import_module(mod_path)
  File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/home/gregor/projects/oTree/otree-core/otree/apps.py", line 11, in <module>
    from otree.models_concrete import StubModel
  File "/home/gregor/projects/oTree/otree-core/otree/models_concrete.py", line 1, in <module>
    from otree.db import models
  File "/home/gregor/projects/oTree/otree-core/otree/db/models.py", line 13, in <module>
    from handy.models import JSONField, PickleField
  File "/home/gregor/projects/oTree/otree-core/.tox/py2.7-django1.9-unittest/lib/python2.7/site-packages/handy/models/__init__.py", line 1, in <module>
    from .fields import *
  File "/home/gregor/projects/oTree/otree-core/.tox/py2.7-django1.9-unittest/lib/python2.7/site-packages/handy/models/fields.py", line 17, in <module>
    from handy.utils import get_module_attr
  File "/home/gregor/projects/oTree/otree-core/.tox/py2.7-django1.9-unittest/lib/python2.7/site-packages/handy/utils.py", line 10, in <module>
    from django.db.models.sql.where import Constraint
ImportError: cannot import name Constraint

Is there any chance that Django 1.9 will be supported in the future?

JSON content type

Why there is text/plain content type for decorators.render_to_json? JSON response should have application/json type to determine automatically on client side (e.g. with jQuery.ajax)

@Ajax decorator and json serialization

Currently @ajax and render_to_json uses two different json encoders, one that uses a very old datetime format (the @Ajax one) and another one that uses datetime isoformat (which should be fine to meet current javascript date formatting).

Would be great to have all json serialization code to use the same encoder, and even better, use the django one (DjangoJSONEncoder) that's already implemented to handle all non standard data types.

model StringArrayField

При сохранении русских символов, получаю ошибку

'ascii' codec can't decode byte 0xd1 in position 0: ordinal not in range(128). You passed in <django.forms.forms.BoundField object at 0x7f0e77a2f290> (<class 'django.forms.forms.BoundField'>)
Request Method: GET
Request URL: http://local.nazya.com:8000/admin/base/patternreplacement/3/
Django Version: 1.4.2
Exception Type: DjangoUnicodeDecodeError
Exception Value:
'ascii' codec can't decode byte 0xd1 in position 0: ordinal not in range(128). You passed in <django.forms.forms.BoundField object at 0x7f0e77a2f290> (<class 'django.forms.forms.BoundField'>)
Exception Location: /home/nikolay/env/nazya-env/local/lib/python2.7/site-packages/django/utils/encoding.py in force_unicode, line 93
Python Executable: /home/nikolay/env/nazya-env/bin/python
Python Version: 2.7.3
Python Path:
['/home/nikolay/env/nazya-env/local/lib/python2.7/site-packages/requests/packages',
'/home/nikolay/PycharmProjects/nazya/apps',
'/home/nikolay/PycharmProjects/nazya/libs',
'/home/nikolay/PycharmProjects/nazya',
'/home/nikolay/PycharmProjects/nazya',
'/home/nikolay/pycharm-2.6.3/helpers/pydev',
'/home/nikolay/env/nazya-env/local/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg',
'/home/nikolay/env/nazya-env/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg',
'/home/nikolay/env/nazya-env/local/lib/python2.7/site-packages/distribute-0.6.28-py2.7.egg',
'/home/nikolay/env/nazya-env/src/django-mptt',
'/home/nikolay/env/nazya-env/src/coffin',
'/home/nikolay/env/nazya-env/src/django-pure-pagination',
'/home/nikolay/env/nazya-env/src/django-autocomplete',
'/home/nikolay/env/nazya-env/src/django-debug-toolbar',
'/home/nikolay/env/nazya-env/src/django-piston',
'/home/nikolay/env/nazya-env/local/lib/python2.7/site-packages/mercurial_keyring-0.5.3-py2.7.egg',
'/home/nikolay/env/nazya-env/local/lib/python2.7/site-packages/keyring-0.9.2-py2.7.egg',
'/home/nikolay/env/nazya-env/lib/python2.7',
'/home/nikolay/env/nazya-env/lib/python2.7/plat-linux2',
'/home/nikolay/env/nazya-env/lib/python2.7/lib-tk',
'/home/nikolay/env/nazya-env/lib/python2.7/lib-old',
'/home/nikolay/env/nazya-env/lib/python2.7/lib-dynload',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-linux2',
'/usr/lib/python2.7/lib-tk',
'/home/nikolay/env/nazya-env/local/lib/python2.7/site-packages',
'/home/nikolay/env/nazya-env/local/lib/python2.7/site-packages/PIL']
Server time: Птн, 14 Дек 2012 11:17:06 +0100

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.