domingo, 4 de marzo de 2012

[ en ] Working with node.js and MySQL




This is a small article about how to use node.js as web server to display the results of a query to a MySQL database engine.
The first thing to do is to check is that we have installed the mysql module to run it the following:

lucaMac:BLOG_POSTs pepo$ node
> var Client = require('mysql').Client
Error: Cannot find module 'mysql'
at Function._resolveFilename (module.js:332:11)
at Function._load (module.js:279:25)
at Module.require (module.js:354:17)
at require (module.js:370:17)
at repl:1:14
at REPLServer.eval (repl.js:80:21)
at repl.js:190:20
at REPLServer.eval (repl.js:87:5)
at Interface. (repl.js:182:12)
at Interface.emit (events.js:67:17)
> 
If fails, proceed to install the module via npm:

npm install mysql



The first thing we do is create the object for the query:

var Client = require('mysql').Client,
client = new Client();
client.user = 'user';
client.password = 'password';
client.host='127.0.0.1';
client.port='3306';
client.database='database_name'
client.connect();

then create the web server


var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});

And within this we perform the query, and associate to its callback function

client.query(
"select * from table where campo1 > 1 limit 10;",    
function select(err, results, fields) {
if (err) {
console.log("Error: " + err.message);
throw err;
}
print data to the console and the web response


console.log("Number of rows: "+results.length);
console.log(results);


for (var i in results){

var result = results[i];
res.write(result.campo1+"\n");
}

res.end();
});
We finished the code, setting up a port for listening

}).listen(1337, "0.0.0.0");
console.log('Server running ');


The finished script is like this:

var Client = require('mysql').Client,
client = new Client();
client.user = 'user';
client.password = 'password';
client.host='127.0.0.1';
client.port='3306';
client.database='DB'
client.connect();


var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});


client.query(
"select * from table where campo1 > 1 limit 10;",    
function select(err, results, fields) {
if (err) {
console.log("Error: " + err.message);
throw err;
}
console.log("Number of rows: "+results.length);
console.log(results);
res.write(results);

for (var i in results){

var result = results[i];
res.write(result.campo1+"\n");
}
res.end();
});

}).listen(1337, "0.0.0.0");
console.log('Server running ');
If you want to download this is the link to the   gist

jueves, 1 de marzo de 2012

[en] node.js + socket.IO + mongoDB = real time apps Part 1




Part 1: Setting the environment ....

A few days ago I finished a simple application tweetland.com.ar I made in order to learn more about Node.js and MongoDB ... on the road I also came across Socket.IO which is a great library for real time applications.
The first is to prepare the environment. To do this first download node.js (from node.js ), after downloading the installation follows the traditional steps:
./configure
make
make install *
* the last step as root Once installed, continue with the installation of modules. For this node has npm (which is Node Package Manager) that allows us to install the modules with a single command install npm . Instructions for installing npm are in your home page, also I leave
curl http://npmjs.org/install.sh | sh
At this time we have installed both node.js as its package manager npm. Usually what I usually do is create a directory in my case I call nodeapps as workspace.
Entering the same:
cd "path to nodeapps"
and within it begin to install the modules you require. This is important because when you install the modules npm node_modules create the directory (if not there before), and install the modules in that directory.
This is important because when we do within our code something like:
var sys = require('sys');
node will automatically search the directory sys module within node_modules in the current directory and not finding it will continue with the search recursively upwards, which is always important to remember where you installed the modules that we use.

Before going further make the installation of some modules used, these are express, socket.io, mongoose.

And this is precisely the last module we will use to interact with our database MongoDB, which is an object-oriented database (JSON), high performance and scalable. (in another post I will explain a little more how it works because it is a relatively new and very interesting).
To install you have to download the appropriate version from download , and once discharged, proceed to decompress

 pepo@sokol:~/DESARROLLO/POSTS/node_socket_mongo$ wget http://fastdl.mongodb.org/linux/mongodb-linux-i686-2.0.2.tgz

