Mostrando las entradas con la etiqueta couchapp. Mostrar todas las entradas
Mostrando las entradas con la etiqueta couchapp. Mostrar todas las entradas

martes, noviembre 02, 2010

CouchApp V: filtrar documentos por tag ordenados por fecha

ahora tenemos documentos y para pertenecer a este siglo decidiste agregar tags a algunos elementos para poder filtrarlos y categorizarlos (decí folksonomia y vas a sonar mucho mas hip!)

ahora, como filtro documentos por tag?

si puedo hacer eso, como filtro por tag y ordeno por fecha?

ya que estamos, no seria lindo poder filtrar por tag *y* por fecha?

vamos a resolver todos estos requerimientos con una simple vista

primero creamos la vista

couchapp generate view by-tag

esto crea una vista en el directorio views llamado by-tag, este es un directorio que contiene dos archivos, map.js y reduce.js

en este caso vamos a usar solo map.js asi que borra reduce.js

cd views/by-tag
rm reduce.js

ahora edita map.js para que se vea como esto

function(doc) {
    if (doc.tags) {
        doc.tags.forEach(function (element, index) {
                emit([element, doc.created], doc);
        });
    }
}

por cada documento en la base de datos, vemos si tiene el atributo tags, si lo tiene, por cada tag en tags emitimos un documento cuya llave es un array con el tag y la fecha y cuyo valor es el documento en si.

ahora empujamos los cambios a couchdb

couchapp push

para probar que funciona, crea algunos documentos con el un campo llamado tags que contenga un array de strings y otro campo llamado created que contenga el timestamp en el que el documento fue creado

si pongo esta URL http://localhost:5984/datos/_design/datos/_view/by-tag/ en mi navegador, obtengo algo así:

{"total_rows":8,"offset":0,"rows":[
{"id":"d6de7e9a63039dc1af500a40af0014d7","key":["bar",1288644825761],"value":{"_id":"d6de7e9a63039dc1af500a40af0014d7","_rev":"1-eab86fbc2b4c24f31e1d60dfdd762793","author":"wariano", "created":1288644825761, "tags":["test","foo","bar"], ...}},
...
]}

esto significa que la vista funciono, ahora para filtrar por tag la URL se va a poner un poco rara

vamos a usar filtros en la vista para filtrar solo los documentos con un tag especifico

http://localhost:5984/datos/_design/datos/_view/by-tag?descending=false&startkey=["test", 0]&endkey=["test", 9999999999999]

con este request decimos que queremos los resultados de la vista llamada by-tag, filtrando los documentos empezando con la llave ["test", 0] y terminando con la llave ["test", 9999999999999]. Esto significa que solo queremos los documentos con la llave "test" y que queremos todos los timestamps (por eso el numero enorme en endkey)

si queremos ordenar los tags en orden descendente deberíamos cambiar el orden de starkey y endkey: http://localhost:5984/datos/_design/datos/_view/by-tag?descending=true&startkey=["test", 9999999999999]&endkey=["test", 0]

podemos jugar con startkey y endkey para obtener rangos de tags o un tag en un periodo de tiempo especifico, por ejemplo: "cosas taggeadas con fun en los últimos dos días"

el código para hacer el request a couchdb desde javascript es el siguiente

datos.getByTag = function (tag, descending, okCb, errorCb, startStamp, endStamp) {
    var tmp;

    startStamp = startStamp || 0;
    endStamp = endStamp || 9999999999999;

    if (descending) {
        tmp = endStamp;
        endStamp = startStamp;
        startStamp = tmp;
    }

    $.couch.db(datos.db).view("datos/by-tag",
        {"descending": descending, "startkey": [tag, startStamp], "endkey": [tag, endStamp],
            "success": okCb, "error": errorCb});
};

con esto tenes una forma de listar documentos por uno o mas campos, podes modificar este ejemplo un poco para listar por usuario o por otras cosas

[EN] CouchApp V: filter documents by tag ordered by timestamp

you now have documents and to be in this century you decide to add tags to some elements so you can filter and categorize (say folksonomy and you will sound really hip!)


now, how do I filter the documents by tag?


