how to implement database tables with one level of indirection?

https://groups.google.com/group/web2py/browse_thread/thread/92e4df0cdacd4c0f/0bc28218823b93d1?hl=es&lnk=gst&q=profile#0bc28218823b93d1

Hello!

How do I make a database table where the fields are defined by another
table?

For example, suppose some users of my system are event organizers, and they
can define what fields would belong in a person’s profile.

Then, attendees of that event have to fill out a profile with those specific
fields.

What is the best way to represent this information (the fields relevant for
an event’s profile,  and the event profiles of users) in a database?

What I have been thinking of so far is to define a table that holds the
definitions of profile fields:

db.define_table(‘event_profile_field’,
    Field(‘event’, db.event),
    Field(‘display_title’,'text’),
    Field(‘data_type’,
requires=IS_IN_SET(‘string’,'text’,'checkbox’,'list’)),
    Field(‘display_order’, ‘int’))

and then each user’s profile is built up of multiple entries of the
following:

db.define_table(‘event_profile_entry’,
    Field(‘person’, db.person),
    Field(‘event’, db.event),
    Field(‘event_profile_field’, db.event_profile_field),
    Field(‘data’) # XXX we need data to be of different types

However, as indicated above by the comment, I’m not sure if it is possible
to store different data types in the event_profile_entry.data field.
(I suppose I could just make it be ‘text’ type and have the code know that a
checkbox can only be True or False, for example).

Is there a more efficient/smarter way to do this?

Thanks,
Luis.


    Responder     Responder al autor      Reenviar       

Richard Vézina  
Ver perfil   Traducir al Español
 Más opciones 4 jul, 17:38
    Responder     Responder al autor      Reenviar       

Luis Goncalves  
Ver perfil   Traducir al Español
 Más opciones 5 jul, 01:17

 

Hello Richard!

I looked at this, but wasn’t sure how it could help — what I need is a way
for a (non-technical) admin to create profile forms with arbitrary fields
(through a friendly web interface), and then users to be able to view and
edit their (run-time reconfigurable) profiles.

At any rate, the method I described above seems to work quite well,  thanks
to web2py’s versatility, allowing me to define forms programmatically
(excerpt below).

I was wondering if there was a more clever/efficient/proper way to do so.
Perhaps not!

Thanks!!
Luis.

    for field in event_fields:
          # see if person has a pre-defined value
          found = False
          for my_efield in me.event_field:
              if my_efield.display_title == field.display_title:
                  found = True
                  break

          if found:
              if field.data_type == ‘string’:
                  new_input = INPUT(_type = field.data_type, _name =
field.id, requires=IS_NOT_EMPTY(), _value=my_efield.data )
                  form[0].insert(-2, TR(field.display_title+’:', new_input
))

              elif  field.data_type == ‘text’:
                    …..
          else:
              if field.data_type == ‘string’:
                  new_input = INPUT(_type = field.data_type, _name =
field.id, requires=IS_NOT_EMPTY())
                  form[0].insert(-2, TR(field.display_title+’:', new_input
))

              elif field.data_type == ‘text’:
                   ….


    Responder     Responder al autor      Reenviar       

Richard Vézina  
Ver perfil   Traducir al Español
 Más opciones 5 jul, 01:54

Maybe you could find some inspiration from this project for Django :

http://code.google.com/p/django-dynamic-formset/

You need to install Django to test it…

What you seems to do is adding an arbitrary number of input for a given
field…

Following good database design pratice you will normalise your schema… I
had try to find a solution similar to django dynamic formset, but I give up
in the pass.

You have this thread that could maybe bring some answer :
http://groups.google.com/group/web2py/browse_thread/thread/50af0d6755…

Web2py let you do this :
http://www.web2py.com/book/default/chapter/07?search=filter#One-form-…

But you can’t have fields with the same name in your table…

Finally it maybe possible with component now to load a arbitrary number of
fields inputs for a given table and with jQuery submit the differents forms
as one I would investigate in that direction too…

Good luck

Richard


    Responder     Responder al autor      Reenviar       

Luis Goncalves  
Ver perfil   Traducir al Español
 Más opciones 5 jul, 02:30

Thanks for the links!!

Django dynamic formsets seems powerful!  When I first started off, I
investigated using django, but found it very difficult.  Web2py is so much
easier to use (especially with the clear manual, and “one click” install
with working apps (‘Welcome’))!!!

Maybe I’ll end up contributing a friendly dynamic form creator for web2py

merci,
Luis.

On Mon, Jul 4, 2011 at 4:54 PM, Richard Vézina
<ml.richard.vez@gmail.com>wrote:


    Responder     Responder al autor      Reenviar       

Richard Vézina  
Ver perfil   Traducir al Español
 Más opciones 5 jul, 02:38

It surely a missing feature…

Richard

On Mon, Jul 4, 2011 at 8:30 PM, Luis Goncalves <l@vision.caltech.edu>wrote:


    Responder     Responder al autor      Reenviar       

Bruno Rocha  
Ver perfil   Traducir al Español
 Más opciones 5 jul, 03:19

The web2py app wizard has a Dynamic model creator, may be you can take a
look in to the wizard code. And fork as a plugin.

On Mon, Jul 4, 2011 at 9:38 PM, Richard Vézina
<ml.richard.vez@gmail.com>wrote:



Bruno Rocha
[ About me: http://zerp.ly/rochacbruno ]
[ Aprenda a programar: http://CursoDePython.com.br ]
[ O seu aliado nos cuidados com os animais: http://AnimalSystem.com.br ]
[ Consultoria em desenvolvimento web: http://www.blouweb.com ]


    Responder     Responder al autor      Reenviar       

Richard Vézina  
Ver perfil   Traducir al Español
 Más opciones 5 jul, 16:23

I thougth about it too, but I didn’t find the thread…

;-)

Richard


    Responder     Responder al autor      Reenviar       

     
Anthony  
Ver perfil   Traducir al Español
 Más opciones 5 jul, 16:51

 

That type of method will work, but it will result in a new database table
being created for each event/custom profile. There are various alternatives
for implementing user defined fields — here are some Stackoverflow links:

http://stackoverflow.com/questions/5106335/how-to-design-a-database-f…
http://stackoverflow.com/questions/4151468/how-to-store-custom-user-f…
http://stackoverflow.com/questions/2924027/db-design-to-store-custom-.

0

0
 

Creacion de grupos de usuarios y miembros: UserGroups: Extend Auth_Group or Table Inheritance?

Anaconda  
Ver perfil   Traducir al Español
 Más opciones 21 ago, 07:20
I am looking to allow users to create their own groups and have
members. Which is more effecient:

Table Inheritance:
db.define_table(‘user_groups’, db.auth_group,
Field(‘name’) ………..ect…….))

or
Extend auth_group:

db.define_table(
   auth.settings.table_user_group,
  Field(‘role’, length=512, default=”,
label=auth.messages.label_role),
  Field(‘description’, ‘text’,
label=auth.messages.label_description),
  Field(‘name’, length=128, default=”, unique=True))

custom_auth_group = db[auth.settings.table_user_group]

# auth.define_tables()

Thanks in advance for any help!!


     
Massimo Di Pierro  
Ver perfil   Traducir al Español
 Más opciones 21 ago, 10:27
The question is: do you use a auth_groups to manage internal working
of the app or not? For example to you have user roles like “manager”
or “admin” etc. If so you may want to expose a different mechanism to
users. If you can use auth_groups (because you are not using it
already or you you plan to add checks to avoid conflicts, by all
means, you should use that, as it will save work later.

Massimo

 

0

0
 

Multiples aplicaciones

Multiples aplicaciones – web2py-usuarios | Grupos de Google:
Hola,

tengo hosting en webfaction y corriendo dos aplicaciones web2py desde
hace 4-5 meses. Hoy subí una tercera y en apache pongo lo mismo que en
las otras dos:

<VirtualHost 127.0.0.1:44051>
  ServerName undominio.com.ar
  ServerAlias www.undominio.com.ar

  RewriteEngine On
  RewriteRule ^/$ /miaplicacion3/ [R]

  <LocationMatch “^(/[\w_]*/static/.*)”>
    Order Allow,Deny
    Allow from all
  </LocationMatch>

  <Location “/”>
    Order Deny,Allow
    Allow from all
  </Location>
</VirtualHost>

el problema que tengo en que cuando entro me devuelve “invalid
controller”.
Si cambio RewriteRule ^/$ /miaplicacion3/ [R] por RewriteRule ^/$ /
miaplicacion1/ [R]
funciona bien e ingresa a la aplicación1.

Probé con crear una nueva aplicación y subirla tal como la crea y
también me da el mismo mensaje.

La duda es saber si ha cambiado algo en web2py con los esqueletos de
aplicaciones que crea ahora respecto a los de hace unos meses.

Alguna idea de lo que está sucediendo.

Saludos
Jose


    Responder al autor     Reenviar       

    Calificar esta entrada: Text for clearing space

Debes registrarte antes de enviar mensajes.
Para enviar una entrada, antes deberás formar parte del grupo.
Antes de enviar entradas, actualiza tu alias en la configuración de la suscripción.
No dispones del permiso necesario para enviar entradas.

Mariano Reingart  
Ver perfil   Traducir al Español Traducido (ver original)
 Más opciones 10 mar, 17:30
De: Mariano Reingart <reing@gmail.com>
Fecha: Wed, 10 Mar 2010 13:30:05 -0300
Local: Mié 10 mar 2010 17:30
Asunto: Re: Multiples aplicaciones

2010/3/10 Jose <jjac@gmail.com>:

- Mostrar texto de la cita -

Como lo estas utilizando, con WSGI, FASTCGI, mod_proxy, etc…?

Sds

Mariano Reingart
http://www.web2py.com.ar
http://reingart.blogspot.com


    Responder al autor     Reenviar       

    Calificar esta entrada: Text for clearing space

Debes registrarte antes de enviar mensajes.
Para enviar una entrada, antes deberás formar parte del grupo.
Antes de enviar entradas, actualiza tu alias en la configuración de la suscripción.
No dispones del permiso necesario para enviar entradas.

Jose  
Ver perfil   Traducir al Español Traducido (ver original)
 Más opciones 10 mar, 18:32
De: Jose <jjac@gmail.com>
Fecha: Wed, 10 Mar 2010 09:32:17 -0800 (PST)
Local: Mié 10 mar 2010 18:32
Asunto: Re: Multiples aplicaciones

On 10 mar, 16:30, Mariano Reingart <reing@gmail.com> wrote:

> Como lo estas utilizando, con WSGI, FASTCGI, mod_proxy, etc…?

WSGI


    Responder al autor     Reenviar       

    Calificar esta entrada: Text for clearing space

Debes registrarte antes de enviar mensajes.
Para enviar una entrada, antes deberás formar parte del grupo.
Antes de enviar entradas, actualiza tu alias en la configuración de la suscripción.
No dispones del permiso necesario para enviar entradas.

Jose  
Ver perfil  
 Más opciones 10 mar, 18:39
De: Jose <jjac@gmail.com>
Fecha: Wed, 10 Mar 2010 09:39:58 -0800 (PST)
Local: Mié 10 mar 2010 18:39
Asunto: Re: Multiples aplicaciones

Podes probar en www.corraleslamagdalena.com.ar

esto redirecciona a: http://www.corraleslamagdalena.com.ar/lamagdalena/

cambiando
   RewriteRule ^/$ /lamagdalena/ [R] por:

RewriteRule ^/$ /examples/ [R] (nvalid
controller)

RewriteRule ^/$ /prueba/ [R] (nvalid
controller)

RewriteRule ^/$ /alguna_aplicacion_vieja/ [R] (funciona Ok)

fijate que examples se actualiza con hg pull (update) y yo lo tengo
actualizado, por eso pregunto si cambió en algo la estructura de una
app web2py.

Saludos


    Responder al autor     Reenviar       

    Calificar esta entrada: Text for clearing space

Debes registrarte antes de enviar mensajes.
Para enviar una entrada, antes deberás formar parte del grupo.
Antes de enviar entradas, actualiza tu alias en la configuración de la suscripción.
No dispones del permiso necesario para enviar entradas.

Mariano Reingart  
Ver perfil  
 Más opciones 10 mar, 18:41
De: Mariano Reingart <reing@gmail.com>
Fecha: Wed, 10 Mar 2010 14:41:13 -0300
Local: Mié 10 mar 2010 18:41
Asunto: Re: Multiples aplicaciones

On Wed, Mar 10, 2010 at 2:32 PM, Jose <jjac@gmail.com> wrote:

> On 10 mar, 16:30, Mariano Reingart <reing@gmail.com> wrote:

>> Como lo estas utilizando, con WSGI, FASTCGI, mod_proxy, etc…?

> WSGI

Y como lo estás configurando? en la configuración que pasaste no
aparece nada, tenes bien el WSGIScriptAlias y el wsgihandler.py?

Sds

Mariano Reingart
http://reingart.blogspot.com


    Responder al autor     Reenviar       

    Calificar esta entrada: Text for clearing space

Debes registrarte antes de enviar mensajes.
Para enviar una entrada, antes deberás formar parte del grupo.
Antes de enviar entradas, actualiza tu alias en la configuración de la suscripción.
No dispones del permiso necesario para enviar entradas.

Jose  
Ver perfil   Traducir al Español Traducido (ver original)
 Más opciones 10 mar, 18:47
De: Jose <jjac@gmail.com>
Fecha: Wed, 10 Mar 2010 09:47:50 -0800 (PST)
Local: Mié 10 mar 2010 18:47
Asunto: Re: Multiples aplicaciones

On 10 mar, 17:41, Mariano Reingart <reing@gmail.com> wrote:

> Y como lo estás configurando? en la configuración que pasaste no
> aparece nada, tenes bien el WSGIScriptAlias y el wsgihandler.py?

Mariano, antes de los virtual host tengo esto:

ServerRoot “/home/jjachuf/webapps/apachew2p/apache2″

LoadModule dir_module modules/mod_dir.so
LoadModule env_module modules/mod_env.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule mime_module modules/mod_mime.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule wsgi_module modules/mod_wsgi.so
#LoadModule ssl_module modules/mod_ssl.so

LoadModule alias_module modules/mod_alias.so
LoadModule authz_host_module modules/mod_authz_host.so

KeepAlive Off
Listen 44051

WSGIScriptAlias / /home/micuenta/web2py/wsgihandler.py

WSGIDaemonProcess web2py user=miusuario group=migrupo \
     home=/home/micuenta/web2py/ \
     processes=10 maximum-requests=500

NameVirtualHost 127.0.0.1:44051

aquí los tres VH (como dije los dos primeros funcionan pero el tercero
no)

por último esto:

LogFormat “%{X-Forwarded-For}i %l %u %t \”%r\” %>s %b \”%{Referer}i\”
\”%{User-Agent}i\”" combined
CustomLog logs/access_log combined
ServerLimit 5

Saludos


    Responder al autor     Reenviar       

    Calificar esta entrada: Text for clearing space

Debes registrarte antes de enviar mensajes.
Para enviar una entrada, antes deberás formar parte del grupo.
Antes de enviar entradas, actualiza tu alias en la configuración de la suscripción.
No dispones del permiso necesario para enviar entradas.

Mariano Reingart  
Ver perfil  
 Más opciones 10 mar, 19:01
De: Mariano Reingart <reing@gmail.com>
Fecha: Wed, 10 Mar 2010 15:01:46 -0300
Local: Mié 10 mar 2010 19:01
Asunto: Re: Multiples aplicaciones

- Mostrar texto de la cita -

Calculo que wsgihandler.py adentro esta apuntando correctamente a la
carpeta (o por defecto tomará /home/micuenta/web2py/)

Preguntas:
¿en el admin te aparece bien?
¿la carpeta/directorio no tiene ningún caracter especial en su nombre?
¿no hay links ni problemas de permisos?

Sds

Mariano Reingart
http://www.web2py.com.ar
http://reingart.blogspot.com


    Responder al autor     Reenviar       

    Calificar esta entrada: Text for clearing space

Debes registrarte antes de enviar mensajes.
Para enviar una entrada, antes deberás formar parte del grupo.
Antes de enviar entradas, actualiza tu alias en la configuración de la suscripción.
No dispones del permiso necesario para enviar entradas.

Jose  
Ver perfil  
 Más opciones 10 mar, 21:23
De: Jose <jjac@gmail.com>
Fecha: Wed, 10 Mar 2010 12:23:51 -0800 (PST)
Local: Mié 10 mar 2010 21:23
Asunto: Re: Multiples aplicaciones

On 10 mar, 18:01, Mariano Reingart <reing@gmail.com> wrote:

> On Wed, Mar 10, 2010 at 2:47 PM, Jose <jjac@gmail.com> wrote:
> Calculo que wsgihandler.py adentro esta apuntando correctamente a la
> carpeta (o por defecto tomará /home/micuenta/web2py/)

Nunca toqué wsgihandler.py

> Preguntas:
> ¿en el admin te aparece bien?

No lo uso porque en su momento no lo pude hacer funcionar (si, sobre
https) y después no lo necesité y no volví a darle bola.

> ¿la carpeta/directorio no tiene ningún caracter especial en su nombre?

nada raro, ni eñes, ni acentos, ni nada por el estilo

> ¿no hay links ni problemas de permisos?

los mismos que en las dos aplicaciones que sí funcionan.

> Sds

Gracias por tu tiempo.


    Responder al autor     Reenviar       

    Calificar esta entrada: Text for clearing space

Debes registrarte antes de enviar mensajes.
Para enviar una entrada, antes deberás formar parte del grupo.
Antes de enviar entradas, actualiza tu alias en la configuración de la suscripción.
No dispones del permiso necesario para enviar entradas.

Mariano Reingart  
Ver perfil  
 Más opciones 10 mar, 21:32
De: Mariano Reingart <reing@gmail.com>
Fecha: Wed, 10 Mar 2010 17:32:24 -0300
Local: Mié 10 mar 2010 21:32
Asunto: Re: Multiples aplicaciones

2010/3/10 Jose <jjac@gmail.com>:

- Mostrar texto de la cita -

¿Si pones toda URL (controlador y función, ej /app/default/index)
también te da error?

Mariano Reingart
http://reingart.blogspot.com


    Responder al autor     Reenviar       

    Calificar esta entrada: Text for clearing space

Debes registrarte antes de enviar mensajes.
Para enviar una entrada, antes deberás formar parte del grupo.
Antes de enviar entradas, actualiza tu alias en la configuración de la suscripción.
No dispones del permiso necesario para enviar entradas.

El asunto del debate ha cambiado a “Multiples aplicaciones (SOLUCIONADO)” de Jose

Jose  
Ver perfil  
 Más opciones 10 mar, 21:39
De: Jose <jjac@gmail.com>
Fecha: Wed, 10 Mar 2010 12:39:56 -0800 (PST)
Local: Mié 10 mar 2010 21:39
Asunto: Re: Multiples aplicaciones (SOLUCIONADO)

On 10 mar, 20:32, Mariano Reingart <reing@gmail.com> wrote:

> ¿Si pones toda URL (controlador y función, ej /app/default/index)
> también te da error?

Ya probé pero no funciona.

Cambié la definición del VH por esta:

<VirtualHost 127.0.0.1:44051>
  ServerName midominio.com.ar
  ServerAlias www.midominio.com.ar
  DocumentRoot /home/micuenta/web2py/applications/miaplicacion

  RewriteEngine On
  RewriteRule ^/$ /miaplicacion/ [R]

  <Directory />
    Options FollowSymLinks
    AllowOverride None
  </Directory>

  <Directory /home/jjachuf/webapps/apachew2p/>
    Options indexes FollowSymLinks MultiViews
    AllowOverride None
    Order Allow,Deny
    Allow from all
  </Directory>
</VirtualHost>

Ahora funciona!

Podrías decirme por qué algunas aplicaciones funcionan con el otro VH
y otras no.

Saludos

0

0
 

Sobreescribir Auth

[web2py:23284] how to override Auth:

how to override Auth

Sebastian E. Ovide
Thu, 04 Jun 2009 11:09:50 -0700

Hi all,

in db.py I'd like to extend Auth so that I can override some
methods... such as define tables... and maybe in the future make it
login using OpenID or facebook etc...

so I've extended Auth and and overrided define_tables... but I'm
getting an error on auth.define_tables()

any ideas ?

class MyAuth(Auth):
    def define_tables(self, migrate=True):
        """
        to be called unless tables are defined manually

        usages:

        auth.define_tables()                           # defines all
needed tables and table files UUID+'_auth_user.table',...

        auth.define_tables(migrate='myprefix_')        # defines all
needed tables and table files 'myprefix_auth_user.table',...

        auth.define_tables(migrate=False)              # defines all
needed tables without migration/table files

        """

        db = self.db
        if not self.settings.table_user:
            password = self.settings.password_field
            self.settings.table_user = db.define_table(
                self.settings.table_user_name,
                db.Field('first_name', length=128,default=''),
                db.Field('last_name', length=128,default=''),
                db.Field('location', length=128,default=''),
                db.Field('email', length=128,default=''),
                db.Field(password, 'password', readable=False,
                         label='Password'),
                db.Field('registration_key', length=128,
                         writable=False, readable=False, default=''),

migrate=self.__get_migrate(self.settings.table_user_name, migrate))
            table = self.settings.table_user
            table.first_name.requires = IS_NOT_EMPTY()
            table.last_name.requires = IS_NOT_EMPTY()
            table[password].requires = CRYPT()
            table.email.requires = [IS_EMAIL(), IS_NOT_IN_DB(db, '%s.email'
                                 % self.settings.table_user._tablename)]
            table.registration_key.default = ''
        if not self.settings.table_group:
            self.settings.table_group = \
                db.define_table(self.settings.table_group_name,
                                db.Field('role', length=128,default=''),
                                db.Field('description', 'text'),

migrate=self.__get_migrate(self.settings.table_group_name, migrate))
            table = self.settings.table_group
            table.role.requires = IS_NOT_IN_DB(db, '%s.role'
                 % self.settings.table_group._tablename)
        if not self.settings.table_membership:
            self.settings.table_membership = \
                db.define_table(self.settings.table_membership_name,
                                db.Field('user_id',
                                self.settings.table_user),
                                db.Field('group_id',
                                self.settings.table_group),

migrate=self.__get_migrate(self.settings.table_membership_name,
migrate))
            table = self.settings.table_membership
            table.user_id.requires = IS_IN_DB(db, '%s.id'
                 % self.settings.table_user._tablename,
                '%(id)s: %(first_name)s %(last_name)s\
')
            table.group_id.requires = IS_IN_DB(db, '%s.id'
                 % self.settings.table_group._tablename,
                '%(id)s: %(role)s')
        if not self.settings.table_permission:
            self.settings.table_permission = \
                db.define_table(self.settings.table_permission_name,
                                db.Field('group_id',self.settings.table_group),
                                db.Field('name', default='default'),
                                db.Field('table_name'),
                                db.Field('record_id', 'integer'),

migrate=self.__get_migrate(self.settings.table_permission_name,
migrate))         <----------- error here *******
            table = self.settings.table_permission
            table.group_id.requires = IS_IN_DB(db, '%s.id'
                 % self.settings.table_group._tablename,
                '%(id)s: %(role)s')
            table.name.requires = IS_NOT_EMPTY()
            table.table_name.requires = IS_IN_SET(self.db.tables)
            table.record_id.requires = IS_INT_IN_RANGE(0, 10 ** 9)
        if not self.settings.table_event:
            self.settings.table_event = db.define_table(
                self.settings.table_event_name,
                db.Field('time_stamp', 'datetime',
                         default=self.environment.request.now),
                db.Field('client_ip',
                         default=self.environment.request.client),
                db.Field('user_id', self.settings.table_user,
                         default=None),
                db.Field('origin', default='auth'),
                db.Field('description', 'text', default=''),

migrate=self.__get_migrate(self.settings.table_event_name, migrate))
            table = self.settings.table_event
            table.user_id.requires = IS_IN_DB(db, '%s.id'
                 % self.settings.table_user._tablename,
                '%(id)s: %(first_name)s %(last_name)s\
')
            table.origin.requires = IS_NOT_EMPTY()
            table.description.requires = IS_NOT_EMPTY()

auth=MyAuth(globals(),db)            # authentication/authorization
auth.define_tables()               # creates all needed tables


Traceback (most recent call last):
  File "/home/sebas/projects/meetings/src/gluon/restricted.py", line
107, in restricted
    exec ccode in environment
  File "/home/sebas/projects/meetings/src/applications/welcome/models/db.py",
line 151, in <module>
    auth.define_tables()               # creates all needed tables
  File "/home/sebas/projects/meetings/src/applications/welcome/models/db.py",
line 82, in define_tables
    migrate=self.__get_migrate(self.settings.table_user_name, migrate))
AttributeError: 'MyAuth' object has no attribute '_MyAuth__get_migrate'


Re: how to override Auth

Fran
Sat, 06 Jun 2009 07:59:48 -0700

On 4 June, 19:09, "Sebastian E. Ovide" <sebastianov...@gmail.com>
wrote:
> class MyAuth(Auth):

Add here:
    def __init__(self, environment, db = None):
        Auth.__init__(self, environment, db)

F

0

0
 

web2py with tornado instead of cherrypy

web2py with tornado instead of cherrypy – web2py-developers | Google Groups:

Hi folks,
in PythonBrasil5[1] Douglas talked with me about tornado[2].

web2py + cherrypy without concurrent requests: 39.35 requests/sec
(mean time per request: 25.411 ms)
web2py + tornado without concurrent requests: 43.97 requests/sec (mean
time per request: 22.742 ms)

web2py + cherrypy with with 100 concurrent requests: 39.46
requests/sec (mean time per request: 25.340 ms)
web2py + tornado with 100 concurrent requests: 46.16 requests/sec
(mean time per request: 21.662 ms)

tornado versys cherrypy without concurrent requests: +11.75% faster
tornado versys cherrypy with 100 concurrent requests: +16.97% faster

What you need to do this experiment:
1- Download attached file main_tornado.py and replace gluon/main.py
with this file;
2- Download tornado, uncompress and copy directory ‘tornado’ (inside
tornado-0.1′ directory) and copy it to web2py’s root directory.

I did not test my modification but for some tests, GET and POST with
query strings are working OK. To create other HTTP methods we need
only to add ‘new_method = get’ in MainHandler class.

What do you think?

[1] http://www.pythonbrasil.org.br/
[2] http://www.tornadoweb.org/


 Álvaro Justen
 Peta5 – Telecomunicações e Software Livre
 21 3021-6001 / 9898-0141
 http://www.peta5.com.br/

  main_tornado.py
37K View Download


Massimo Di Pierro  
View profile  
 More options Sep 16 2009, 6:52 am

Thank you for this test. It is very valuable.

It seems to me the effect is too small to justify a change. In  
particular considering that if one of the requests take long time to  
process, cherrypy still handles the concurrent requests while tornado  
(not multi threading) will block until the slow one is completed.

Massimo

On Sep 15, 2009, at 11:41 PM, Álvaro Justen [Turicas] wrote:

0

0
 

Subdomains with routes.py

WikiYou – Showcase – web2py-users | Grupos de Google:

I would like to share my 2nd app using web2py, its at www.wikiyou.org.
It is like wikipedia about us and you can create your own subdomain
usernames like having your own username.wikiyou.org. I actually have a
PHP/MySQL version using Zend Framework before, but I decided to port
it to web2py and having more features than before.
Also I have few questions on how to resolve some things.

First.
Is there a way to add attributes using the MENU() helper in anchor
tags? like I want to add rel=”nofollow” in there.

Second.
This might not be web2py related, but gae, on gae they don’t support
naked domains so when you go to wikiyou.org it will be no page found.
I already followed and added some of appengine groups to fix it, but
no luck, the domain is in enom. So I added @ www.wikiyou.org
URL_REDIRECT type. cause I can’t add empty.

Third.
Is there like a way to know if i’m on a development server and
production? starting from routes.py so I could change settings
depending on my env info? even a single switch somewhere will help.

———————-

Would you tell how you created this subdomain thing?

Is there a dedicated function for this?
——————————–

Hi,

I used routes.py to handle subdomain.
Also I added in google domain * for subdomain.

Here is the routes.py to give you an idea on how I did it.

routes_in = ((‘.*:https?://([^www][a-z0-9]+)\.wikiyou\.dev:.* /wiki/
(.*)’, r’/wikiyou/user/wiki/\1/\2′),
             (‘.*:https?://([^www][a-z0-9]+)\.wikiyou\.dev:.* /(.*)’,
r’/wikiyou/user/index/\1/\2′))
also routes_out should have a redirect so it uses www for user styles
and other stuff that needs to link back

routes_out = ((‘/wikiyou/static(?P<any>.*)’, ‘http://www.wikiyou.dev/
wikiyou/static\g<any>’))

I have lots of things in my routes.py but thats the only thing that
makes the subdomain works.
Also my second question might have been fixed, by simply removing all
A Records that has @ leaving only the URL redirect.
But doesn’t work in my google chrome yet, but works on firefox.

——————————————-

Can you explain how you tested the url mapping in development.  I have
a similar architecture and am not sure how to test the url mapping
using localhost.

My Scenario is as follows:
1) A user is email link of “http://mycommunity.mydomain.com.
2) They click on link.
3) The web2Py app requires login via a central mechanism common to all
communities.
4) It parses the environment variable to try and get the parameter.
5) It then opens a database specific to the community (I believe this
is analogous to your personal wiki’s).
6) The goal being there is only one copy of all controllers and views,
etc. (Again, I suspect your app is the same).

