web2py: Deploy specific app with Apache Webserver

If you want to deploy a web2py app as an alias in Apache Webserver, you need configure your directive in httpd.conf as follows:

<VirtualHost *:80>
    DocumentRoot /var/www/html
    ServerName www.domain.com
    ServerAlias domain.com *.domain.com
    <Directory /var/www/html>
        Options FollowSymLinks
        AllowOverride All
    </Directory>

    RewriteEngine On
    RewriteCond %{REQUEST_URI} ^/myapp.* [NC]
    RewriteRule ^/(.*) /myapp/$1 [PT,L]
    WSGIScriptAlias /myapp /opt/web2py/wsgihandler.py
</VirtualHost>

It’s common that a bad configuration raise the exception: RuntimeError: Using a recursive select but encountered a broken reference: auth_group 1 when you try to login. Although it work properly with the built-in webserver (./python web2py.py …)

As defined in their official page of web2py it’s a:

Free open source full-stack framework for rapid development of fast, scalable, secure and portable database-driven web-based applications. Written and programmable in Python.


Python: if statements, several ways.

I want to explain some ways to perform if in Python.

For this example, we will consider adult people over 18, otherwise, are children.

1) Basic way

#Option A
if age >= 18:
  typeOfPerson = "adult"
else:
  typeOfPerson = "child"

We can assign a default value and change it only if a condition is met.

#Option B
typeOfPerson = "child" #default value
if age >= 18:
  typeOfPerson = "adult"

Option A is better than option B for code optimization, assuming that the probability of either is not very far (Thanks to Arturo Moysen for this comment).

2) Inline if (result = x if condition else y)

typeOfPerson = "adult" if age >= 18 else "child"

3) Inline if (result = condition and x or y)

typeOfPerson = age >= 18 and "adult" or "child"

4) Inline with tuple, (on_false, on_true)[condition]

typeOfPerson = ("child", "adult")[age >= 18]

Condition can be anything that evaluates to a Boolean. It is then treated as an integer since it is used to index the tuple: False == 0, True == 1, which then selects the right item from the tuple.


Conferencia: Tecnologías del momento para el desarrollo ágil de aplicaciones, UNID.

El día de hoy di una conferencia sobre las tecnologías más recientes para el desarrollo de aplicaciones móviles y web, además de tocar temas como: Frameworks, Control de Versiones, Administración de Proyectos con SCRUM y un poco de optimización con Memcached.

Aquí les dejo la presentación para descargar.

Conferencia: Tecnologías del momento para el desarrollo ágil de aplicaciones

Extract mail addresses from html webpage with Python

This is a very simple script in Python to perform this operation:

import urllib2
response = urllib2.urlopen('http://server.com/section/page.html') //or php, aspx or anything
html = response.read()
import re
mailsrch = re.compile(r'[\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4}')
found = []
found.extend(mailsrch.findall(html))
print found

MySQL LDAP Authentication Plugin (Clear password client plugin)

Based on my last post MySQL LDAP Authentication Plugin, I received feedback from MySql Joro Blog by Oracle.

They told me:

Insted of writing (and having to deply) your own client plugin you probably can reuse the cleartext client side plugin, specially because it’s available in a number of mysql clients already. Check sql-common/client.c on MySQL 5.5+ for details.

This is very useful because you only need to put the plugin in server side, and in the client side you only need to check if the clear password plugin is enabled.

Now, I present the updated code with the only server side plugin, and I reused the cleartext client side plugin from MySql, it’s more short and very focused in LDAP authentication:

(continue reading…)


MySQL LDAP Authentication Plugin

As a continuation of previous post, now, I will show how to make a mysql plugin for ldap authentication.

Get the mysql-server source code at http://dev.mysql.com/downloads/mysql/ (http://dev.mysql.com/get/Downloads/MySQL-5.5/mysql-5.5.27.tar.gz/from/http://cdn.mysql.com/)

Installing necessary packages

yum groupinstall 'Development Tools'
yum install cmake ncurses-devel

Download source code, build and start MySQL Server

wget http://dev.mysql.com/get/Downloads/MySQL-5.5/mysql-5.5.27.tar.gz/from/http://cdn.mysql.com/
tar -xzf mysql-5.5.27.tar.gz
cd mysql-5.5.25

# Preconfiguration setup
groupadd mysql
useradd -r -g mysql mysql

# Beginning of source-build specific instructions
cmake .
make
make install

# Postinstallation setup
chown -R mysql .
chgrp -R mysql .
./scripts/mysql_install_db --user=mysql
chown -R root .
chown -R mysql data

cp support-files/mysql.server /etc/init.d/mysql.server

# Start mysql server
/etc/init.d/mysql.server start

Goal 1) The first version of the plugin must should allow user authentication with password.

(continue reading…)


LDAP C Client Authentication Example (with OpenLDAP)