2012-02-28 11:42:19 (1.06 MB/s) - `mongodb-linux-i686-2.0.2.tgz' saved [38157227/38157227]

pepo@sokol:~/DESARROLLO/POSTS/node_socket_mongo$ tar -xzf mongodb-linux-i686-2.0.2.tgz
Once unpacked and could start the service mongod and start, but I'd rather create the directory structure I will use my base, create two directories for data and logs, the first store the files of the database and the second of logs. I also create the configuration file with which I will start the service, in my case is as follows:
cat mongod.config 

dbpath = /home/pepo/nodeapps/data/
logpath =/home/pepo/nodeapps/logs/mongodb.log
bind_ip = 127.0.0.1
noauth = true 
verbose = true 
 Bind_ip option is set to only listen on localhost requests (since by default it does on all interfaces) and indicate that we will not configure the authentication and verbose.

To start the service simply run:
bin/mongod --config mongod.config *
* Inside the unzipped directory MongoDB

we see something like this:
 # mongodb-linux-i686-2.0.2/bin/mongod --config mongod.config 
all output going to: ./logs/mongodb.log
Finally to test the service entered as follows (always from the binary directory MongoDB):
pepo@sokol:bin$ ./mongo
MongoDB shell version: 2.0.2
connecting to: test
> show dbs
local    (empty)
Well, with this we have our environment set up and configured to start programming applications in node.js with MongoDB, but that will be for the next post....
  

martes, 28 de febrero de 2012

node.js + socket.IO + mongoDB = real time apps (parte 1)




Parte 1: Preparando el ámbiente....

Hace unos días terminé una simple aplicación tweetland.com.ar que realicé con el objetivo de aprender (existe otro?) más sobre Node.js y mongoDB... en el camino también me topé con Socket.IO que es una gran librería para realizar aplicaciones en tiempo real.

Lo primero es preparar el ambiente, para ello primero descargamos node.js (desde su home page node.js), una vez descargado la instalación sigue los pasos tradicionales:
./configure
make
make install *
* este último como root
Una vez instalado, seguimos con la instalación de módulos. Para ello node cuenta con npm (que es Node Package Manager) que nos permite instalar los módulos con un simple comando npm install . Las instrucciones para instalar npm están en su home page, igualmente se las dejo:
curl http://npmjs.org/install.sh | sh
En este momento ya tenemos instalado tanto node.js como su manejador de paquetes npm. Por lo general lo que suelo hacer es crear un directorio, en mi caso lo llamo nodeapps, como workspace.
Ingreso al mismo:
cd "path to nodeapps"
y dentro de él comienzo a instalar los modulos que requiero. Esto es importante porque al instalar los modulos npm creará el directorio node_modules (siempre y cuando no exista antes), e instalará los modulos en dicho directorio.
Y esto es importante porque cuando dentro de nuestro código hagamos algo como:
var sys = require('sys');
node automáticamente buscará el módulo sys dentro de directorio node_modules en el directorio actual y de no encontrarlo seguira con la busqueda recursiva hacia arriba, por lo cual siempre es importante tener en mente donde se instalán los módulos que vamos a utilizar.

Antes de seguir adelante realicen la instalación de algunos módulos que utilizaran, estos son express, socket.io, mongoose .

Y este último módulo es justamente el que utilizaremos para interactuar con nuestra base de datos mongoDB, que es una base orientada a objetos (JSON), de alta performance y escalable. (en otro post explicaré un poco más como funciona ya que es una tecnología relativamente nueva y muy interesante).
Para realizar la instalación tenemos que descargar la versión que corresponda desde mongoDB download , y una vez descargada la descomprimimos

 pepo@sokol:~/DESARROLLO/POSTS/node_socket_mongo$ wget http://fastdl.mongodb.org/linux/mongodb-linux-i686-2.0.2.tgz

2012-02-28 11:42:19 (1.06 MB/s) - `mongodb-linux-i686-2.0.2.tgz' saved [38157227/38157227]