When I try and enter a URL like “http://mycommunity.127.0.0.1:8000/
mm_beta_1/default/index”  where mycommunity is actually a parameter
specifying which community to operate on, I get page not found errors.

——————————————————

Hello David,

>  When I try and enter a URL like “http://mycommunity.127.0.0.1:8000/mm_beta_1/default/index”  where mycommunity is actually a parameter specifying which community

The problem is that the browser does not understand a address like subdomain.127.0.0.1, you have to fool the operating system when testing subdomains.

On Windows look at the file hosts in c:\windows\system32\drivers\etc or /etc/hosts on linux.

Put a new line for every subdomain you want to test:
127.0.0.1       kennethscommunity.community.com
127.0.0.1       davidscommunity.community.com
127.0.0.1       joescommunity.community.com

you can t use a wildcard, I think.

Now if you try to reach http://davidscommunity.community.com you should arrive at your site. I have not done this myself but I m pretty sure it should work.

Kenneth

————————————————–
kenneth is correct. You have to edit your /etc/hosts in linux and c:
\windows\system32\drivers\etc\hosts in windows, then add those new
lines,
I usually practive doing like this
127.0.0.1 www.mysite.dev
127.0.0.1 sub.mysite.dev
like using original domain and using .dev as extension.
I also believe you can’t use wildcard for hosts, thats for linux. I
dont know about windows.
Also you will be checking for ports still if you don’t run it in port
80 so it will be like
mycommunity.community.com:8000/mm_beta_1… etc