I have the goal of authenticate MySQL users with an LDAP server, currently, employees of my company are authenticated in several services (ftp, ssh, svn) through my LDAP server, except MySQL. (As you can imagine, I need to add manually every user in MySQL, a very tedious task).

In this post I only leave the example with LDAP authentication.

Installing necessary packages


yum groupinstall 'Development Tools'
yum install openldap-devel

Source ldapClient.c

#include <stdio.h>
#include <ldap.h>
/* LDAP Server settings */
#define LDAP_SERVER "ldap://nafiux.com:389"
int
main( int argc, char **argv )
{
LDAP        *ld;
int        rc;
char        bind_dn[100];

/* Get username and password */
if( argc != 3 )
{
perror( "invalid args, required: username password" );
return( 1 );
}
sprintf( bind_dn, "cn=%s,ou=People,dc=nafiux,dc=com", argv[1] );
printf( "Connecting as %s...\n", bind_dn );

/* Open LDAP Connection */
if( ldap_initialize( &ld, LDAP_SERVER ) )
{
perror( "ldap_initialize" );
return( 1 );
}

/* User authentication (bind) */
rc = ldap_simple_bind_s( ld, bind_dn, argv[2] );
if( rc != LDAP_SUCCESS )
{
fprintf(stderr, "ldap_simple_bind_s: %s\n", ldap_err2string(rc) );
return( 1 );
}
printf( "Successful authentication\n" );
ldap_unbind( ld );
return( 0 );
}

Compile and build

gcc ldapClient.c -o ldapClient -lldap

Run


Aumentar tamaño de Partición en VirtualBox

Si alguna ves te pasó (como a mí) que instalé Windows 7 (o cualquier S.O.) con una espacio en Disco Duro reducido para hacer pruebas, y después de trabajar mucho te das cuenta que el espacio ya no te alcanzo, lo menos que quieres hacer es volver a instalarlo con todas las aplicaciones y configuración nuevamente.

La solución es la siguiente:

  1. Añade un disco con mayor capacidad a tu Máquina Virtual (aparte del que ya tienes instalado, por ejemplo, mi disco duro virtual era de 20GB, le agregué otro de 50GB)
  2. Descarga la última versión del LiveCD de GParted (http://gparted.sourceforge.net/)
  3. Configurar la máquina Virtual, para que inicie desde el CD (debes configurar al CD para que cargue la imagen de GParted)
  4. Configuración en GParted
    1. En el nuevo disco duro, crea una nueva partición de tipo MSDOS
    2. Del primer disco duro (el de menor capacidad) copia cada partición y pégala en el nuevo disco duro
  5. En la máquina Virtual, remueve el disco duro anterior (no lo elimines aún por seguridad)
  6. Pone el disco duro como primera opción de arranque

Es probable, que cuando inicies la máquina el S.O. (en mi caso con Windows 7) marcó un error de Boot, ya que normalmente una instalación tiene 2 particiones (una es el boot y la otra el espacio de almacenamiento en si), para reparar eso, inicia la máquina virtual desde una imagen ISO de Windows 7 y en lugar de instalar da clic en la opción de Reparar, automáticamente detectará el error, te pedirá reiniciar y listo.

Ahora disfruto de 20 GB libres :)

La misma explicación pero en Inglés y con imágenes: http://www.my-guides.net/en/content/view/122/26/


Virus USB: Archivos Ocultos y Accesos Directos (.lnk)

Clic para descargar herramienta

Existe un virus muy común que afecta a Dispositivos de Almacenamientos USB para Sistemas Operativos Windows, que oculta los archivos y carpetas y genera muchos archivos de accesos directo (.lnk).

Hice un Script en VBScript (archivo .vbs) que de manera automática restaura los archivos que el virus ocultó y elimina los archivos de acceso directo (.lnk).

Para utilizar el Script, debes descargar el archivo, descomprimirlo y copiar el archivo que se llama HerramientaArchivos.vbs a la USB (Dispositivo de Almacenamiento), una vez que el archivo está en la memoria (en la raíz), solo debes ejecutarlo (Darle doble clic)

El Script es seguro, si deseas ver el contenido puedes abrirlo con el Bloc de Notas. Te agradecería reportaras si algo no te funciona o si haces una mejora al Script para compartira con la comunidad.

(continue reading…)


CakePHP: View to PDF

I was working on a system that needed generate a PDF report of a view, I solved it as follows:

function report_view() {
	...
	$this->render();
	require_once ('vendors/dompdf/dompdf_config.inc.php'); // import dompdf library
	$dompdf = new DOMPDF();
	$dompdf->load_html($this->output);
	$dompdf->set_paper("a4", "landscape" );
	$dompdf->render();
	$dompdf->stream('ReportExample_'.date('d_M_Y').'.pdf');
	exit(0);
}

You can see, that I used “$this->output” as parameter of load_html to get the output of the view.

I used the dompdf library.


  • Categorías

  • Twitter

  • Copyright © 2009-2011 nafiux.com Blog. All rights reserved.
    iDream theme by Templates Next | Powered by WordPress