if I can do that, how do I filter by tag and order by date?


now that we are at it, wouldn't be nice to have a filter by tag *and* date?


we will solve all this requirements with a simple view


first we create the view


couchapp generate view by-tag

this creates a view in the views called by-tags, this is a directory that contains two files, map.js and reduce.js


in this case we will only use the map.js file, so remove the reduce.js file


cd views/by-tag
rm reduce.js

now edit the map.js file to look like this


function(doc) {
    if (doc.tags) {
        doc.tags.forEach(function (element, index) {
                emit([element, doc.created], doc);
        });
    }
}

here for each document in the database we check if the document has the tags attribute and if it has the attribute, for each tag we emit a document that contains as key an array with the tag and timestamp when the document was created and as value the document itself


now we push our changes to couchdb


couchapp push

to test that this works, create some documents with a field called tags that contains a list of strings and a field called created that contain the timestamp when the item was created


if I put this URL http://localhost:5984/datos/_design/datos/_view/by-tag/ in my browser I get something like this


{"total_rows":8,"offset":0,"rows":[
{"id":"d6de7e9a63039dc1af500a40af0014d7","key":["bar",1288644825761],"value":{"_id":"d6de7e9a63039dc1af500a40af0014d7","_rev":"1-eab86fbc2b4c24f31e1d60dfdd762793","author":"wariano", "created":1288644825761, "tags":["test","foo","bar"], ...}},
...
]}

this means the view worked, now to filter by tag the URL will get weird


we will use filters in the view to filter only for a specific tag


http://localhost:5984/datos/_design/datos/_view/by-tag?descending=false&startkey=["test", 0]&endkey=["test", 9999999999999]