————————————————

also don’t forget, if you will be running on port 8000 you should be
accessing it at
http://davidscommunity.community.com:8000
Also I think it’s not supported to use wildcards in linux.
And I usually use the same url except for .com to .dev in my hosts for
most of my dev stuff.
On Aug 16, 5:06 am, Kenneth Lundström <kenneth.t.lundst@gmail.com>
wrote:

0

0
 

Sanitizing embedded video from users

I’m developing an app that needs to allow users to create and view
content that includes links, images, and embedded video, e.g. from
YouTube.  The following wrapper for the XML function seems the minimum
set that will do the job, but I’m concerned about XSS attacks.

def myXML(text):
    return XML(text, sanitize=True,
        permitted_tags=['a', 'b', 'blockquote', 'br/', 'i', 'li',
           'ol', 'ul', 'p', 'cite', 'code', 'pre',
'img/','object','embed'],
        allowed_attributes={‘a’:['href', 'title'],
           ’img’:['src', 'alt'], ‘blockquote’:['type'],
           ’object’:['height','width'],
           ’embed’:['allowfullscreen','src','type'],
           })

Any suggestions from the security experts in the community?

Thanks,
Mike


    Responder     Responder al autor     Reenviar       

    Calificar esta entrada: Text for clearing space

Debes registrarte antes de enviar mensajes.
Para enviar una entrada, antes deberás formar parte del grupo.
Antes de enviar entradas, actualiza tu alias en la configuración de la suscripción.
No dispones del permiso necesario para enviar entradas.

