Giter Site home page Giter Site logo

redisca's Introduction

Master branch: Build Status

Redisca2

Look at redisca2 for new features. This version will receive bug fixes only.

Installation

Using PyPi (recommended):

sudo pip install redisca

or

wget https://pypi.python.org/packages/source/r/redisca/redisca-X.tar.gz
tar xvf redisca-X.tar.gz
sudo python redisca-X/setup.py install

Model

from redisca import Model
from redisca import Email
from redisca import DateTime

class User (Model):
        email = Email(
                field='eml', # Define link with 'eml' hash key.
                index=True,  # Index support.
                unique=True, # Makes sure that field is unique across db.
        )

        created = DateTime(
                field='created',        # Define link with 'created' hash key.
                new=datetime.utcnow, # Value which is used as default in User.new()
        )

        age = Integer(
                field='age', # Define link with 'age' hash key.
                index=True,  # Enable index.
        )

user = User.new() # Create model with random id and "new" fields values.
user = User.new(model_id='your_id') # Or use custom id if needed.

user.getid() # user id
user.email = '[email protected]'

user.save()   # Saving routines
user.exists() # True

user.delete() # Deletion routines
user.exists() # False

Fields

Field is the way how you should control data in your models. Just define class variables with field-specific options and take classic ORM's advantages:

  • data validation;
  • native python data types support;
  • transparent relations between models;
  • indexes support (incl. unique indexes).

Available parameters:

  • field - redis hash field name to store value in.
  • index - makes field searchable.
  • unique - tells that value should be unique across database. Model.save() will raise an Exception if model of same class already exists with given value.
  • new - field value which is used as default in Model.new(). Functions, methods and built-in's are acceptable as callback values.

Built-in fields:

  • String - extends IndexField with additional parameters minlen and maxlen.
  • Email - extends IndexField field with email validation support.
  • Integer - extends RangeIndexField with parameters minval and maxval. Accepts int and numeric strings. Returns int.
  • Reference - extends IndexField with cls (reference class) parameter. Accepts and returns instance of cls.
  • MD5Pass - extends String field. Acts like string but converts given string to md5 sum.
  • DateTime - extends RangeIndexField without additional parameters. Accepts datetime and int(timestamp) values. Returns datetime.

Getting Data

Using id

Here is an example how to get model instance using id (empty model returned if it not exists yet):

user = User('user id')
print(user.email) # '[email protected]'

Each initialized model is saved in registry and returned on each attempt of re-init:

user1 = User('user_id')
user2 = User('user_id')
user1 is user2 # Always is True

user.free()   # Unregister model instance.
User.free_all()  # Cleanup User's registry.
Model.free_all() # Unregister all known models.

Find by Index

users = User.email == '[email protected]' # or User.email.find('[email protected]')

Subclasses of RangeIndexField has a limited support for ranged queries:

users = User.age >= 10 # User.age.range(minval=10)

More complex queries are also possible:

# SELECT * FROM `users` where `age` BETWEEN 0 AND 100 LIMIT 10 OFFSET 50;
users = User.age.range(minval=0, maxval=100, start=50, num=10)

Dict API

All fields are linked to model dict keys. Use can use model dict API to read and write redis hash data AS IS:

user = User('id')
user['eml'] = '[email protected]'
user['age'] = 10

Connecting to Redis

Global database connection setup looks like this:

from redisca import conf
from redis import Redis

conf.db = Redis()

Note: redisca uses localhost:6379(0) as default database. You can setup inheritable per-model database connection using conf class decorator:

from redisca import Model
from redisca import conf

from redis import Redis

@conf(db=Redis())
class User (Model):
        pass

Key Format

Model key format is:

model_key_prefix:model_id

Default model_key_prefix is lowercased class name. Use conf class decorator to override it like this:

from redisca import Model
from redisca import conf

@conf(prefix='usr')
class User (Model):
        pass

print(User.getprefix()) # 'usr'
print(user.getkey())    # 'usr:1'

Tools

ID Generator

from redisca import hexid
from redisca import intid

print(hexid()) # 59d369790
print(hexid()) # 59d3697bc

print(intid()) # 24116751882
print(intid()) # 24116788848

Flask Support

from redisca import FlaskRedisca

app = Flask()

app.config['REDISCA'] = {
        # redis.StrictRedis constructor kwargs dict.
}

FlaskRedisca(app)

Optional autosave constructor parameter tells redisca that all known models should be saved at the end of request (if no exception raised). Unchanged and deleted instances are ignored. If you want to skip locally changed instances use free() method during request life.

Requirements

  • redis-py 2.7+
  • python 2.7/3.2+ or pypy 2.1+

Python 3.x support

Py3k support is still a sort of experiment but I'm looking carefuly into full compability with cutting-edge builds of CPython. There are no known issues with it actually.

redisca's People

Contributors

khamin avatar

Stargazers

DJun avatar Zeyi Wang avatar suzaku avatar  avatar  avatar  avatar Nícolas Dornelles avatar Daniel Lopez Monagas avatar 陈云云 avatar Ivandir avatar Tanel Puhu avatar Yannick Koechlin avatar  avatar Eugene Klimov avatar Jonathan Barratt avatar

Watchers

Eugene Klimov avatar  avatar 陈云云 avatar

redisca's Issues

Switchable models index

Store models keys in dedicaded set and use it in Model.find_all and Model.exists (check if set item exists instead of key)

"ResponseError: value is not a double" when Model.save()

When I insert data the error mentioned in the title occurs, but the data is actually introduced to the key-value store (I can query it via the command line). It seems strange, because some data is introduced via a form (I'm working with flask) and the rest is handled with the new parameter of the Model classes.

I've been testing with another use case and the same issue happens, and I don't seem to recall why. If I create the a set with a "manually" chosen key the problem doesn't occur but the data that is supposed to be inserted automatically isn't.

Also, it'd be a cool feature that we could set the id manually without breaking the automatic data insertion as the case above.

It's a good project, by the way. Kudos to @khamin.

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.