with this request we say that we want to get the result of the view called by-tag, filtering starting with the key ["test", 0] and ending with the key ["test", 9999999999999]. This means that we only want the documents with the key "test" and we want all the timestamps (that's why the huge number in the endkey


if we want to sort the tags in descending order we should switch the start and endkey like this: http://localhost:5984/datos/_design/datos/_view/by-tag?descending=true&startkey=["test", 9999999999999]&endkey=["test", 0]


we can play with startkey and endkey to get a range of tags or one tag in a specific period, for example, "things tagged fun in the last 2 days"


the code to do the request to couchdb from javascript is the following


datos.getByTag = function (tag, descending, okCb, errorCb, startStamp, endStamp) {
    var tmp;

    startStamp = startStamp || 0;
    endStamp = endStamp || 9999999999999;

    if (descending) {
        tmp = endStamp;
        endStamp = startStamp;
        startStamp = tmp;
    }

    $.couch.db(datos.db).view("datos/by-tag",
        {"descending": descending, "startkey": [tag, startStamp], "endkey": [tag, endStamp],
            "success": okCb, "error": errorCb});
};

with this you have a way to list documents by one or more fields, you can modify this a little to list by users, or by some other thing

viernes, octubre 22, 2010

CouchApp IV: creando funciones show con templates HTML

necesitamos mostrar una entidad en su propia pagina, para eso vamos a necesitar un template html con los valores del documento almacenado en la base de datos, un template es una buena herramienta para eso, veamos como hacerlo en nuestra couchapp


primero creamos la funcion show, esta funcion es llamada para mostrar un documento en algun formato, en nuestro caso html


# generamos la funcion show
couchapp generate show dato
# la editamos con un editor de texto
vim shows/dato.js

en un principio vamos a ver este contenido



function(doc, req) {  
  
}

reemplazamos por algo parecido a esto



function(doc, req) {
    if (doc !== null && doc.name) {
        var ddoc = this,
            Mustache = require("vendor/couchapp/lib/mustache"),
            path = require("vendor/couchapp/lib/path").init(req),
            assetPath = path.asset();

        provides("html", function() {
            return Mustache.to_html(ddoc.templates.dato, {
                assetPath: assetPath,
                doc: doc
            });
        });
    }
    else {
        return "not found";
    }
}

en el codigo controlamos que tenemos un documento, sino mostramos "not found",
tambien creamos algunos objetos que nos ayudan y finalmente renderizamos el template pasandole algunos valores que seran usados dentro del template.


mi template esta en templates/dato.html (por eso ddoc.templates.dato) y contiene un template mustache, mira la documentacion de mustache para mas informacion sobre el formato


la url par acceder a esta funcion es [database]/_design/[app]/_show/[showname]/[docid] un ejemplo podria ser http://localhost:5984/datos/_design/datos/_show/dato/6bd97648d74961996c8f0d42b2005761

[EN] CouchApp IV: creating show functions with html templates

we need to display some entity in its own web page, for that we need to fill an html template with the values of the document stores in the database, a template is a nice fit for this, let's see how we do this in our couchapp


first, create the show function, this is a function that when called displays a document in some format, in our case in HTML


# generate the show function
couchapp generate show dato
# open it with a text editor
vim shows/dato.js

we will see this content



function(doc, req) {  
  
}

we replace the content with something like this



function(doc, req) {
    if (doc !== null && doc.name) {
        var ddoc = this,
            Mustache = require("vendor/couchapp/lib/mustache"),
            path = require("vendor/couchapp/lib/path").init(req),
            assetPath = path.asset();

        provides("html", function() {
            return Mustache.to_html(ddoc.templates.dato, {
                assetPath: assetPath,
                doc: doc
            });
        });
    }
    else {
        return "not found";
    }
}

here we check that we have a document, if not return "not found", also we create some objects that will help us and finally we render the template passing some values that will be used in the template.


my template is located at templates/dato.html (that's why ddoc.templates.dato) and contains a mustache template, see mustache documentation for information about the format


the url to access this function is [database]/_design/[app]/_show/[showname]/[docid] an example could be http://localhost:5984/datos/_design/datos/_show/dato/6bd97648d74961996c8f0d42b2005761

CouchApp III: subiendo los cambios automaticamente

ahora que tenemos todo lo que necesitamos para crear nuestra couchapp, podemos ir al directorio _attachments y empezar a modificar el código para que haga lo que queramos


después de un rato vas a notar que necesitas hacer push de los cambios a couchdb cada vez que queres probarlos, si sos como yo esto se va a poner molesto bastante rápido, hagamos que las herramientas nos ayuden


#install inotify-tools
sudo apt-get install inotify-tools

con inotify tools vamos a correr un script que va a monitorear cualquier cambio de archivos y va a hacer un push cuando eso suceda, voy a excluir los cambios en *.swp ya que vim crea esos archivos y cambian bastante seguido


corre este comando en algún shell y dejalo corriendo


inotifywait -q -e modify -m -r . | while read line; do if echo $line | grep -v .*.swp; then couchapp push; fi; done

ahora edita algún archivo y guardalo, anda al shell donde tenes el script corriendo, vas a ver algo como esto:


./_attachments/ MODIFY index.html
2010-10-22 11:00:48 [INFO] Visit your CouchApp here:
http://wariano:secret@localhost:5984/datos/_design/datos/index.html

ahora podes editar tus archivos y los cambios van a ser automáticamente subidos a couchdb

[EN] CouchApp III: pushing the changes automatically

now we have all we need to start creating our couchapp, go to the _attachments directory and start modifying the code to do what you want


after a moment you will notice that you need to push the changes to couchdb each time you want to test it, if you are like me this will get annoying pretty fast, let's make the tools help us


#install inotify-tools
sudo apt-get install inotify-tools

with inotify tools we will run a script that will monitor any file change and make a couchapp push when that happens, I will exclude the changes in *.swp files since vim create those and they change pretty often


in some shell run this and leave it running


inotifywait -q -e modify -m -r . | while read line; do if echo $line | grep -v .*.swp; then couchapp push; fi; done

now edit some file and save it, go back to the shell where the script is running, you should see something like:


./_attachments/ MODIFY index.html
2010-10-22 11:00:48 [INFO] Visit your CouchApp here:
http://wariano:secret@localhost:5984/datos/_design/datos/index.html

now you can edit your files and the changes will be pushed automatically to couchdb

CouchApp II: arreglando la fiesta de admins

ahora que tenemos nuestra aplicacion corriendo podemos ver que hay un problema con la demo, no tenemos autenticacion, por default couchdb esta en modo "fiesta de admins", para leer mas sobre la fiesta de admins en couchdb podes leer Couchdb the definitive guide


para arreglarlo necesitamos usar futon (el panel administrativo de couchdb) y crear el primer admin


anda a futon con tu browser a http://localhost:5984/_utils/index.html


abajo a la derecha de la pagina deberias leer algo como "Welcome to Admin Party! Everyone is admin. Fix this", hace click en el link y crea el primer admin


voy a crear el admin como "wariano" y como password "secret", cuando veas esto deberías cambiarlo por tu usuario y password


si intentamos hacer push de nuestra couchapp de nuevo vamos a obtener un error que nos dice que no estamos autorizados, esto es porque necesitamos proveer usuario y contraseña para modificar la base de datos ahora, para hacer esto vamos a editar el archivo .couchapprc de nuevo para agregar el usuario y contraseña


edita la url de


http://localhost:5984/datos

a


http://wariano:secret@localhost:5984/datos

intenta hacer push de nuevo, debería funcionar. Intenta usar la demo de nuevo usando tu usuario y contraseña

[EN] CouchApp II: fixing the admin party

now that we have our app running we can see a problem in the demo, we don't have authentication, and by default couchdb is in "admin party" mode, read more about the admin party in Couchdb the definitive guide


to fix this we need to go to futon (the admin panel of couchdb) and set up the first admin


go to futon pointing your browser to http://localhost:5984/_utils/index.html


at the bottom right corner of the page you should read something like "Welcome to Admin Party! Everyone is admin. Fix this", click on the link and set the first admin


I will create the admin as "wariano" and password "secret", whenever you see that change for your user and password


if we try to push our couchapp again we will get an unauthorized error, that's because we need to provide credentials to modify the database now, to do this we will edit the .couchapprc again to add the user and password


edit the url from


http://localhost:5984/datos

to


http://wariano:secret@localhost:5984/datos

and try pushing again it should work now, try the demo again using your user and password

CouchApp I: instalando el entorno

vamos a empezar nuestra couchapp instalando el entorno, para eso necesitamos instalar couchapp y couchdb


# instalar couchdb y los modulos de python para poder instalar otros modulos
sudo apt-get install python-setuptools couchdb
# descargar pip
curl -O http://python-distribute.org/distribute_setup.py
sudo python distribute_setup.py
sudo easy_install pip
# instalar couchapp
sudo pip install couchapp

ahora que tenemos couchapp vamos a generar nuestro proyecto, vamos a llamarlo "datos"


couchapp generate datos
cd datos
# editamos el archivo couchapprc
vim .couchapprc

el archivo .couchapprc contiene los destinos donde vamos a instalar nuestra aplicación, definamos el target por defecto


{"env": {
  "default": {
   "db": "http://localhost:5984/datos"
  }
 }
}

guardar el contenido y correr


couchapp push

deberia mostrar algo como lo siguiente:


2010-10-22 10:21:10 [INFO] Visit your CouchApp here:
http://localhost:5984/datos/_design/datos/index.html

ahora anda a esa URL con tu browser, deberías ver la pagina de demostración.

[EN] CouchApp I: setting up the environment

we will start our couchapp setting up the environment, for that we will install couchdb and couchapp


# install couchdb and python modules to install other modules
sudo apt-get install python-setuptools couchdb
# download pip
curl -O http://python-distribute.org/distribute_setup.py
sudo python distribute_setup.py
sudo easy_install pip
# install couchapp
sudo pip install couchapp

now that we have couchapp we will generate our project, we will call it "datos"


couchapp generate datos
cd datos
# edit the couchapprc file
vim .couchapprc

the .couchapprc file contains the targets where we can deploy our application, let's define the default target


{"env": {
  "default": {
   "db": "http://localhost:5984/datos"
  }
 }
}

save the content and run


couchapp push

it should display something like the following:


2010-10-22 10:21:10 [INFO] Visit your CouchApp here:
http://localhost:5984/datos/_design/datos/index.html

now go to that site with your browser, you should see a demo page.

Seguidores

Archivo del Blog