GoldenTiger  
Ver perfil   Traducir al Español Traducido (ver original)
 Más opciones 1 jul, 20:40
De: GoldenTiger <goldenboy@gmail.com>
Fecha: Thu, 1 Jul 2010 11:40:33 -0700 (PDT)
Local: Jue 1 jul 2010 20:40
Asunto: Re: Sanitizing embedded video from users

I don’t know how XML function works, let me see your upload form code
and any html output of myXML

On 1 jul, 18:32, MikeEllis <michael.f.el@gmail.com> wrote:

- Mostrar texto de la cita -


    Responder     Responder al autor     Reenviar  

Debes registrarte antes de enviar mensajes.
Para enviar una entrada, antes deberás formar parte del grupo.
Antes de enviar entradas, actualiza tu alias en la configuración de la suscripción.
No dispones del permiso necesario para enviar entradas.


MikeEllis  
Ver perfil   Traducir al Español Traducido (ver original)
 Más opciones 1 jul, 21:44
De: MikeEllis <michael.f.el@gmail.com>
Fecha: Thu, 1 Jul 2010 12:44:49 -0700 (PDT)
Local: Jue 1 jul 2010 21:44
Asunto: Re: Sanitizing embedded video from users

Thanks for responding!

The XML() helper is described in the online web2py book in section
5.2.