pepo@sokol:~/DESARROLLO/POSTS/node_socket_mongo$ tar -xzf mongodb-linux-i686-2.0.2.tgz
Una vez descomprimido ya podríamos arrancar el servicio mongod y comenzar, pero antes prefiero crear la estructura de directorios que utilizaré con mi base, para eso creo dos directorios data y logs, el primero guardará los archivos de la base de datos y el segundo los archivos de logs. También creo el archivo de configuración con el que voy a levantar el servicio, en mi caso tiene la siguiente forma:
cat mongod.config 

dbpath = /home/pepo/nodeapps/data/
logpath =/home/pepo/nodeapps/logs/mongodb.log
bind_ip = 127.0.0.1
noauth = true 
verbose = true 
 La opción bind_ip está configurada para que sólo escuche las peticiones sobre el localhost (ya que por defecto lo hace sobre todas las interfaces) e indicamos que no tendremos autenticación y configuramos el verbose.

Para levantar el servicio simplemente ejecutamos:
bin/mongod --config mongod.config *
* Dentro de directorio descomprimido de mongoDB

Y veremos algo como:
 # mongodb-linux-i686-2.0.2/bin/mongod --config mongod.config 
all output going to: ./logs/mongodb.log

Por último para probar  el servicio ingresamos de la siguiente forma (siempre desde el directorio de binarios de mongoDB):
pepo@sokol:bin$ ./mongo
MongoDB shell version: 2.0.2
connecting to: test
> show dbs
local    (empty)
Bueno, y con esto ya tenemos nnuestro entorno instalado y configurado para comenzar a programar aplicaciones en con node.js con mongoDB, pero eso quedará para la próxima....

  

domingo, 12 de febrero de 2012

5 buenas herramientas para probar sitios móviles

En este tiempo de diversas resoluciones de pantallas es cada vez más importante poder contar con buenas herramientas para probar facilmente como se un sitio en diferentes dispositivos, en este link les dejo 5 muy buenas herramientas que facilitan esa tarea.

http://bit.ly/xA20TT

miércoles, 28 de septiembre de 2011

DJANGO_SETTINGS_MODULE... The simplest way to configure!

Looking for simple and efficient way to configure my environment to develop different django apps, and set the environment variable DJANGO_SETTINGS_MODULE on the fly, I found this function to bash us greatly simplifies our work.
You just have to edit and add user bash_profile
function setdsm() {
# add the current directory and the parent directory to PYTHONPATH
# sets DJANGO_SETTINGS_MODULE
export PYTHONPATH=$PYTHONPATH:$PWD/..
export PYTHONPATH=$PYTHONPATH:$PWD
if [ -z "$1" ]; then
x=${PWD/\/[^\/]*\/}
export DJANGO_SETTINGS_MODULE=$x.settings
else
export DJANGO_SETTINGS_MODULE=$1
fi

echo "DJANGO_SETTINGS_MODULE set to $DJANGO_SETTINGS_MODULE"
}
And then from our project directory run:
user$ setdsm

I hope this functios will be as as useful for you as is for me.

Link to source

lunes, 6 de junio de 2011

Dump object attributtes python

Una forma simple de hacer debuging es dumpear los atributos de los obejtos que manejemos, que en el caso de python la forma más simple es:

print object.__dict__

El cual nos imprimirá el diccionario de atributos del objeto en cuestión.-

domingo, 5 de junio de 2011

Cast an ArrayList to an Array of strings (android)

Me topé con la necesidad de catear un arraylist a un array de strings desarrollando una app para android, por suerte luego de una simple búsqueda encontre la fomar más simple de realizarlo :D

String [] myStringsArray = myArrayList.toArray(new String[myArrayList.size()]);

Lección aprendidad para un domingo :D