Basically, it prevents characters that are special to HTML from being
escaped in the output of other web2py helpers.   The sanitize argument
tells XML() to escape all but a permitted set of tags and allowed
attributes.  Massimo has some examples in the book of using XML() to
escape <script> tags to prevent javascript XSS attacks while allowing
innocuous markup to pass through unaltered.

The myXML() wrapper I wrote adds 2 tags, ‘object’ and ‘embed’ and
specifies with allowed attributes ‘height’ and ‘width’ for object and
‘allowfullscreen’, ‘src’, and ‘type’.  These seem to be sufficient to
allow one to go to YouTube, Vimeo, or MetaCafe, click the embed
button, copy the html,  paste it into the CKEditor instance in my
application, and allow the video to play when my application renders
the user’s content.

So, for example,  if the input a user submits contains video embedding
code like this:

<object width=”400″ height=”225″><param name=”allowfullscreen”
value=”true” /><param name=”allowscriptaccess” value=”always” /><param
name=”movie” value=”http://vimeo.com/moogaloop.swf?
clip_id=12475071&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1″ /

clip_id=12475071&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1″
type=”application/x-shockwave-flash” allowfullscreen=”true”
allowscriptaccess=”always” width=”400″ height=”225″></embed></object>

then myXML() will turn it into

<object height=”225″
width=”400″>&lt;param&gt;&lt;param&gt;&lt;param&gt;<embed
allowfullscreen=”true” src=”http://vimeo.com/moogaloop.swf?
clip_id=12475071&server=vimeo.com&show_title=1&show_byline=1&show_portrait=0&color=&fullscreen=1″
type=”application/x-shockwave-flash”></embed></object>

Notice that the <param> tags are escaped and their attributes are
removed.  Also notice that the “allowscriptaccess” tag has been
removed from the <embed> tag.   Surprisingly, removing this stuff
doesn’t seem to affect the display and playback of the video.

So what I’m trying to find out is whether this level of escaping is
sufficient to prevent anything harmful from being served by my
application or, if not, what additional validation and filtering is
needed.

You asked about my upload form.  Basically it looks like this:

    fields = [Field("edited", 'string', default=itemtext,
                    requires=IS_NOT_EMPTY(),
                    widget=ckeditor_basic,
                    formstyleitem=None,
                    )
             ]
    form = SQLFORM.factory(*fields)
    if form.accepts(request.vars, session):
        session.flash = ‘Edit accepted.’
        #import pdb; pdb.set_trace()
        update(form.vars.edited)

         … etc ..

    elif form.errors:
        response.flash = ‘Form has errors!’
    else:
        response.flash = ‘Fill out the form’
    return dict(form=form)

The ckeditor_basic widget is a wrapper that replaces a textarea with a
CKEditor instance.  So what the user get is the ability to compose
content with a limited set of markup including links, images, and
embedded video.  Note that there is no support for uploading the
actual image or video files.  When the user submits the content, my
application stores it verbatim to be served later after passing it
through the myXML() function.

Thanks,
Mike

0

0
 

Upload to Static folder? Serve File without streaming?


Phyo Arkar  
Ver perfil   Traducir al Traducido (ver original)
 Más opciones 3 jul, 01:40

Anyway to Upload directly to Static Folder (none SQLForm, none DB)
And Serve file without streaming and going through Controller?


    Responder     Responder al autor     Reenviar       

    Calificar esta entrada: Text for clearing space

Debes registrarte antes de enviar mensajes.
Para enviar una entrada, antes deberás formar parte del grupo.
Antes de enviar entradas, actualiza tu alias en la configuración de la suscripción.
No dispones del permiso necesario para enviar entradas.

mdipierro  
Ver perfil   Traducir al Español Traducido (ver original)
 Más opciones 3 jul, 01:48

def index():

form=FORM((INPUT(_type=’file’,_name=’myfile’),INPUT(_type=’submit’))
     if form.accepts(request.vars,session):

open(os.path.join(request.folder,’static’,'filename.txt’),’wb’).write(form.myfile.file.read())
           response.flash=’uploaded’
     return dict(form=form)

but you need to come up with a safe way to generate a ‘filename.txt’

On 2 Lug, 18:40, Phyo Arkar <phyo.arkarl@gmail.com> wrote:

- Mostrar texto de la cita -


    Responder     Responder al autor     Reenviar       

    Calificar esta entrada: Text for clearing space

Debes registrarte antes de enviar mensajes.
Para enviar una entrada, antes deberás formar parte del grupo.
Antes de enviar entradas, actualiza tu alias en la configuración de la suscripción.
No dispones del permiso necesario para enviar entradas.

Phyo Arkar  
Ver perfil   Traducir al Español Traducido (ver original)
 Más opciones 3 jul, 02:06
De: Phyo Arkar <phyo.arkarl@gmail.com>
Fecha: Sat, 3 Jul 2010 00:06:58 +0000
Local: Sáb 3 jul 2010 02:06
Asunto: Re: [web2py] Re: Upload to Static folder? Serve File without streaming?

Thanks a lot!
this code can also write Large Files right?

- Mostrar texto de la cita -


    Responder     Responder al autor     Reenviar       

    Calificar esta entrada: Text for clearing space

Debes registrarte antes de enviar mensajes.
Para enviar una entrada, antes deberás formar parte del grupo.
Antes de enviar entradas, actualiza tu alias en la configuración de la suscripción.
No dispones del permiso necesario para enviar entradas.

mdipierro  
Ver perfil   Traducir al Español Traducido (ver original)
 Más opciones 3 jul, 02:27
De: mdipierro <mdipie@cs.depaul.edu>
Fecha: Fri, 2 Jul 2010 17:27:58 -0700 (PDT)
Local: Sáb 3 jul 2010 02:27
Asunto: Re: Upload to Static folder? Serve File without streaming?

No. For large files use this instead:

def index():

form=FORM((INPUT(_type=’file’,_name=’myfile’),INPUT(_type=’submit’))
     if form.accepts(request.vars,session):

shutil.copyfileobj(form.myfile.file,open(os.path.join(request.folder,’static’,'filename.txt’),’wb’))
           response.flash=’uploaded’
     return dict(form=form)

On 2 Lug, 19:06, Phyo Arkar <phyo.arkarl@gmail.com> wrote:

- Mostrar texto de la cita -


    Responder     Responder al autor     Reenviar       

    Calificar esta entrada: Text for clearing space

Debes registrarte antes de enviar mensajes.
Para enviar una entrada, antes deberás formar parte del grupo.
Antes de enviar entradas, actualiza tu alias en la configuración de la suscripción.
No dispones del permiso necesario para enviar entradas.

weheh  
Ver perfil   Traducir al Español Traducido (ver original)
 Más opciones 3 jul, 03:48
De: weheh <richard_gor@verizon.net>
Fecha: Fri, 2 Jul 2010 18:48:54 -0700 (PDT)
Local: Sáb 3 jul 2010 03:48
Asunto: Re: Upload to Static folder? Serve File without streaming?

Massimo, just for my personal edification, why won’t
open(os.path.join(…,’wb’).write(…read()) be suitable for writing
large files? What’s a large file, anyway?

On Jul 2, 8:27 pm, mdipierro <mdipie@cs.depaul.edu> wrote:

- Mostrar texto de la cita -


    Responder     Responder al autor     Reenviar       

    Calificar esta entrada: Text for clearing space

Debes registrarte antes de enviar mensajes.
Para enviar una entrada, antes deberás formar parte del grupo.
Antes de enviar entradas, actualiza tu alias en la configuración de la suscripción.
No dispones del permiso necesario para enviar entradas.

Scott  
Ver perfil   Traducir al Español Traducido (ver original)
 Más opciones 3 jul, 04:55
De: Scott <blueseas@gmail.com>
Fecha: Fri, 2 Jul 2010 19:55:11 -0700 (PDT)
Local: Sáb 3 jul 2010 04:55
Asunto: Re: Upload to Static folder? Serve File without streaming?

With regards to storing the file, can you still use regex to validate
the filename if you choose to utilize this direct upload method?  I’m
working on a project where a requirement is to store the files as-is
on the filesystem as they will be utilized by other programs.

On Jul 2, 8:27 pm, mdipierro <mdipie@cs.depaul.edu> wrote:

- Mostrar texto de la cita -


    Responder     Responder al autor     Reenviar       

    Calificar esta entrada: Text for clearing space

Debes registrarte antes de enviar mensajes.
Para enviar una entrada, antes deberás formar parte del grupo.
Antes de enviar entradas, actualiza tu alias en la configuración de la suscripción.
No dispones del permiso necesario para enviar entradas.


ron_m  
Ver perfil   Traducir al Español Traducido (ver original)
 Más opciones 3 jul, 05:26
De: ron_m <ron.mco@gmail.com>
Fecha: Fri, 2 Jul 2010 20:26:47 -0700 (PDT)
Local: Sáb 3 jul 2010 05:26
Asunto: Re: Upload to Static folder? Serve File without streaming?

It reads the entire file into memory, then writes it out, not good for
files large enough to consume a significant fraction of system memory.

On Jul 2, 6:48 pm, weheh <richard_gor@verizon.net> wrote:

- Mostrar texto de la cita -

0

0
 

Upload to Static folder? Serve File without streaming?

Anyway to Upload directly to Static Folder (none SQLForm, none DB)
And Serve file without streaming and going through Controller?

    Responder     Responder al autor     Reenviar       

    Calificar esta entrada: Text for clearing space

Debes registrarte antes de enviar mensajes.
Para enviar una entrada, antes deberás formar parte del grupo.
Antes de enviar entradas, actualiza tu alias en la configuración de la suscripción.
No dispones del permiso necesario para enviar entradas.

mdipierro  
Ver perfil   Traducir al Español Traducido (ver original)
 Más opciones 3 jul, 01:48
De: mdipierro <mdipie@cs.depaul.edu>
Fecha: Fri, 2 Jul 2010 16:48:22 -0700 (PDT)
Local: Sáb 3 jul 2010 01:48
Asunto: Re: Upload to Static folder? Serve File without streaming?

def index():

form=FORM((INPUT(_type=’file’,_name=’myfile’),INPUT(_type=’submit’))
     if form.accepts(request.vars,session):

open(os.path.join(request.folder,’static’,'filename.txt’),’wb’).write(form.myfile.file.read())
           response.flash=’uploaded’
     return dict(form=form)

but you need to come up with a safe way to generate a ‘filename.txt’

On 2 Lug, 18:40, Phyo Arkar <phyo.arkarl@gmail.com> wrote:

- Mostrar texto de la cita -


    Responder     Responder al autor     Reenviar       

    Calificar esta entrada:

Debes registrarte antes de enviar mensajes.
Para enviar una entrada, antes deberás formar parte del grupo.
Antes de enviar entradas, actualiza tu alias en la configuración de la suscripción.
No dispones del permiso necesario para enviar entradas.

Phyo Arkar  
Ver perfil   Traducir al Español Traducido (ver original)
 Más opciones 3 jul, 02:06
De: Phyo Arkar <phyo.arkarl@gmail.com>
Fecha: Sat, 3 Jul 2010 00:06:58 +0000
Local: Sáb 3 jul 2010 02:06
Asunto: Re: [web2py] Re: Upload to Static folder? Serve File without streaming?

Thanks a lot!
this code can also write Large Files right?

- Mostrar texto de la cita -


    Responder     Responder al autor     Reenviar       

    Calificar esta entrada: Text for clearing space

Debes registrarte antes de enviar mensajes.
Para enviar una entrada, antes deberás formar parte del grupo.
Antes de enviar entradas, actualiza tu alias en la configuración de la suscripción.
No dispones del permiso necesario para enviar entradas.

mdipierro  
Ver perfil   Traducir al Español Traducido (ver original)
 Más opciones 3 jul, 02:27
De: mdipierro <mdipie@cs.depaul.edu>
Fecha: Fri, 2 Jul 2010 17:27:58 -0700 (PDT)
Local: Sáb 3 jul 2010 02:27
Asunto: Re: Upload to Static folder? Serve File without streaming?

No. For large files use this instead:

def index():

form=FORM((INPUT(_type=’file’,_name=’myfile’),INPUT(_type=’submit’))
     if form.accepts(request.vars,session):

shutil.copyfileobj(form.myfile.file,open(os.path.join(request.folder,’static’,'filename.txt’),’wb’))
           response.flash=’uploaded’
     return dict(form=form)

On 2 Lug, 19:06, Phyo Arkar <phyo.arkarl@gmail.com> wrote:

- Mostrar texto de la cita -


    Responder     Responder al autor     Reenviar       

    Calificar esta entrada: Text for clearing space

Debes registrarte antes de enviar mensajes.
Para enviar una entrada, antes deberás formar parte del grupo.
Antes de enviar entradas, actualiza tu alias en la configuración de la suscripción.
No dispones del permiso necesario para enviar entradas.

weheh  
Ver perfil   Traducir al Español Traducido (ver original)
 Más opciones 3 jul, 03:48
De: weheh <richard_gor@verizon.net>
Fecha: Fri, 2 Jul 2010 18:48:54 -0700 (PDT)
Local: Sáb 3 jul 2010 03:48
Asunto: Re: Upload to Static folder? Serve File without streaming?

Massimo, just for my personal edification, why won’t
open(os.path.join(…,’wb’).write(…read()) be suitable for writing
large files? What’s a large file, anyway?

On Jul 2, 8:27 pm, mdipierro <mdipie@cs.depaul.edu> wrote:

- Mostrar texto de la cita -


    Responder     Responder al autor     Reenviar       

    Calificar esta entrada: Text for clearing space

Debes registrarte antes de enviar mensajes.
Para enviar una entrada, antes deberás formar parte del grupo.
Antes de enviar entradas, actualiza tu alias en la configuración de la suscripción.
No dispones del permiso necesario para enviar entradas.

Scott  
Ver perfil   Traducir al Español Traducido (ver original)
 Más opciones 3 jul, 04:55
De: Scott <blueseas@gmail.com>
Fecha: Fri, 2 Jul 2010 19:55:11 -0700 (PDT)
Local: Sáb 3 jul 2010 04:55
Asunto: Re: Upload to Static folder? Serve File without streaming?

With regards to storing the file, can you still use regex to validate
the filename if you choose to utilize this direct upload method?  I’m
working on a project where a requirement is to store the files as-is
on the filesystem as they will be utilized by other programs.

On Jul 2, 8:27 pm, mdipierro <mdipie@cs.depaul.edu> wrote:

- Mostrar texto de la cita -


    Responder     Responder al autor     Reenviar       

    Calificar esta entrada: Text for clearing space

Debes registrarte antes de enviar mensajes.
Para enviar una entrada, antes deberás formar parte del grupo.
Antes de enviar entradas, actualiza tu alias en la configuración de la suscripción.
No dispones del permiso necesario para enviar entradas.


ron_m  
Ver perfil   Traducir al Español Traducido (ver original)
 Más opciones 3 jul, 05:26
De: ron_m <ron.mco@gmail.com>
Fecha: Fri, 2 Jul 2010 20:26:47 -0700 (PDT)
Local: Sáb 3 jul 2010 05:26
Asunto: Re: Upload to Static folder? Serve File without streaming?

It reads the entire file into memory, then writes it out, not good for
files large enough to consume a significant fraction of system memory.

On Jul 2, 6:48 pm, weheh <richard_gor@verizon.net> wrote:

0

0