[web2py] Re: static files extending layout.html

2012-06-26 Thread Annet
I have the following menu:

response.util_menu=[
['Disclaimer',request.function=='generic' and 
request.args(0)=='disclaimer',URL('util','generic',args='disclaimer')],
['Privacy',request.function=='generic' and 
request.args(0)=='privacy',URL('util','generic',args='privacy')],
['Copyright',request.function=='generic' and 
request.args(0)=='copyright',URL('util','generic',args='copyright')],
['Cookies',request.function=='generic' and 
request.args(0)=='cookies',URL('util','generic',args='cookies')],
['Site map',request.function=='generic' and 
request.args(0)=='sitemap',URL('util','generic',args='sitemap')],
['Contact',request.function=='contact',URL('util','contact')]]

... and in a controller util.py the following function:

def generic():
if request.args(0) in 
['disclaimer','privacy','copyright','cookies','sitemap']:
response.view='util/' + str(request.args(0)) + '.html'
else:
redirect(URL('default','error'))
return dict()

... and the following view named util/disclaimer.html:

{{extend 'default/layout.html'}}


  
Disclaimer text here
   
 

When I request: http://127.0.0.1:8000/init/util/generic/disclaimer
I get: invalid function (default/util)

I don't understand why.


Annet.

-- 





[web2py] Re: App does not exist or your are not authorized when deploying layout plugin

2012-06-26 Thread François Delpierre
Ok, so it means that the solution from Massimo is not working anymore :
http://permalink.gmane.org/gmane.comp.python.web2py/71241

How can I then make plugins that automatically change the layout of the 
application without having to leave web interface ?

That's strange, as one of the downloadable layout does exactly that, and 
works :
pivert@skinner:~/Downloads$ tar -ztvf web2py.plugin.layout_Compromise.w2p 
-rw-r--r-- mdipierro/staff 5559 2010-11-03 17:09 views/layout.html
-rw-r--r-- mdipierro/staff 3359 2010-11-03 17:03 
static/plugin_layouts/superfish.css
-rw-r--r-- mdipierro/staff 3714 2010-11-03 17:03 
static/plugin_layouts/superfish.js
-rw-r--r-- mdipierro/staff 5559 2010-11-03 17:07 
views/plugin_layouts/layouts/Compromise.html
drwxr-xr-x mdipierro/staff0 2010-10-20 07:09 
static/plugin_layouts/layouts/Compromise/
drwxr-xr-x mdipierro/staff0 2010-10-20 07:09 
static/plugin_layouts/layouts/Compromise/images/
-rw-r--r-- mdipierro/staff 6452 2010-10-20 07:09 
static/plugin_layouts/layouts/Compromise/index.html
-rw-r--r-- mdipierro/staff 13901 2010-10-20 07:09 
static/plugin_layouts/layouts/Compromise/license.txt
-rw-r--r-- mdipierro/staff 18861 2010-10-20 07:09 
static/plugin_layouts/layouts/Compromise/preview.png
-rw-r--r-- mdipierro/staff  4856 2010-10-20 07:09 
static/plugin_layouts/layouts/Compromise/style.css
-rw-r--r-- mdipierro/staff  1631 2010-10-20 07:09 
static/plugin_layouts/layouts/Compromise/images/img01.gif
-rw-r--r-- mdipierro/staff   413 2010-10-20 07:09 
static/plugin_layouts/layouts/Compromise/images/img02.jpg
-rw-r--r-- mdipierro/staff  2496 2010-10-20 07:09 
static/plugin_layouts/layouts/Compromise/images/img03.jpg
-rw-r--r-- mdipierro/staff  9087 2010-10-20 07:09 
static/plugin_layouts/layouts/Compromise/images/img04.jpg
-rw-r--r-- mdipierro/staff  2989 2010-10-20 07:09 
static/plugin_layouts/layouts/Compromise/images/img05.gif


-- 





[web2py] Re: Rocket server truncating long responses

2012-06-26 Thread Ron McOuat
I was getting this in a reproducible way some months ago and all I had to 
do was move from the local LAN where it works to over an IPSec tunnel from 
the office which would be over the WAN where it did not work. The 
truncation result was more chaotic in my case, mostly Javascript files were 
chopped because looking at the resulting page the Javascript to decorate 
the jQueryUI buttons had not run. In some cases large jpg images were 
broken. For production I still front end with Apache and the problem goes 
away. What was puzzling at the time was different browsers got different 
results, probably timing differences between how they loaded referenced 
file resources that made up the page. In my case the page loads were under 
5 seconds total. I concluded I would never run production under rocket so I 
did not press further. I still have the wireshark packet captures from then 
if you want them.

Ron

On Tuesday, 26 June 2012 12:43:16 UTC-7, Massimo Di Pierro wrote:
>
> If you can reproduce. Chould you try wireshark to do a packet capture? I 
> would like to see what is going on.
> Tim is a new dad and has not been responsive. I will try an attempt to fix 
> this myself (although I cannot repcoduce it) else we wil revert to 
> cherrypy. 
>
> On Tuesday, 26 June 2012 07:04:15 UTC-5, Álvaro José Iradier wrote:
>>
>> Hi,
>>
>> I am developing an application that needs to return a big report page, 
>> with a lot of data. We were testing the application using the integrated 
>> rocket server, and the report was working correctly when accessing the app 
>> on the local network.
>>
>> However, when connection from the outside via a DSL router, making a NAT 
>> to the web2py http server, the response page gets truncated after about 
>> 15-30 seconds (could not determine an exact period). The browser stops 
>> receiving data, and the page is truncated. Capturing traffic with wireshark 
>> shows the remote end is finishing the connection (FIN flag set) before 
>> sending all data, but the Content-Length header was correctly set to a 
>> higher value.
>>
>> The problem dissapears when running web2py with lighttpd via FastCGI.
>>
>> The truncate problem also dissapears if instead of accessing directly to 
>> the web server, we make a SSH tunnel to the Linux machine hosting the 
>> web2py application, and requesting the report though the tunnel, but 
>> probably the SSH tunnel is retrieving the full page, then buffering it 
>> through the tunnel.
>>
>> Has anybody hit the same problem? It there a maximum response time for 
>> rocket server? I found there is a maximum request time, but the request is 
>> being processed quite fast, less than 1 second. The problem is *sending* 
>> the response, which is getting longer.
>>
>> Thanks.
>>
>>

-- 





Re: [web2py] Re: Best practice using scheduler as a task queue?

2012-06-26 Thread Michael Toomim
In case it is useful to someone, here is the full code I used with locking, 
using postgresql advisory locks. The benefit of using postgresql's locks 
are that:
  • It locks on the database—works across multiple clients
  • The locks are automatically released if a client disconnects from the db
  • I think it's fast

def check_daemon(task_name, period=None):
period = period or 4

tasks_query = ((db.scheduler_task.function_name == task_name)
   & db.scheduler_task.status.belongs(('QUEUED',
   'ASSIGNED',
   'RUNNING',
   'ACTIVE')))

# Launch a launch_queue task if there isn't one already
tasks = db(tasks_query).select()
if len(tasks) > 1:  #  Check for error
raise Exception('Too many open %s tasks!!!  N, there are %s'
% (task_name, len(tasks)))
if len(tasks) < 1:
if not db.executesql('select pg_try_advisory_lock(1);')[0][0]:
debug('Tasks table is already locked.')
return

# Check again now that we're locked
if db(tasks_query).count() >= 1:
debug('Caught a race condition! Glad we got outa there!')
db.executesql('select pg_advisory_unlock(1);')
return

debug('Adding a %s task!', task_name)
db.scheduler_task.insert(function_name=task_name,
 application_name='utility/utiliscope',
 task_name=task_name,
 stop_time = now + 
timedelta(days=9),
 repeats=0, period=period)
db.commit()
db.executesql('select pg_advisory_unlock(1);')

elif tasks[0].period != period:
debug('Updating period for task %s', task_name)
tasks[0].update_record(period=period)
db.commit()

check_daemon('process_launch_queue_task')
check_daemon('refresh_hit_status')
check_daemon('process_bonus_queue')



On Tuesday, June 26, 2012 7:57:25 PM UTC-7, Michael Toomim wrote:
>
> All, thank you for the excellent discussion!
>
> I should explain why I posted that recommendation. The "vision" of using 
> the scheduler for background tasks was:
>
> "Woohoo, this scheduler will *automatically handle locks*—so I don't need 
> to worry about stray background processes running in parallel 
> automatically, and it will *automatically start/stop the processes* with 
> the web2py server with -K, which makes it much easier to deploy the code!"
>
>  
> It turned out:
>   • Setting up scheduler tasks was complicated in itself.
>  • 3 static tasks had to be inserted into every new db.
>This requires new installations of my software to run a setup 
> routine. Yuck.
>  • When I made that automatic in models/, it required locks to avoid 
> db race condition.
>(I used postgresql advisory locks. Not cross-platform, but I dunno 
> a better solution.)
>  • The goal was to avoid locks in the first place!
>   • When things go wrong, it's harder to debug.
> • The scheduler adds a new layer of complexity.
> • Because now I have to make sure my tasks are there properly.
> • And then look for the scheduler_run instances to see how they went.
>
> I must admit that this second problem would probably go away if we fixed 
> all the scheduler's bugs! But it still leaves me uneasy. And I don't like 
> having 40,000 scheduler_run instances build up over time.
>
> At this point, I realized that what I really want is a new feature in 
> web2py that:
>   • Runs a function in models (akin to scheduler's executor function) in a 
> subprocess repeatedly
>   • Ensures, with locks etc., that:
>  • Only one is running at a time
>  • That it dies if the parent web2py process dies
>
> And it seems better to just implement this as a web2py feature, than to 
> stranglehold the scheduler into a different design.
>
> Cron's @reboot is very close to this. I used to use it. The problems:
>   • I still had to implement my own locks and kills. (what I was trying to 
> avoid)
>   • It spawns 2 python subprocesses for each cron task (ugly, but not 
> horrible)
>   • It was really buggy. @reboot didn't work. I think massimo fixed this.
>   • Syntax is gross.
> I basically just got scared of cron.
> Now I guess I'm scared of everything. :/
>
> Hopefully this detailed report of my experience will be of help to 
> somebody. I'm sure that fixing the bugs will make things 5x better. I will 
> try your new scheduler.py Niphlod!
>
> On Tuesday, June 26, 2012 12:13:32 PM UTC-7, Niphlod wrote:
>>
>> problem here started as "I can't ensure my app to insert only one task 
>> per function", that is not a scheduler problem "per se": it's a common 
>> database problem. Would have been the same if someone created a 
>> db.define_table('mytable',
>>  

Re: [web2py] Re: Best practice using scheduler as a task queue?

2012-06-26 Thread Michael Toomim
All, thank you for the excellent discussion!

I should explain why I posted that recommendation. The "vision" of using 
the scheduler for background tasks was:

"Woohoo, this scheduler will *automatically handle locks*—so I don't need 
to worry about stray background processes running in parallel 
automatically, and it will *automatically start/stop the processes* with 
the web2py server with -K, which makes it much easier to deploy the code!"

 
It turned out:
  • Setting up scheduler tasks was complicated in itself.
 • 3 static tasks had to be inserted into every new db.
   This requires new installations of my software to run a setup 
routine. Yuck.
 • When I made that automatic in models/, it required locks to avoid db 
race condition.
   (I used postgresql advisory locks. Not cross-platform, but I dunno a 
better solution.)
 • The goal was to avoid locks in the first place!
  • When things go wrong, it's harder to debug.
• The scheduler adds a new layer of complexity.
• Because now I have to make sure my tasks are there properly.
• And then look for the scheduler_run instances to see how they went.

I must admit that this second problem would probably go away if we fixed 
all the scheduler's bugs! But it still leaves me uneasy. And I don't like 
having 40,000 scheduler_run instances build up over time.

At this point, I realized that what I really want is a new feature in 
web2py that:
  • Runs a function in models (akin to scheduler's executor function) in a 
subprocess repeatedly
  • Ensures, with locks etc., that:
 • Only one is running at a time
 • That it dies if the parent web2py process dies

And it seems better to just implement this as a web2py feature, than to 
stranglehold the scheduler into a different design.

Cron's @reboot is very close to this. I used to use it. The problems:
  • I still had to implement my own locks and kills. (what I was trying to 
avoid)
  • It spawns 2 python subprocesses for each cron task (ugly, but not 
horrible)
  • It was really buggy. @reboot didn't work. I think massimo fixed this.
  • Syntax is gross.
I basically just got scared of cron.
Now I guess I'm scared of everything. :/

Hopefully this detailed report of my experience will be of help to 
somebody. I'm sure that fixing the bugs will make things 5x better. I will 
try your new scheduler.py Niphlod!

On Tuesday, June 26, 2012 12:13:32 PM UTC-7, Niphlod wrote:
>
> problem here started as "I can't ensure my app to insert only one task per 
> function", that is not a scheduler problem "per se": it's a common database 
> problem. Would have been the same if someone created a 
> db.define_table('mytable',
>  Field('name'),
>  Field('uniquecostraint')
> )
> and have to ensure, without specifying Field('uniquecostraint', 
> unique=True) that there are no records with the same value into the column 
> uniquecostraint.
>
> From there to "now I have tasks stuck in RUNNING status, please avoid 
> using the scheduler" without any further details, the leap is quite 
> "undocumented".
>
> And please do note that scheduler in trunk has gone under some changes: 
> there was a point in time where abnormally killed schedulers (as kill 
> -SIGKILL the process) left tasks in RUNNING status, that would not be 
> picked up by subsequent scheduler processes.
>
> That was a design issue: if a task is RUNNING and you kill scheduler while 
> the task was processed, you had no absolutely way to tell what the function 
> did (say, send a batch of 500 emails) before it was actually killed. 
> If the task was not planned properly it could send e.g. 359 mails, be 
> killed, and if it was picked up again by another scheduler after the "first 
> killed round" 359 of your recipients would get 2 identical mails.
> It has been decided to requeue RUNNING tasks without any active worker 
> doing that (i.e. leave to the function the eventual check of what has been 
> done), so now RUNNING tasks with a dead worker assigned get requeued.
>
> With other changes (soon in trunk, the previously attached file) you're 
> able to stop workers, so they may be killed "ungracefully" being sure that 
> they're not processing tasks.
>
> If you need more details, as always, I'm happy to help, and other 
> developers too, I'm sure :D
>
>

-- 





[web2py] Re: Problem with Skeleton and Web2py

2012-06-26 Thread SeamusSeamus
Yep, CSS issue. My own fault. I didnt create a container correctly. Sorry 
folks for wasting bandwidth!

On Tuesday, June 26, 2012 7:40:36 PM UTC-6, SeamusSeamus wrote:
>
> I am trying to make a nice design with skeleton. It doesn't seem to  be 
> working. Skeleton normally comes with layout.css, base.css, and 
> skeleton.css, as well as an index.html. Web2py only has skeleton.css. Why 
> is this?
>  So I download skeleton, place the CSS files in the CSS directory, and put 
> the skeleton index.html as newindex.html in the same folder as layout.html, 
> and then  add the {{extend 'layout.html'}} into my /default/index.html 
> file. I update the layout.html with the appropriate paths to the CSS file 
> and it doesn't seem to work. Its frustrating how the Skeleton in Web2py 
> isnt complete and it is refered to as the web2py grid, and not the skeleton 
> grid. What am I missing? Is web2py.css really the base.css file from 
> skeleton just renamed? 
>
> In other words:
> 1. Downloaded skeleton. Placed the SKeleton.css (overwrote the original), 
> base.css, and layout.css inside /static/css
> 2. Put the index.html from skeleton, renamed it to newindex, and placed in 
> /views/
> 3. Updated the newindex and removed this:
>   
>
>
> Then I added this:
> {{response.files.append(URL('static','css/skeleton.css'))}}
> {{response.files.append(URL('static','css/base.css'))}}
> {{response.files.append(URL('static','css/layout.css'))}}
> {{include 'web2py_ajax.html'}}
>
> 4. THen I changed /default/index.html to this:
>
> {{extend 'newlayout.html'}}
>
> Now only SOME of the CSS Styles change. I am sure this is a CSS issue, but 
> it would be nice to have another set of eyes.
>
>
> This should be visible
>

-- 





[web2py] Problem with Skeleton and Web2py

2012-06-26 Thread SeamusSeamus
I am trying to make a nice design with skeleton. It doesn't seem to  be 
working. Skeleton normally comes with layout.css, base.css, and 
skeleton.css, as well as an index.html. Web2py only has skeleton.css. Why 
is this?
 So I download skeleton, place the CSS files in the CSS directory, and put 
the skeleton index.html as newindex.html in the same folder as layout.html, 
and then  add the {{extend 'layout.html'}} into my /default/index.html 
file. I update the layout.html with the appropriate paths to the CSS file 
and it doesn't seem to work. Its frustrating how the Skeleton in Web2py 
isnt complete and it is refered to as the web2py grid, and not the skeleton 
grid. What am I missing? Is web2py.css really the base.css file from 
skeleton just renamed? 

In other words:
1. Downloaded skeleton. Placed the SKeleton.css (overwrote the original), 
base.css, and layout.css inside /static/css
2. Put the index.html from skeleton, renamed it to newindex, and placed in 
/views/
3. Updated the newindex and removed this:
  
   
   
Then I added this:
{{response.files.append(URL('static','css/skeleton.css'))}}
{{response.files.append(URL('static','css/base.css'))}}
{{response.files.append(URL('static','css/layout.css'))}}
{{include 'web2py_ajax.html'}}

4. THen I changed /default/index.html to this:

{{extend 'newlayout.html'}}

Now only SOME of the CSS Styles change. I am sure this is a CSS issue, but 
it would be nice to have another set of eyes.


This should be visible

-- 





Re: [web2py] Short way to update or insert data from SQLFORM.factory into the main db.my_table ??? ...

2012-06-26 Thread Le Don X
Amazing ! .. Viva python .. viva web2py !

This is pretty cool stuff !

thanks Anthony ..


2012/6/26 Anthony 

>
>
> On Tuesday, June 26, 2012 6:17:58 PM UTC-4, Don_X wrote:
>>
>> Hello Anthony, ...
>>
>> I have tried the suggested line of code ...
>> the following way, based on my function index(): in the controller the
>> filter field is 'email_check'
>>
>> so I have entered :
>> db.auth_user.insert(**db.auth_**user.email_check(form.vars))
>>  but I get an error msg ! .. should I put it in brakets ? in parenthesis
>> ?? .. ...
>
>
> No, you should literally use the exact code I included:
>
> db.auth_user.insert(**db.auth_user._filter_fields(form.vars))
>
> The _filter_fields() method takes dictionary-like object and filters out
> any items that are not fields in the table. So, if you pass form.vars to
> it, it will remove any items that don't belong to the db.auth_user table
> (in this case, the email_check variable).
>
> Anthony
>
>
> --
>
>
>
>



-- 
William James nous dit : '' La plus grande découverte de ma génération est
que l'être  humain peut transformer sa vie simplement en modifiant sa
maniére de penser.''
--
Le Don X

-- 





Re: [web2py] DAL performance vs executesql

2012-06-26 Thread Anthony

>
> I wish it was possible to use other time-saving tools like SQLFORM.grid 
> with db.executesql().
>
> At the moment most of the representation tools like SQLTABLE and 
> plugin_wiki's jqgrid suppose DAL usage.
>

This wouldn't help with SQLFORM.grid, which does its own query, but for 
other cases where you need a Rows object with executesql, this might work:

raw_rows = db.executesql('[SQL code]')
rows = db._adapter.parse(raw_rows,
fields=[db.mytable[f] for f in db.mytable.fields],
colnames=db.mytable.fields) 

Anthony

-- 





Re: [web2py] Re: web2py crashing

2012-06-26 Thread Jonathan Lundell
On Jun 26, 2012, at 5:25 PM, Massimo Di Pierro wrote:
> Looks like a buggy socket.py or ssl.py. Is this an occasional error (which 
> may depend on parameters such as certificates) or it reproducible?

This was fixed in Python 2.7. The underlying error is "Transport endpoint is 
not connected", which of course shouldn't cause a crash. I suppose we could 
catch the exception in Rocket as a workaround.

> 
> On Tuesday, 26 June 2012 12:30:58 UTC-5, msmagoo wrote:
> Hi all,
> 
> I have a healthcheck web2py application that simply reads healthcheck 
> information from a database and makes a few REST api calls to a separate 
> web2py application. Over the past while the application has been crashing at 
> least once, sometimes twice a day with few errors in the logs. Most are 
> connection reset by peer errors, which I found out to be nothing that would 
> crash the application. An error I have been seeing frequently is:
> ERROR:Rocket.Errors.Thread-8:Traceback (most recent call last):
> 
>   File "/opt/apps/web2py/gluon/rocket.py", line 1302, in run
> self.run_app(conn)
> 
>   File "/opt/apps/web2py/gluon/rocket.py", line 1986, in run_app
> self.environ = environ = self.build_environ(sock_file, conn)
> 
>   File "/opt/apps/web2py/gluon/rocket.py", line 1807, in build_environ
> request = self.read_request_line(sock_file)
> 
>   File "/opt/apps/web2py/gluon/rocket.py", line 1363, in read_request_line
> d = sock_file.readline()
> 
>   File "/usr/lib/python2.6/socket.py", line 406, in readline
> data = self._sock.recv(self._rbufsize)
> 
>   File "/usr/lib/python2.6/ssl.py", line 96, in 
> self.recv = lambda buflen=1024, flags=0: SSLSocket.recv(self, buflen, 
> flags)
> 
>   File "/usr/lib/python2.6/ssl.py", line 224, in recv
> return socket.recv(self, buflen, flags)
> 
> TypeError: 'member_descriptor' object is not callable
> 
> ERROR:Rocket.Errors.Thread-8:Tried to send "500 Server Error" to client but 
> received socket error
> 
> 
> I have web2py running on https with some certs set up. Any help would be very 
> appreciated.
> 
> Thanks!
> 
> 


-- 





[web2py] Re: web2py crashing

2012-06-26 Thread msmagoo
It happens rather frequently. At least a few times a day, which 
consequently causes web2py to hang and forces me to restart it. I can't 
reproduce it manually.

On Tuesday, June 26, 2012 5:25:43 PM UTC-7, Massimo Di Pierro wrote:
>
> Looks like a buggy socket.py or ssl.py. Is this an occasional error (which 
> may depend on parameters such as certificates) or it reproducible?
>
> On Tuesday, 26 June 2012 12:30:58 UTC-5, msmagoo wrote:
>>
>> Hi all,
>>
>> I have a healthcheck web2py application that simply reads healthcheck 
>> information from a database and makes a few REST api calls to a separate 
>> web2py application. Over the past while the application has been crashing 
>> at least once, sometimes twice a day with few errors in the logs. Most are 
>> connection reset by peer errors, which I found out to be nothing that would 
>> crash the application. An error I have been seeing frequently is:
>> ERROR:Rocket.Errors.Thread-8:Traceback (most recent call last):
>>
>>   File "/opt/apps/web2py/gluon/rocket.py", line 1302, in run
>> self.run_app(conn)
>>
>>   File "/opt/apps/web2py/gluon/rocket.py", line 1986, in run_app
>> self.environ = environ = self.build_environ(sock_file, conn)
>>
>>   File "/opt/apps/web2py/gluon/rocket.py", line 1807, in build_environ
>> request = self.read_request_line(sock_file)
>>
>>   File "/opt/apps/web2py/gluon/rocket.py", line 1363, in read_request_line
>> d = sock_file.readline()
>>
>>   File "/usr/lib/python2.6/socket.py", line 406, in readline
>> data = self._sock.recv(self._rbufsize)
>>
>>   File "/usr/lib/python2.6/ssl.py", line 96, in 
>> self.recv = lambda buflen=1024, flags=0: SSLSocket.recv(self, buflen, 
>> flags)
>>
>>   File "/usr/lib/python2.6/ssl.py", line 224, in recv
>> return socket.recv(self, buflen, flags)
>>
>> TypeError: 'member_descriptor' object is not callable
>>
>> ERROR:Rocket.Errors.Thread-8:Tried to send "500 Server Error" to client 
>> but received socket error
>>
>>
>> I have web2py running on https with some certs set up. Any help would be 
>> very appreciated.
>>
>> Thanks!
>>
>

-- 





Re: [web2py] DAL performance vs executesql

2012-06-26 Thread Anthony

>
> One can already skip this by specifying an alterante processor function
>
> db(...).select(processor=lambda rows,fields,colnames,blob_decode: )
>

We should probably document that. Note, it doesn't appear to pass a 
blob_decode argument to the processor (though the default parse() method 
does take that argument).

Anthony

-- 





[web2py] Re: web2py crashing

2012-06-26 Thread Massimo Di Pierro
Looks like a buggy socket.py or ssl.py. Is this an occasional error (which 
may depend on parameters such as certificates) or it reproducible?

On Tuesday, 26 June 2012 12:30:58 UTC-5, msmagoo wrote:
>
> Hi all,
>
> I have a healthcheck web2py application that simply reads healthcheck 
> information from a database and makes a few REST api calls to a separate 
> web2py application. Over the past while the application has been crashing 
> at least once, sometimes twice a day with few errors in the logs. Most are 
> connection reset by peer errors, which I found out to be nothing that would 
> crash the application. An error I have been seeing frequently is:
> ERROR:Rocket.Errors.Thread-8:Traceback (most recent call last):
>
>   File "/opt/apps/web2py/gluon/rocket.py", line 1302, in run
> self.run_app(conn)
>
>   File "/opt/apps/web2py/gluon/rocket.py", line 1986, in run_app
> self.environ = environ = self.build_environ(sock_file, conn)
>
>   File "/opt/apps/web2py/gluon/rocket.py", line 1807, in build_environ
> request = self.read_request_line(sock_file)
>
>   File "/opt/apps/web2py/gluon/rocket.py", line 1363, in read_request_line
> d = sock_file.readline()
>
>   File "/usr/lib/python2.6/socket.py", line 406, in readline
> data = self._sock.recv(self._rbufsize)
>
>   File "/usr/lib/python2.6/ssl.py", line 96, in 
> self.recv = lambda buflen=1024, flags=0: SSLSocket.recv(self, buflen, 
> flags)
>
>   File "/usr/lib/python2.6/ssl.py", line 224, in recv
> return socket.recv(self, buflen, flags)
>
> TypeError: 'member_descriptor' object is not callable
>
> ERROR:Rocket.Errors.Thread-8:Tried to send "500 Server Error" to client 
> but received socket error
>
>
> I have web2py running on https with some certs set up. Any help would be 
> very appreciated.
>
> Thanks!
>

-- 





Re: [web2py] DAL performance vs executesql

2012-06-26 Thread Massimo Di Pierro
The only "non-essential" processing that has been mentioned is parsing and 
normalization of the records returned by the DB.

One can already skip this by specifying an alterante processor function

db(...).select(processor=lambda rows,fields,colnames,blob_decode: )

where processor acts like the parse function defined in dal BaseAdapter.


Anyway, delaying the parsing and making it lazy has not performance 
advantage. If you retrieve N records it is because you plan to do something 
with all them. If you parse them at retrieve time you are guaranteed to do 
it once. If you do it lazily, you make the select faster but you risk of 
parsing them more than once later thus in incurring in an overall 
performance penalty.

The only think that we can do to speed the dal is to do avoid re-executing 
the define-table. We are working on this. One option would be to have the 
define table in a module (not a model) which is executed only once and the 
use the new recorrect method to recycle an existing db object with all its 
table definitions. this will break migrations and it is still very 
experimental.

Is there something else we can in your opinion improve?

Massimo

On Tuesday, 26 June 2012 12:05:00 UTC-5, pbreit wrote:
>
> Massimo, any ideas on DAL performance? I wonder if it would make sense to 
> have some flags to skip some of the non-essential processing?

-- 





Re: [web2py] Routes - simple requirement, but how??

2012-06-26 Thread villas
Hi Jonathan and Anthony

Thanks for your comments.  I appreciate the work you have done to try and 
simplify this tricky subject.  However,  for me,  the parametric router and 
other ideas,  such as the autoroutes.py and some other recipes I have 
seen,  are not a good idea,  at all.

Now I know you may be thinking,  'Hmm poor soul doesn't seem to know that 
autoroutes and the other recipes are all just based on the pattern-matching 
and parametric routers'.  Well,  I do know -- now!  Yes now that I have 
spent an entire day looking through regex expressions and source code.

It is usually a good thing that we have choices,  but not choices of blind 
alleys.  IMO  there should be one comprehensive way for web2py to do 
routes. If regex patterns are the only way to solve all situations then so 
be it - we should just get used to it.  All our efforts can then go in 
building up a comprehensive list of recipes and off-the-shelf regex 
patterns that we can all just use.

The fact that there doesn't seem to be a clear answer to my easy question 
already says it all,  but the idea of renaming plugin_wiki as a work-around 
puts the issue beyond doubt  :)   

BTW plugin_wiki is one of my favourite things and it really surprises me 
that no one seems to have expressed an interest in wanting to give it 
better URLs.

Best regards,  David

-- 





[web2py] Re: difference between crud.select(db.hem,query) and db(query).select()?

2012-06-26 Thread Massimo Di Pierro
I suggest you do not use crud but use SQLFORM.grid instead. It has much 
better functionality.

On Tuesday, 26 June 2012 07:26:56 UTC-5, Jonas Fredriksson wrote:
>
> hi
>
> When doing results=crud.select(db.hem,query) I got a list containing the 
> result with html tags in the beginning and the end. But I am not able to 
> access different fields like result.info and so on. When I am using 
>  results=db(query).select() I can do results.info. Is there any way to 
> get individual fields using crud.select(db.hem,query)?
>

-- 





Re: [web2py] Short way to update or insert data from SQLFORM.factory into the main db.my_table ??? ...

2012-06-26 Thread Anthony


On Tuesday, June 26, 2012 6:17:58 PM UTC-4, Don_X wrote:
>
> Hello Anthony, ...
>
> I have tried the suggested line of code ...
> the following way, based on my function index(): in the controller the 
> filter field is 'email_check'
>
> so I have entered :
> db.auth_user.insert(**db.auth_user.email_check(form.vars))
>  but I get an error msg ! .. should I put it in brakets ? in parenthesis 
> ?? .. ...


No, you should literally use the exact code I included:

db.auth_user.insert(**db.auth_user._filter_fields(form.vars))

The _filter_fields() method takes dictionary-like object and filters out 
any items that are not fields in the table. So, if you pass form.vars to 
it, it will remove any items that don't belong to the db.auth_user table 
(in this case, the email_check variable).

Anthony
 

-- 





[web2py] Re: Routes - simple requirement, but how??

2012-06-26 Thread Anthony

>
> Lessons to be learnt:
> 1. Why have 3 different routing systems?  One obvious way of doing 
> things?  ha!
>

What's the third routing system (besides parameter-based and pattern-based) 
-- the default routing? Anyway, the parameter-based system was introduced 
to provide an easier method to handle the most common use cases, but the 
pattern-based system had to be retained for backward compatibility (not to 
mention that it is needed to handle the more complicated cases). "One 
obvious way" doesn't necessarily extend to all levels of the system (what 
if their were only one Python framework with which to build a web 
application?).
 

> 2. Regex is almost always beyond someone like me -- unless I have 
> recipes to follow.


Note, even the pattern-based system provides a simpler non-regex syntax for 
the less complex cases. Ultimately, though, if you want the ability to do 
arbitrary rewriting, you'll need some regex.
 

>   All the obvious routing ideas should be spelt out in one list.


Yes, I think the rewrite documentation could be improved, particularly with 
more examples for cases like this.

Note, the parameter-based system does domain mapping and also converts from 
underscores to hyphens, but it won't map your "prettyurl" to "plugin_wiki" 
(hmm, I wonder if you can simply change the name of "plugin_wiki"). I 
believe the pattern-based system should be able to map domains as well, but 
it might be trickier to get it to handle the hyphen conversions via regex. 
Ultimately, it would be nice if the two systems could be used together.

Anthony

-- 





[web2py] Re: web2py book now free in PDF

2012-06-26 Thread Joel Kim
Great!
Thank you.

On Tuesday, June 12, 2012 10:17:46 PM UTC+9, Massimo Di Pierro wrote:
>
> The official web2py book is now free for everybody:
>
> https://dl.dropbox.com/u/18065445/web2py/web2py_manual_4th.1.pdf
>
> Massimo
>

-- 





Re: [web2py] Routes - simple requirement, but how??

2012-06-26 Thread Jonathan Lundell
On Jun 26, 2012, at 7:12 AM, villas wrote:
> I have spent a full day trying to make simple routing work.  Please,  I have 
> tried all the routers and read everything I can.  Could anyone please help?
> 
> Apache / wsgi  standard setup without any changes.  Single instance of web2py
> 
> Two domains and two apps:
> domain1.com  ->  app1
> domain2.com  ->  app2
> 
> One other URL renaming pattern:  
> plugin_wiki  ->  prettyurl
> 
> Tests:
> domain1.com/prettyurl/page/home  ->  /app1/plugin_wiki/page/home
> domain2.com/prettyurl/page/home  ->  /app2/plugin_wiki/page/home
> domain2.com/default/myfunc  ->  /app2/default/myfunc
> 
> This is such a standard requirement,  surely it cannot be so difficult??

The parametric router doesn't do renaming/aliasing at all, so at a minimum 
you'll need to do it with the pattern-matching router.

Note that you *could* use the parametric router successfully in the 
incoming-URL side, by translating request.controller early in your model. But 
there's no general mechanism to translate the other direction, so URL calls 
within plugin_wiki would generate untranslated URLs.

I'd be open to suggestions to allow some kind of outgoing URL hook. I think the 
code would have to live in routes.py, though, since URL can be called from 
anywhere (model, controller, view).

-- 





[web2py] Re: Error using A() tag

2012-06-26 Thread Anthony
That should never have worked, as it is not a legal Python identifier. 
However, you can do:

A('move out', _href=URL('#myModal'), **{'_data-toggle': 'modal'})

This is actually discussed in the book, at the end of this section: 
http://web2py.com/books/default/chapter/29/5#HTML-helpers.

Anthony

On Tuesday, June 26, 2012 6:46:08 PM UTC-4, pbreit wrote:
>
> I'm getting an error on:
> {{=A('move out', _href=URL('#myModal'), _data-toggle='modal')}}
>
> Traceback (most recent call last):
>   File "/Users/pbreit/web2py/gluon/restricted.py", line 204, in restricted
> ccode = compile2(code,layer)
>   File "/Users/pbreit/web2py/gluon/restricted.py", line 189, in compile2
> return compile(code.rstrip().replace('\r\n','\n')+'\n', layer, 'exec')
>   File 
> "/Users/pbreit/web2py/applications/rentmatic/views/default/property.html", 
> line 115
> 
> SyntaxError: keyword can't be an expression
>
> The problem is with the dash in the '_data-toggle' attribute.
>
>
>
> This works OK but of course I need it to be '_data-toggle'.
> {{=A('move out', _href=URL('#myModal'), _data='modal')}}
>
>
>
> The error is different when there is just a dash at the end:
> {{=A('move out', _href=URL('#myModal'), _data-='modal')}}
>
> Traceback (most recent call last):
>   File "/Users/pbreit/web2py/gluon/restricted.py", line 204, in restricted
> ccode = compile2(code,layer)
>   File "/Users/pbreit/web2py/gluon/restricted.py", line 189, in compile2
> return compile(code.rstrip().replace('\r\n','\n')+'\n', layer, 'exec')
>   File 
> "/Users/pbreit/web2py/applications/rentmatic/views/default/property.html", 
> line 115
> response.write(A('move out', _href=URL('#myModal'), _data-='modal'))
>   ^
> SyntaxError: invalid syntax
>
>
> I'm pretty sure this used to work.
>

-- 





[web2py] Error using A() tag

2012-06-26 Thread pbreit
I'm getting an error on:
{{=A('move out', _href=URL('#myModal'), _data-toggle='modal')}}

Traceback (most recent call last):
  File "/Users/pbreit/web2py/gluon/restricted.py", line 204, in restricted
ccode = compile2(code,layer)
  File "/Users/pbreit/web2py/gluon/restricted.py", line 189, in compile2
return compile(code.rstrip().replace('\r\n','\n')+'\n', layer, 'exec')
  File 
"/Users/pbreit/web2py/applications/rentmatic/views/default/property.html", line 
115

SyntaxError: keyword can't be an expression

The problem is with the dash in the '_data-toggle' attribute.

This works OK but of course I need it to be '_data-toggle'.
{{=A('move out', _href=URL('#myModal'), _data='modal')}}

The error is different when there is just a dash at the end:
{{=A('move out', _href=URL('#myModal'), _data-='modal')}}

Traceback (most recent call last):
  File "/Users/pbreit/web2py/gluon/restricted.py", line 204, in restricted
ccode = compile2(code,layer)
  File "/Users/pbreit/web2py/gluon/restricted.py", line 189, in compile2
return compile(code.rstrip().replace('\r\n','\n')+'\n', layer, 'exec')
  File 
"/Users/pbreit/web2py/applications/rentmatic/views/default/property.html", line 
115
response.write(A('move out', _href=URL('#myModal'), _data-='modal'))
  ^
SyntaxError: invalid syntax


I'm pretty sure this used to work.

-- 





[web2py] difference between crud.select(db.hem,query) and db(query).select()?

2012-06-26 Thread Jonas Fredriksson
hi

When doing results=crud.select(db.hem,query) I got a list containing the 
result with html tags in the beginning and the end. But I am not able to 
access different fields like result.info and so on. When I am using 
 results=db(query).select() I can do results.info. Is there any way to get 
individual fields using crud.select(db.hem,query)?

-- 





[web2py] web2py crashing

2012-06-26 Thread msmagoo
Hi all,

I have a healthcheck web2py application that simply reads healthcheck 
information from a database and makes a few REST api calls to a separate 
web2py application. Over the past while the application has been crashing 
at least once, sometimes twice a day with few errors in the logs. Most are 
connection reset by peer errors, which I found out to be nothing that would 
crash the application. An error I have been seeing frequently is:
ERROR:Rocket.Errors.Thread-8:Traceback (most recent call last):

  File "/opt/apps/web2py/gluon/rocket.py", line 1302, in run
self.run_app(conn)

  File "/opt/apps/web2py/gluon/rocket.py", line 1986, in run_app
self.environ = environ = self.build_environ(sock_file, conn)

  File "/opt/apps/web2py/gluon/rocket.py", line 1807, in build_environ
request = self.read_request_line(sock_file)

  File "/opt/apps/web2py/gluon/rocket.py", line 1363, in read_request_line
d = sock_file.readline()

  File "/usr/lib/python2.6/socket.py", line 406, in readline
data = self._sock.recv(self._rbufsize)

  File "/usr/lib/python2.6/ssl.py", line 96, in 
self.recv = lambda buflen=1024, flags=0: SSLSocket.recv(self, buflen, 
flags)

  File "/usr/lib/python2.6/ssl.py", line 224, in recv
return socket.recv(self, buflen, flags)

TypeError: 'member_descriptor' object is not callable

ERROR:Rocket.Errors.Thread-8:Tried to send "500 Server Error" to client but 
received socket error


I have web2py running on https with some certs set up. Any help would be 
very appreciated.

Thanks!

-- 





[web2py] Impersonate

2012-06-26 Thread Paolo
Hi all, 
I am trying to use impersonate but so far I got always the ticket shown 
below. 
The user was logged in and its group has the permission to impersonate all 
users; I am using a custom auth table with web2py trunk

Function:
@auth.requires_login()
def impersonate():
r = auth.impersonate()
return response.render('admin/imp.html', dict(form=r))

Ticket:
2012-06-26 16:24:55,140 - web2py - ERROR - Traceback (most recent call 
last):
  File "/home/paolo/Desktop/git/web2py/gluon/restricted.py", line 205, in 
restricted
exec ccode in environment
  File 
"/home/paolo/Dropbox/git/web2py/applications/bikend/controllers/user.py", 
line 490, in 
  File "/home/paolo/Desktop/git/web2py/gluon/globals.py", line 182, in 

self._caller = lambda f: f()
  File 
"/home/paolo/Dropbox/git/web2py/applications/bikend/controllers/user.py", 
line 366, in impersonate
r = auth.impersonate()
  File "/home/paolo/Desktop/git/web2py/gluon/tools.py", line 2592, in 
impersonate
self.settings.login_onaccept(form)
TypeError: 'list' object is not callable

Regards,
paolo

-- 





[web2py] Re: Routes - simple requirement, but how??

2012-06-26 Thread villas
Dear All, 

Ok here I am -- over a full day later --  with a stupidly-simple 
work-around hack:  

routes_in...
 ('/app1/prettyurl(?P.*)',  r'/app1/plugin_wiki\g'),
 ('/app2/prettyurl(?P.*)', r'/app2/plugin_wiki\g'),
 
routes_out...
  ('/app1/plugin_wiki(?P.*)', r'/app1/prettyurl\g'),
  ('/app2/plugin_wiki(?P.*)', r'/app2/prettyurl\g'),

However,  on accessing http://domain2/  I would always be redirected to 
http://domain1/

So I added this line to the beginning of  app1/models/0.py
if 'domain2' in request.env.http_host:
redirect('http://domain2/app2/prettyurl/page/home')  # my home page 
in plugin_wiki

I won't even mention about the hyphens in my plugin_wiki slugs.  I had to 
change them to underscores and then hack the plugin_wiki code to accept 
them.  What a huge amount of time for such small progress!  
 
Lessons to be learnt:
1. Why have 3 different routing systems?  One obvious way of doing 
things?  ha!
2. Regex is almost always beyond someone like me -- unless I have 
recipes to follow.  All the obvious routing ideas should be spelt out in 
one list.  There aren't that many mainstream ideas for routing.  For 
example,  what is anyone supposed to make of this?

(r'.*http://otherdomain.com.* /app/ctr(?P.*)', r'\g')

I may possibly be the only person in the group to have found it 
incomprehensible,  which is indeed a pity because it looks as if it might 
have been exactly what I wanted.  Sadly, I still don't understand it after 
a full day.  This list is full of routing questions,  none of which seemed 
to quite spell it out.

Sorry for ranting a bit,  and thanks for listening.  The only route I need 
now is the route to the nearest bar!

Best regards,  David

-- 





Re: [web2py] App does not exist or your are not authorized when deploying layout plugin

2012-06-26 Thread LightDot
Correct. AFAIK, you're not supposed to overwrite the app's default 
layout.html with the one from a plugin.

You can include a custom layout, ie. /views/plugin_layout_name/layout.html, 
but not /views/layout.html.

Regards,
Ales

On Tuesday, June 26, 2012 11:59:40 PM UTC+2, François Delpierre wrote:
>
> No, it's not a permission problem.
> It seems to happen when I include the view/layout.html file in the w2p 
> file by issuing the tar command manually as described by Massimo.
> Here is the command I use :
>
> tar zcvf ../web2py.plugins.name_layout.w2p views/layout.html 
> views/plugin_layout_name/* static/plugin_layout_name/*
>
> Regards,
>
>

-- 





Re: [web2py] Short way to update or insert data from SQLFORM.factory into the main db.my_table ??? ...

2012-06-26 Thread Don_X
Hello Anthony, ...

I have tried the suggested line of code ...
the following way, based on my function index(): in the controller the 
filter field is 'email_check'

so I have entered :
db.auth_user.insert(**db.auth_user.email_check(form.vars))
 but I get an error msg ! .. should I put it in brakets ? in parenthesis ?? 
.. ... 

 I have tried it with an underscore in front of it ... .. still .. it is 
not working ? ... help me out here .. please ...

and I am also supposing that the timestamp field will be updated 
automatically ...

please advise

Don


On Tuesday, 26 June 2012 08:23:57 UTC-4, Anthony wrote:
>
> db.auth_user.insert(**db.auth_user._filter_fields(form.vars))
>
> That will filter out the fields that don't belong to the table.
>
> Anthony
>
> On Tuesday, June 26, 2012 8:12:39 AM UTC-4, Don_X wrote:
>>
>> Thank you Bruno I believe  it would of work  but ... I get an error 
>> ...
>>
>>  Field email_check does not belong to the 
>> table
>>
>> I think it is because I check the email entered in the SQLFORM.factory 
>> form and the field e-mail_check does not exist in the table 
>> it is just a verification scheme !
>> is there a way for me to do the same thing ( updating the database ) ... 
>> without that specific field and without doing it line by line ? ...
>>
>> and please tell me .. does the timestamp field in the auth_user table get 
>> updated automatically ...
>>
>> thanks
>>
>> Don
>>
>> On Monday, 25 June 2012 23:17:23 UTC-4, rochacbruno wrote:
>>>
>>> if form.process().accepted:
>>>
>>>db.auth_user.insert(**form.vars)
>>>
>>>response.flash = T('Quick Sign-up Accepted ! - Check your e-mail 
>>> !')
>>>
>>>
>>

-- 





Re: [web2py] App does not exist or your are not authorized when deploying layout plugin

2012-06-26 Thread François Delpierre
No, it's not a permission problem.
It seems to happen when I include the view/layout.html file in the w2p file 
by issuing the tar command manually as described by Massimo.
Here is the command I use :

tar zcvf ../web2py.plugins.name_layout.w2p views/layout.html 
views/plugin_layout_name/* static/plugin_layout_name/*

Regards,

-- 





[web2py] Re: web2py book now free in PDF

2012-06-26 Thread ionel
Thank you!

-- 





[web2py] Re: How capable is the ajax function in web2py.js?

2012-06-26 Thread Cliff Kachinske
Daniel,

Do your table manipulation in Web2py using view helpers.

Example:
thead = THEAD(TR(TH("something'), TH('this'), TH('that'), TH('theother')))
tbody = TBODY()
for r in rows:
   tbody.append(TR(
 r.something, r.this, r.that, r.theother
  ))
return TABLE(thead, tbody)

There are other examples with even fewer lines of code in the manual at 
http://web2py.com/books/default/chapter/29/5#Built-in-helpers.

This is just how I like to do it.

On Tuesday, June 26, 2012 5:12:49 AM UTC-4, Daniel Gonzalez wrote:
>
> Thanks for both your comments, they are good food for thought.
>
> My experience with Javascript is very limited and I want to avoid it as 
> much as possible. That is why I have considered - and tried - pyjamas 
> (which has been working very well for me: very easy to use, and up to now 
> very robust). I have some worries:
>
>1. This approach means I must keep coding, and integrating, two 
>technologies: web2py and pyjamas. It is still way better than having to 
>code in javascript.
>2. One thing that worries me about implementing all this logic 
>client-side is that a big chunk of my code will be autogenerated 
>javascript. That means, if I run into trouble, I guess it will be very 
>difficult to solve any problems I may have.
>3. And this a side issue, but I need to mention it nevertheless: I am 
>having a hard time integrating the CSS from pyjamas and web2py. Since some 
>styles from web2py (table, td, ...) override my styles, suddenly all my 
>pyjamas components are looking very bad. This is a very painful problem, 
>which I do not know how to solve. Do you have any suggestions on how to 
>debug CSS issues? I am limited to Chrome inspector basically.
>
> So what I was aiming at now is to use as little client side logic as 
> possible: just perform some AJAX calls to get the data ready for 
> presentation. Actually, I was even planning to do (for example) HTML table 
> rendering on the server (I am considering 
> markup.py for 
> that) and send it via AJAX to the client to be displayed. Basically, the 
> server would be in charge of updating the html in the client. The same that 
> web2py does with controllers/views/functions, but for dynamic content, 
> which must be sent via AJAX.
>
> I have not yet decided which approach to take. If you have experience in 
> this scenario, your comments are welcome!
>
> Thanks,
> Daniel
>

-- 





Re: [web2py] Re: Creating users on checkout?

2012-06-26 Thread RKS
Not to mention the redirect to user/profile I mentioned in another post. 
Trying to invoke auth.register() with a logged in user will force a 
redirect. Instead, I think it's best I just select the auth.users table and 
write directly to the database. But easier said than done.

On Monday, June 25, 2012 2:53:07 PM UTC-5, RKS wrote:
>
> Also, if you were to use the {{=*.custom.widget.email}} method you get 
> errors when a logged in user is using the form. The form tries to act like 
> a registration form instead of a checkout form. 
>
> If I use things in the inputs like {{=auth.user.first_name}} it works to 
> prefill values if users are logged in. But afaik it looks like setting the 
> values to the auth.users db manually after checkout is the only way to go. 
> I could be wrong thought since I'm not as good on web2py as many/most other 
> people here.
>

-- 





[web2py] Re: Keyword argument 'object' does not work for auth.add_permission?

2012-06-26 Thread Anthony

>
> I did read the manual but perhaps I'm missing something? 
> From Page 411 in the web2py manual:
>
> auth.add_permission(group_id, 'name', 'object', record_id)
>
> Note, 'object' is in quotes there, which is meant to indicate it is an 
example value, not the actual keyword argument name. In fact, the name of 
the third argument to add_permission() is table_name (it is often used to 
give permissions on tables, though technically it can refer to any object, 
not just tables).

Anthony

-- 





[web2py] Keyword argument 'object' does not work for auth.add_permission?

2012-06-26 Thread Bill Thayer


Trying to add crud permissions to my application but I must be making this 
harder than it should be. After defining a table in db.py I use a 
nested loop to add the crud permissions. Being a newbie I assumed that I could 
name my arguments if I have reason not to insert them in the 
correct order:

for group in [3,4,5]:
for permission in ["create","read","update"]:
auth.add_permission(group_id=group, name=permission, record_id=0, 
object='charge_numbers')

however i get this error:
TypeError: add_permission() got an unexpected keyword argument 'object'

I did read the manual but perhaps I'm missing something? 
>From Page 411 in the web2py manual:

auth.add_permission(group_id, 'name', 'object', record_id)
gives permission "name" (user defined) on the object "object" (also user
defined) to members of the group group_id. If "object" is a tablename then
the permission can refer to the entire table by setting record_id to a 
value of
zero, or the permission can refer to a specific record by specifying a 
record_id
value greater than zero. 


Thank you,
Bill

-- 





[web2py] Re: Rocket server truncating long responses

2012-06-26 Thread Massimo Di Pierro
If you can reproduce. Chould you try wireshark to do a packet capture? I 
would like to see what is going on.
Tim is a new dad and has not been responsive. I will try an attempt to fix 
this myself (although I cannot repcoduce it) else we wil revert to 
cherrypy. 

On Tuesday, 26 June 2012 07:04:15 UTC-5, Álvaro José Iradier wrote:
>
> Hi,
>
> I am developing an application that needs to return a big report page, 
> with a lot of data. We were testing the application using the integrated 
> rocket server, and the report was working correctly when accessing the app 
> on the local network.
>
> However, when connection from the outside via a DSL router, making a NAT 
> to the web2py http server, the response page gets truncated after about 
> 15-30 seconds (could not determine an exact period). The browser stops 
> receiving data, and the page is truncated. Capturing traffic with wireshark 
> shows the remote end is finishing the connection (FIN flag set) before 
> sending all data, but the Content-Length header was correctly set to a 
> higher value.
>
> The problem dissapears when running web2py with lighttpd via FastCGI.
>
> The truncate problem also dissapears if instead of accessing directly to 
> the web server, we make a SSH tunnel to the Linux machine hosting the 
> web2py application, and requesting the report though the tunnel, but 
> probably the SSH tunnel is retrieving the full page, then buffering it 
> through the tunnel.
>
> Has anybody hit the same problem? It there a maximum response time for 
> rocket server? I found there is a maximum request time, but the request is 
> being processed quite fast, less than 1 second. The problem is *sending* 
> the response, which is getting longer.
>
> Thanks.
>
>

-- 





Re: [web2py] Re: Error importing ldap_auth module

2012-06-26 Thread José Luis Redrejo
2012/6/26 ehgonzalez :
> José this is my configuration,
>
> db.py:
> from gluon.contrib.login_methods.ldap_auth import ldap_auth
>
> If mod_php is on:
> ERROR:root:missing ldap, try "easy_install python-ldap" (apache log error)
>
> If mod_php is off, the application works OK.
>
> mod_php  5.3.3
> mod_wsgi 3.3
> I've installed web2py from source.


I can not tell you where the problem is . It looks like php mod is
changing something in the way the directories are seen by
wsgihandler.py, thus it can not find gluon or gluon.contrib.
I think you should add gluon to your python path, so you avoid this problem.
That's why using the Debian package python-gluon in a Debian (or
Debian derivative distribution) helps, because the package allows you
doing
import gluon
at any directory in your machine.
You can do it even manually placing gluon dir from web2py sources in
the directory where your python modules are stored in your
distribution.




>
> Apache:
> 
>   ServerName web2py-test.foo.com
>   WSGIDaemonProcess web2pytest user=www-data group=www-data \
>    display-name=%{GROUP}
>   WSGIProcessGroup web2pytest
>   WSGIScriptAlias / /var/www/web2pytest/wsgihandler.py
>
>   
>     AllowOverride None
>     Order Allow,Deny
>     Deny from all
>     
>   Allow from all
>     
>   
>
>   AliasMatch ^/([^/]+)/static/(.*) \
>    /var/www/web2pytest/applications/$1/static/$2
>   
>     Order Allow,Deny
>     Allow from all
>   
>
>   
>       Deny from all
>   
>
>   LogLevel info
>   CustomLog /var/log/apache2/web2pytest_access.log common
>   ErrorLog /var/log/apache2/web2pytest_error.log
> 



I can not see any diferences in this configuration with the one I'm
using and I've sent in a previous email.


>
> Eduardo.
>
> El martes, 26 de junio de 2012 13:07:43 UTC-4:30, Bill Thayer escribió:
>>
>>
>> Hi Jose,
>>
>> Not to hijack your thread but quickly
>>
>> Your are probably as busy as the rest of us but I'd love to see a recipe
>> or tutorial on how you got php MyAdmin to run with web2py.
>>
>> Regards,
>> Bill
>
> --
>
>
>

-- 





Re: [web2py] Re: Error importing ldap_auth module

2012-06-26 Thread José Luis Redrejo
2012/6/26 Bill Thayer :
>
> Hi Jose,
>
> Not to hijack your thread but quickly
>
> Your are probably as busy as the rest of us but I'd love to see a recipe or
> tutorial on how you got php MyAdmin to run with web2py.
>


There 's not a special recipe. I'm using Debian, with python-gluon
installed and phpldapadmin installed as packages too.
In apache, I place my web2py configuration sometimes on
/etc/apache2/conf.d and some others on /etc/apache2/sites-available,
depending if I install my web2py application using a debian package
(then I use conf.d) or by hand (then I use sites-available, because
it's simpler)

I'm attaching the configuration I used in my latest project. This one
used a sqlite backend, not a ldap backend, and lives in a server
together with mediawiki , which uses php too. I needed both http and
https access, and I always install the application directory at
/var/web2py/applications , the application name in this case was aeee.

Hope this helps.


> Regards,
> Bill
>
> --
>
>
>

-- 





agenciaevaluacion
Description: Binary data


[web2py] Re: Unable to create timestamp: tzinfo error

2012-06-26 Thread Niphlod
hey, requires is expecting :
- a validator
- a list of validators

If you need to have a "last_modified" column, i.e. gets a value only when 
row is updated, than:

db.define_table( 
'sometb', 
Field('name', requires=[IS_NOT_EMPTY(), IS_NOT_IN_DB(db, 'sometb.name')]), 

Field('last_modified', 'datetime', update=request.now), 
format='%(name)s' 
) 

if you want also the column to have a value when the row is inserted, than:

db.define_table( 
'sometb', 
Field('name', requires=[IS_NOT_EMPTY(), IS_NOT_IN_DB(db, 'sometb.name')]), 

Field('created_or_last_modified', 'datetime', update=request.now, 
default=request.now), 
format='%(name)s' 
) 

to exclude that "by default" in forms, you can set its readable and 
writable attributes to False, i.e.

Field('created_or_last_modified', 'datetime', update=request.now, 
default=request.now, writable=False, readable=False), 


On Tuesday, June 26, 2012 9:03:40 PM UTC+2, Alec Taylor wrote:
>
> I'm confused at how to implement automatic timestamps to tables. 
>
> So I want to know when each record was created (might have a separate 
> field for "last modified"). 
>
> The form should either have an uneditable field with the current 
> timestamp xor—preferably—it shouldn't be present in the form. 
>
> Here's a test-case: 
>
> # Models 
>
> from datetime import datetime 
>
> db.define_table( 
> 'sometb', 
> Field('name', requires=[IS_NOT_EMPTY(), IS_NOT_IN_DB(db, 
> 'sometb.name')]), 
>
> Field('date_created', 'datetime', requires=datetime.now, 
> default=datetime.now), 
> format='%(name)s' 
> ) 
>
> # Controllers 
>
> def sometb(): 
> return dict(tbform=crud.create(db.group_of_events)) 
>
> # Views 
>
> {{if 'tbform' in globals():}} 
> {{=tbform}} 
> {{else:}} 
> Form not found :[ 
> {{pass}} 
>
> # {{pass}}! 
>
> Thanks for your time, 
>
> Alec Taylor 
>

-- 





Re: [web2py] Re: Best practice using scheduler as a task queue?

2012-06-26 Thread Niphlod
problem here started as "I can't ensure my app to insert only one task per 
function", that is not a scheduler problem "per se": it's a common database 
problem. Would have been the same if someone created a 
db.define_table('mytable',
 Field('name'),
 Field('uniquecostraint')
)
and have to ensure, without specifying Field('uniquecostraint', 
unique=True) that there are no records with the same value into the column 
uniquecostraint.

>From there to "now I have tasks stuck in RUNNING status, please avoid using 
the scheduler" without any further details, the leap is quite 
"undocumented".

And please do note that scheduler in trunk has gone under some changes: 
there was a point in time where abnormally killed schedulers (as kill 
-SIGKILL the process) left tasks in RUNNING status, that would not be 
picked up by subsequent scheduler processes.

That was a design issue: if a task is RUNNING and you kill scheduler while 
the task was processed, you had no absolutely way to tell what the function 
did (say, send a batch of 500 emails) before it was actually killed. 
If the task was not planned properly it could send e.g. 359 mails, be 
killed, and if it was picked up again by another scheduler after the "first 
killed round" 359 of your recipients would get 2 identical mails.
It has been decided to requeue RUNNING tasks without any active worker 
doing that (i.e. leave to the function the eventual check of what has been 
done), so now RUNNING tasks with a dead worker assigned get requeued.

With other changes (soon in trunk, the previously attached file) you're 
able to stop workers, so they may be killed "ungracefully" being sure that 
they're not processing tasks.

If you need more details, as always, I'm happy to help, and other 
developers too, I'm sure :D

-- 





[web2py] Re: How does the auto-increment on field id work? I'd like to use the method in a table.

2012-06-26 Thread Anthony
:-)

On Tuesday, June 26, 2012 2:46:15 PM UTC-4, RKS wrote:
>
> Perfect. I got the web2py Application cookboo eBook but you really need to 
> write a book. I'd buy it. You help me more than anyone. Thanks a bundle.
>

-- 





[web2py] Unable to create timestamp: tzinfo error

2012-06-26 Thread Alec Taylor
I'm confused at how to implement automatic timestamps to tables.

So I want to know when each record was created (might have a separate
field for "last modified").

The form should either have an uneditable field with the current
timestamp xor—preferably—it shouldn't be present in the form.

Here's a test-case:

# Models

from datetime import datetime

db.define_table(
'sometb',
Field('name', requires=[IS_NOT_EMPTY(), IS_NOT_IN_DB(db, 'sometb.name')]),
Field('date_created', 'datetime', requires=datetime.now,
default=datetime.now),
format='%(name)s'
)

# Controllers

def sometb():
return dict(tbform=crud.create(db.group_of_events))

# Views

{{if 'tbform' in globals():}}
{{=tbform}}
{{else:}}
Form not found :[
{{pass}}

# {{pass}}!

Thanks for your time,

Alec Taylor

-- 





[web2py] Re: How does the auto-increment on field id work? I'd like to use the method in a table.

2012-06-26 Thread RKS
Perfect. I got the web2py Application cookboo eBook but you really need to 
write a book. I'd buy it. You help me more than anyone. Thanks a bundle.

-- 





Re: [web2py] Re: Error importing ldap_auth module

2012-06-26 Thread ehgonzalez
José this is my configuration,

db.py:
from gluon.contrib.login_methods.ldap_auth import ldap_auth

If mod_php is on:
ERROR:root:missing ldap, try "easy_install python-ldap" (apache log error)

If mod_php is off, the application works OK.

mod_php  5.3.3
mod_wsgi 3.3
I've installed web2py from source. 

Apache:

  ServerName web2py-test.foo.com
  WSGIDaemonProcess web2pytest user=www-data group=www-data \
   display-name=%{GROUP}
  WSGIProcessGroup web2pytest
  WSGIScriptAlias / /var/www/web2pytest/wsgihandler.py

  
AllowOverride None
Order Allow,Deny
Deny from all

  Allow from all

  

  AliasMatch ^/([^/]+)/static/(.*) \
   /var/www/web2pytest/applications/$1/static/$2
  
Order Allow,Deny
Allow from all
  
  
  
  Deny from all
  

  LogLevel info
  CustomLog /var/log/apache2/web2pytest_access.log common
  ErrorLog /var/log/apache2/web2pytest_error.log


Eduardo.

El martes, 26 de junio de 2012 13:07:43 UTC-4:30, Bill Thayer escribió:
>
>
> Hi Jose,
>
> Not to hijack your thread but quickly 
>
> Your are probably as busy as the rest of us but I'd love to see a recipe 
> or tutorial on how you got php MyAdmin to run with web2py.
>
> Regards,
> Bill

-- 





[web2py] SMTP authentication with gmail

2012-06-26 Thread aungsan
Please let me know anything wrong in the following code. 

from gluon.tools import Auth, Crud, Service, PluginManager, prettydate
auth = Auth(db, hmac_key = Auth.get_or_create_key())

auth.settings.create_user_groups=False
auth.settings.actions_disabled=['register','change_password','request_reset_password','retrieve_username','profile']
auth.settings.remember_me_form = False

## create all tables needed by auth if not custom tables
#auth.define_tables(username=True, migrate = False, fake_migrate = True)
auth.define_tables(migrate = False, fake_migrate = True)

from gluon.contrib.login_methods.email_auth import email_auth
auth.settings.login_methods.append(
email_auth("smtp.gmail.com:587", "@gmail.com"))

I am having the same problem. How did you fix it? Let say, if port 587 is 
 not working, what kind of error do you have. 

For me, it return no error at all. Just show me that invalid login.

Any idea ? 

-- 





[web2py] Re: email_auth with GMail and fluxflex

2012-06-26 Thread aungsan
I am having the same problem. How did you fix it? Let say, if port 587 is 
 not working, what kind of error do you have. 

For me, it return no error at all. Just show me that invalid login.

Any idea ? 

-- 





Re: [web2py] Re: Best practice using scheduler as a task queue?

2012-06-26 Thread Alec Taylor
Wouldn't lock-free mechanisms be more useful?

On Wed, Jun 27, 2012 at 4:10 AM, Andrew  wrote:
> Michael, I intend to use the scheduler for infinite looping background tasks. 
>  From what I have read in this thread, I see the issue is that you are most 
> concerned about race conditions.
>
> I am yet to do this with web2py scheduler,  but why not have something in 
> cron at reboot to insert and perhaps a regular task to check, if you like.  
> We implement mutex functions for this and they can be as fancy as you like.   
>   http://en.wikipedia.org/wiki/Mutual_exclusion
> Either enforce uniqueness at the database, or have something in your mutex 
> function that will only allow one process at a time to attempt an insert.  A 
> lock token file perhaps.
> Web2py should enforce uniqueness, but you can also implement you own mutex 
> function.
>
> As for the bugs, these aren't design flaws, they just need to get fixed.
>
> I have not given up on the scheduler.
>
> --
>
>
>

-- 





[web2py] Re: Best practice using scheduler as a task queue?

2012-06-26 Thread Andrew
Michael, I intend to use the scheduler for infinite looping background tasks.  
From what I have read in this thread, I see the issue is that you are most 
concerned about race conditions.

I am yet to do this with web2py scheduler,  but why not have something in cron 
at reboot to insert and perhaps a regular task to check, if you like.  We 
implement mutex functions for this and they can be as fancy as you like. 
http://en.wikipedia.org/wiki/Mutual_exclusion
Either enforce uniqueness at the database, or have something in your mutex 
function that will only allow one process at a time to attempt an insert.  A 
lock token file perhaps.  
Web2py should enforce uniqueness, but you can also implement you own mutex 
function.

As for the bugs, these aren't design flaws, they just need to get fixed.  

I have not given up on the scheduler.

-- 





[web2py] Re: Parsing python from db fields?

2012-06-26 Thread Anthony
Can you pack and attach a minimal application that reproduces the problem 
(use a SQLite db with at least one blog.body entry that demonstrates the 
problem)?

Anthony

On Tuesday, June 26, 2012 12:57:30 PM UTC-4, RKS wrote:
>
> View source does not show anything below the content inside that XML. 
>
> For example, I have a layout.html with the standard {{include}} {{ include 
> footer.html}} etc.
>
> The place where I have this XML element fall within the view that's 
> extending this layout. So no matter what, there should be a footer at the 
> very least. There's none. Even after the XML I have HTML within that view 
> that no longer exists in source. The new source just ends after the content 
> of blog.body like web2py no longer recognizes anything else.
>
> That's why I added in the {{pass}} trying to force web2py to stop whatever 
> it is doing to ignore the rest of the HTML.
>
> There is no  since the data being called inside the blog.body is 
> just a field from the db. I know I could have put a  in the field or 
> in the included view it's calling but I double checked after reading your 
> comment and there is none. All that html after the snippet is just like 
> Keyser Soze.
>

-- 





[web2py] Re: Authentication

2012-06-26 Thread Anthony

>
> from gluon.contrib.login_methods.ldap_auth import ldap_auth
>
> auth.settings.login_methods.append(ldap_auth(mode='ad',
>server='my.domain.controller',
>base_dn='ou=Users,dc=domain,dc=com'))
>
>
> But my question is do I still have to keep the following lines ? 
>
> from gluon.tools import Auth, Crud, Service, PluginManager, prettydate
> auth = Auth(db, hmac_key = Auth.get_or_create_key())
>
> What is auth = Auth(db, hmac_key = Auth.get_or_create_key()) actually does 
> ? If i comment those line, I got error saying that auth is not defined.
>

auth = Auth(...) defines the Auth object -- you must do that if you want to 
use the Auth system. The LDAP code above references auth, so it must be 
created before it is referenced. You do not necessarily need Crud, Service, 
or PluginManager (you do not need them at all for Auth).

Anthony
 

-- 





Re: [web2py] Re: Error importing ldap_auth module

2012-06-26 Thread Bill Thayer

Hi Jose,

Not to hijack your thread but quickly 

Your are probably as busy as the rest of us but I'd love to see a recipe or 
tutorial on how you got php MyAdmin to run with web2py.

Regards,
Bill

-- 





[web2py] Re: After LDAP authentication, where can I change some actions?

2012-06-26 Thread aungsan
same here. Please keep me in your circle. If anyone know the answer, plz 
share with me :)

-- 





[web2py] Re: How does the auto-increment on field id work? I'd like to use the method in a table.

2012-06-26 Thread Anthony

>
> {{for i, (product_id, qty, total_price, product, options) in 
> enumerate(order):}}
>  id="value_pro_1" type="text" value="{{=qty}}" />
> -
> +
>
> So item two would be:
>
>  id="value_pro_2" type="text" value="{{=qty}}" />
> -
> +


If you want the numbers to increment from 1, you could do:


-
+

Or instead, you might consider using the product_id in place of (i + 1).

Anthony

-- 





[web2py] Re: ldap

2012-06-26 Thread aungsan
Thanks. From source, it work. I normally do dev on nix. This time, on 
windows. So I do not notice. I was even surprised when I do not see source 
to debug. ^_^

-- 





[web2py] Re: web2py book now free in PDF

2012-06-26 Thread Bill Thayer
Thank you!

On Tuesday, June 12, 2012 8:17:46 AM UTC-5, Massimo Di Pierro wrote:
>
> The official web2py book is now free for everybody:
>
> https://dl.dropbox.com/u/18065445/web2py/web2py_manual_4th.1.pdf
>
> Massimo
>

-- 





[web2py] Re: Authentication

2012-06-26 Thread aungsan
How about LDAP? 

I use the following as seen on site.


from gluon.contrib.login_methods.ldap_auth import ldap_auth
auth.settings.login_methods.append(ldap_auth(mode='ad',
   server='my.domain.controller',
   base_dn='ou=Users,dc=domain,dc=com'))


But my question is do I still have to keep the following lines ? 

from gluon.tools import Auth, Crud, Service, PluginManager, prettydate
auth = Auth(db, hmac_key = Auth.get_or_create_key())

What is auth = Auth(db, hmac_key = Auth.get_or_create_key()) actually does 
? If i comment those line, I got error saying that auth is not defined.

-- 





Re: [web2py] DAL performance vs executesql

2012-06-26 Thread pbreit
Massimo, any ideas on DAL performance? I wonder if it would make sense to 
have some flags to skip some of the non-essential processing?

-- 





[web2py] Re: Image Optimization

2012-06-26 Thread pbreit
There are some slices on making thumbnails:
http://www.web2pyslices.com/slice/search?q=thumbnail

-- 





[web2py] Re: static files extending layout.html

2012-06-26 Thread pbreit
I have an "html" directory in my views folder and place html snippets in 
there. Then you can include them in any view file with {{include 
'html/mysnippet.html'}}.

-- 





[web2py] Re: Parsing python from db fields?

2012-06-26 Thread RKS
View source does not show anything below the content inside that XML. 

For example, I have a layout.html with the standard {{include}} {{ include 
footer.html}} etc.

The place where I have this XML element fall within the view that's 
extending this layout. So no matter what, there should be a footer at the 
very least. There's none. Even after the XML I have HTML within that view 
that no longer exists in source. The new source just ends after the content 
of blog.body like web2py no longer recognizes anything else.

That's why I added in the {{pass}} trying to force web2py to stop whatever 
it is doing to ignore the rest of the HTML.

There is no  since the data being called inside the blog.body is 
just a field from the db. I know I could have put a  in the field or 
in the included view it's calling but I double checked after reading your 
comment and there is none. All that html after the snippet is just like 
Keyser Soze.

-- 





[web2py] Re: Parsing python from db fields?

2012-06-26 Thread Anthony
Just to be clear, are you saying web2py is not generating the HTML at all 
(i.e., if you do "view source" in the browser, the HTML simply isn't 
there), or is it that the content below that point is being generated but 
simply isn't being visually rendered by the browser (which could occur, for 
example, if your XML() object includes a closing  tag).

Anthony

On Monday, June 25, 2012 2:14:37 PM UTC-4, RKS wrote:
>
> This all works, but I can't wrap my head around why everything after this 
> snippet is no longer displayed. It does not even exist in the source. For 
> example, my code is like this:
>
> 
> {{import os}}
> {{from gluon.template import render}}
> {{=XML(render(blog.body,path=os.path.join(request.folder, 
> 'views'), context=globals()))}}
> {{pass}}
> 
>  
> 
> NEW USER?
>  src="{{=URL('static','images/button_register.png')}}" alt="Login/Register 
> to comment!" />
> 
> 
> CURRENT USER?
> {{=blog_form}}
> 
> 
> 
>
> Everything from the inserted comment () will not exist any 
> more after this. Go back to simple {{=XML(blog.body)}} and everything after 
> it displays fine. I've tried adding a pass, no pass, two passes, etc. But 
> it still appears from that point web2py is not recognizing regular html 
> anymore. Nothing after that will display at all.
>

-- 





Re: [web2py] Re: Error importing ldap_auth module

2012-06-26 Thread José Luis Redrejo
2012/6/26 ehgonzalez :
> Hi everyone,
>
> I've finally found out what was wrong in my system. I use apache2 + mod_php
> + wsgi, if I disable mod_php the application works Ok. Is there anyway to
> run mod_php and wsgi without problems?


I'm doing it in a lot of servers without any problem (runing a web2py
application which uses ldap as auth backend and phpldapadmin in the
same machine). There must be an error in your apache configuration or
in the way web2py is installed. I'm running it on Debian systems using
the python-gluon package.

Regards
José L.


>
> Eduardo.
>
> El jueves, 21 de junio de 2012 14:48:19 UTC-4:30, ehgonzalez escribió:
>>
>> Ldap utilities works OK. For example: ldapsearch -x -h mycompany.com -b
>> dc=mycompany,dc=com "(sAMAccountName=gonzalezej)".
>>
>> El jueves, 21 de junio de 2012 12:43:09 UTC-4:30, szimszon escribió:
>>>
>>> common ldap utilities are working? ldapsearch and co?
>>>
>>> 2012. június 21., csütörtök 17:34:45 UTC+2 időpontban ehgonzalez a
>>> következőt írta:

 You rigth, python version is 2.6.6. I copied ldap_auth.py from trunk but
 it's throwing same error.

 any ideas?

 El jueves, 21 de junio de 2012 10:18:43 UTC-4:30, szimszon escribió:
>
> Try to use ldap_auth.py from trunk. Just copy it over the old one.
>
> You say Python 2.7.3 but in the error there is a
>
> ... python2.6/dist-packages/ldap ...
>
>
> 2012. június 21., csütörtök 16:39:40 UTC+2 időpontban ehgonzalez a
> következőt írta:
>>
>> Hi,
>>
>> When I try to import the ldap_auth module in my db.py is throwing an
>> error. Here's the traceback:
>>
>> Traceback (most recent call last):
>>   File "/var/www/web2pytest/gluon/restricted.py", line 205, in
>> restricted
>> exec ccode in environment
>>   File "/var/www/web2pytest/applications/SMS/models/db.py", line 44,
>> in 
>> from gluon.contrib.login_methods.ldap_auth import ldap_auth
>>   File "/var/www/web2pytest/gluon/custom_import.py", line 293, in
>> __call__
>> fromlist, level)
>>   File "/var/www/web2pytest/gluon/custom_import.py", line 78, in
>> __call__
>> level)
>>   File "/var/www/web2pytest/gluon/contrib/login_methods/ldap_auth.py",
>> line 9, in 
>> raise e
>> SystemError: error 89 from ldap_set_option
>>
>>
>> Web2py's Shell:
>>
>> In [1] : import ldap
>>
>> In [2] : import ldap.filter
>>
>> In [3] : ldap.set_option( ldap.OPT_REFERRALS, 0 )
>> Traceback (most recent call last):
>>   File "/var/www/web2py/gluon/contrib/shell.py", line 225, in run
>> exec compiled in statement_module.__dict__
>>   File "", line 1, in 
>>   File "/usr/lib/python2.6/dist-packages/ldap/functions.py", line 124,
>> in set_option
>> _ldap_function_call(_ldap.set_option,option,invalue)
>>   File "/usr/lib/python2.6/dist-packages/ldap/functions.py", line 57,
>> in _ldap_function_call
>> result = func(*args,**kwargs)
>> SystemError: error 89 from ldap_set_option
>>
>> Debian 6.0.5, Apache 2.2.16, WSGI 3.3-2, Python 2.7.3, , web2py
>> 1.99.7.
>>
>>
>> Any help much appreciated.
>>
>> Eduardo.
>>
>>
>>
>>
>>
>>
> --
>
>
>

-- 





[web2py] Re: Error importing ldap_auth module

2012-06-26 Thread ehgonzalez
Hi everyone,

I've finally found out what was wrong in my system. I use apache2 + mod_php 
+ wsgi, if I disable mod_php the application works Ok. Is there anyway to 
run mod_php and wsgi without problems?

Eduardo.

El jueves, 21 de junio de 2012 14:48:19 UTC-4:30, ehgonzalez escribió:
>
> Ldap utilities works OK. For example: ldapsearch -x -h mycompany.com -b 
> dc=mycompany,dc=com "(sAMAccountName=gonzalezej)".
>
> El jueves, 21 de junio de 2012 12:43:09 UTC-4:30, szimszon escribió:
>>
>> common ldap utilities are working? ldapsearch and co?
>>
>> 2012. június 21., csütörtök 17:34:45 UTC+2 időpontban ehgonzalez a 
>> következőt írta:
>>>
>>> You rigth, python version is 2.6.6. I copied ldap_auth.py from trunk but 
>>> it's throwing same error.
>>>
>>> any ideas?
>>>
>>> El jueves, 21 de junio de 2012 10:18:43 UTC-4:30, szimszon escribió:

 Try to use ldap_auth.py from trunk. Just copy it over the old one.

 You say Python 2.7.3 but in the error there is a 

 ... python2.6/dist-packages/ldap ...


 2012. június 21., csütörtök 16:39:40 UTC+2 időpontban ehgonzalez a 
 következőt írta:
>
> Hi,
>
> When I try to import the ldap_auth module in my db.py is throwing an 
> error. Here's the traceback:
>
> Traceback (most recent call last):
>   File "/var/www/web2pytest/gluon/restricted.py", line 205, in restricted
> exec ccode in environment
>   File "/var/www/web2pytest/applications/SMS/models/db.py" 
> , line 
> 44, in 
> from gluon.contrib.login_methods.ldap_auth import ldap_auth
>   File "/var/www/web2pytest/gluon/custom_import.py", line 293, in __call__
> fromlist, level)
>   File "/var/www/web2pytest/gluon/custom_import.py", line 78, in __call__
> level)
>   File "/var/www/web2pytest/gluon/contrib/login_methods/ldap_auth.py", 
> line 9, in 
> raise e
> SystemError: error 89 from ldap_set_option
>
>
> Web2py's Shell:
>
> In [1] : import ldap
>
> In [2] : import ldap.filter
>
> In [3] : ldap.set_option( ldap.OPT_REFERRALS, 0 )
> Traceback (most recent call last):
>   File "/var/www/web2py/gluon/contrib/shell.py", line 225, in run
> exec compiled in statement_module.__dict__
>   File "", line 1, in 
>   File "/usr/lib/python2.6/dist-packages/ldap/functions.py", line 124, in 
> set_option
> _ldap_function_call(_ldap.set_option,option,invalue)
>   File "/usr/lib/python2.6/dist-packages/ldap/functions.py", line 57, in 
> _ldap_function_call
> result = func(*args,**kwargs)
> SystemError: error 89 from ldap_set_option
>
> Debian 6.0.5, Apache 2.2.16, WSGI 3.3-2, Python 2.7.3, , web2py 1.99.7.
>
> Any help much appreciated.
>
> Eduardo.
>
>
>
>
>
>
>

-- 





[web2py] Re: Parsing python from db fields?

2012-06-26 Thread RKS
In that trial I was trying to end the python, thinking possibly it's 
affecting what follows. Deleting it does nothing. 

Sort of like {{if:}},{{else:}},{{pass}}. I was just trying to make it 
render that python and then stop.

On Tuesday, June 26, 2012 5:16:49 AM UTC-5, Cliff Kachinske wrote:
>
> What is the purpose of this line of code?
>
> {{pass}}
>
>
> What happens if you delete it?
>
> On Monday, June 25, 2012 2:17:32 PM UTC-4, RKS wrote:
>>
>> BTW, it's EVERYTHING in html after that snippet. It won't display the 
>> footer or anything.
>>
>

-- 





[web2py] How does the auto-increment on field id work? I'd like to use the method in a table.

2012-06-26 Thread RKS
I have some html:

{{for i, (product_id, qty, total_price, product, options) in 
enumerate(order):}}

-
+

I have a js function that takes min_pro_1 and plus_pro_1 and allows them to 
decrement of increment value_pro_1. So they're just buttons a user can 
click and the product quantity goes up and down. Well, the js I have needs 
each quantity field to have a unique id (imagine that) but my {{for i}} 
python just creates each item with the same id.  How do I increment these 
ids to ensure valid code and proper functioning of the js?

So item two would be:


-
+

And so on. The function I've got in my controller now is:

def increment(self,key,value=1):
self.locker.acquire()
try:
if key in self.storage:
value=self.storage[key][0]+value
self.storage[key]=(value)
except BaseException, e:
self.locker.release()
raise e
self.locker.release()
return value

And I figured I could do something like:

{{for i, (product_id, qty, total_price, product, options) in 
enumerate(order):}}

-
+

-- 





Re: [web2py] VPS Hosting in Canada

2012-06-26 Thread Richard Vézina
iWeb!

Richard

On Tue, Jun 26, 2012 at 10:22 AM, Rod Watkins  wrote:

> Hello everyone,
>
> I will soon be needing a hosting provider, preferably a vps hosting
> service, with servers based in Canada (for privacy and legal reasons). I
> know that there are posts on hosting services, but I wanted to get feedback
> from anyone who has experience with one's based in or with servers
> physically within Canada. I like the idea of a vps server rather than
> shared hosting since it avoids several complications. So if I could get any
> recommendations or warning about who to avoid, I would really appreciate
> your input.
>
> Thanks
>
> Rod Watkins
>
>  --
>
>
>
>

-- 





[web2py] VPS Hosting in Canada

2012-06-26 Thread Rod Watkins
Hello everyone,

I will soon be needing a hosting provider, preferably a vps hosting 
service, with servers based in Canada (for privacy and legal reasons). I 
know that there are posts on hosting services, but I wanted to get feedback 
from anyone who has experience with one's based in or with servers 
physically within Canada. I like the idea of a vps server rather than 
shared hosting since it avoids several complications. So if I could get any 
recommendations or warning about who to avoid, I would really appreciate 
your input.

Thanks

Rod Watkins

-- 





[web2py] Routes - simple requirement, but how??

2012-06-26 Thread villas
Hi All,

I have spent a full day trying to make simple routing work.  Please,  I 
have tried all the routers and read everything I can.  Could anyone please 
help?

Apache / wsgi  standard setup without any changes.  Single instance of 
web2py

Two domains and two apps:
domain1.com  ->  app1
domain2.com  ->  app2

One other URL renaming pattern:  
plugin_wiki  ->  prettyurl

Tests:
domain1.com/prettyurl/page/home  ->  /app1/plugin_wiki/page/home
domain2.com/prettyurl/page/home  ->  /app2/plugin_wiki/page/home
domain2.com/default/myfunc  ->  /app2/default/myfunc

This is such a standard requirement,  surely it cannot be so difficult??

Regards,
David

-- 





[web2py] Re: Authentication

2012-06-26 Thread Anthony
See http://web2py.com/books/default/chapter/29/9#Manual-Authentication.

if request.vars:
auth.login_bare(request.vars.ID, request.vars.pass)

But it's dangerous to put the login credentials in the URL.

Anthony

On Tuesday, June 26, 2012 12:42:25 AM UTC-4, aungsan wrote:
>
> I got following issue with web2py Authentication.
>
> I have to authenticate through URL "
> http://www.example.com/something/q?ID='username'&pass='password'"
>
> It return true or false. I cannot go and change it. And I have to do 
> authentication with it for sure.
>
> After I got true or false, I would like to insert username and password 
> into web2py auth database and set login flag. So that user is logged in.
>
> How could I implement it ?
>
>

-- 





[web2py] Re: invalid literal for int() with base 10: ''

2012-06-26 Thread Anthony
To be clear, '%(names)' should be '%(name)s' in all cases.

Anthony

On Tuesday, June 26, 2012 1:05:13 AM UTC-4, Annet wrote:
>
> In all your table definitions you have format='%(name)' except in 
> base_countries table, where you have format='%(name)s'.
>
> I don't understand the trace back, the error is caused by 
> format='%(name)s', which is what I have in my table definitions, and which 
> doesn't cause any errors.
>
>
> Kind regards,
>
> Annet
>

-- 





[web2py] Re: static files extending layout.html

2012-06-26 Thread Anthony
If they extend a layout and therefore must be generated dynamically, they 
cannot be served as static files. Static files have to be fixed documents 
that can be served without running any app code. If you need to generate 
the files dynamically based on web2py templates, treat them like any other 
web2py page. You might create a single function, and serve the appropriate 
content based on request.args(0) -- you could use that to set response.view 
to point to the correct view file with the requested content.

Anthony

On Tuesday, June 26, 2012 7:43:13 AM UTC-4, Annet wrote:
>
> I'd like to put some static files, like disclaimer.html and privacy.html 
> in /static/files/. These files extend a default/layout.html view.
>
> What is the best way do this? Have a controller with a function for every 
> static file and in the layout file have {{include 
> 'static/files/disclaimer.html'}}? Or is there a better way to do this?
>
>
> Kind regards,
>
> Annet
>

-- 





[web2py] Re: ldap

2012-06-26 Thread Anthony
Are you running web2py from source or using the Windows binary? If the 
latter, the web2py binary includes its own Python interpreter and does not 
see or use anything from your machine's Python installation. If you have 
Python installed, run web2py from source instead (it's just as easy to 
download and run).

Anthony

On Tuesday, June 26, 2012 1:36:14 AM UTC-4, aungsan wrote:
>
> from gluon.contrib.login_methods.ldap_auth import ldap_auth
> auth.settings.login_methods = [ldap_auth(mode='ad',
>server='abc.google.com', base_dn='ou=Users, dc=google,dc=com')]
>
> I am having the following error.
>
> File "gluon/contrib/login_methods/ldap_auth.py", line 9, in 
> ImportError: No module named ldap
>
>
> I installed easy_install python-ldap.
>
> I test with just a line in test.py and run python test.py
>
> import ldap
>
> See no error.
>
> i re-install by msi packages. 
>
>
> http://pypi.python.org/packages/2.7/p/python-ldap/python-ldap-2.4.10.win32-py2.7.msi#md5=7bcf356c590ea093f7c3ad410c155f82
>
> Test with simple import. It work. But web2py still giving error.
>
>

-- 





Re: [web2py] Short way to update or insert data from SQLFORM.factory into the main db.my_table ??? ...

2012-06-26 Thread Anthony
db.auth_user.insert(**db.auth_user._filter_fields(form.vars))

That will filter out the fields that don't belong to the table.

Anthony

On Tuesday, June 26, 2012 8:12:39 AM UTC-4, Don_X wrote:
>
> Thank you Bruno I believe  it would of work  but ... I get an error ...
>
>  Field email_check does not belong to the 
> table
>
> I think it is because I check the email entered in the SQLFORM.factory 
> form and the field e-mail_check does not exist in the table 
> it is just a verification scheme !
> is there a way for me to do the same thing ( updating the database ) ... 
> without that specific field and without doing it line by line ? ...
>
> and please tell me .. does the timestamp field in the auth_user table get 
> updated automatically ...
>
> thanks
>
> Don
>
> On Monday, 25 June 2012 23:17:23 UTC-4, rochacbruno wrote:
>>
>> if form.process().accepted:
>>
>>db.auth_user.insert(**form.vars)
>>
>>response.flash = T('Quick Sign-up Accepted ! - Check your e-mail 
>> !')
>>
>>
>

-- 





Re: [web2py] Short way to update or insert data from SQLFORM.factory into the main db.my_table ??? ...

2012-06-26 Thread Don_X
Thank you Bruno I believe  it would of work  but ... I get an error ...

 Field email_check does not belong to the 
table

I think it is because I check the email entered in the SQLFORM.factory form 
and the field e-mail_check does not exist in the table 
it is just a verification scheme !
is there a way for me to do the same thing ( updating the database ) ... 
without that specific field and without doing it line by line ? ...

and please tell me .. does the timestamp field in the auth_user table get 
updated automatically ...

thanks

Don

On Monday, 25 June 2012 23:17:23 UTC-4, rochacbruno wrote:
>
> if form.process().accepted:
>
>db.auth_user.insert(**form.vars)
>
>response.flash = T('Quick Sign-up Accepted ! - Check your e-mail !'
> )
>
>

-- 





[web2py] Rocket server truncating long responses

2012-06-26 Thread Álvaro José Iradier
Hi,

I am developing an application that needs to return a big report page, with 
a lot of data. We were testing the application using the integrated rocket 
server, and the report was working correctly when accessing the app on the 
local network.

However, when connection from the outside via a DSL router, making a NAT to 
the web2py http server, the response page gets truncated after about 15-30 
seconds (could not determine an exact period). The browser stops receiving 
data, and the page is truncated. Capturing traffic with wireshark shows the 
remote end is finishing the connection (FIN flag set) before sending all 
data, but the Content-Length header was correctly set to a higher value.

The problem dissapears when running web2py with lighttpd via FastCGI.

The truncate problem also dissapears if instead of accessing directly to 
the web server, we make a SSH tunnel to the Linux machine hosting the 
web2py application, and requesting the report though the tunnel, but 
probably the SSH tunnel is retrieving the full page, then buffering it 
through the tunnel.

Has anybody hit the same problem? It there a maximum response time for 
rocket server? I found there is a maximum request time, but the request is 
being processed quite fast, less than 1 second. The problem is *sending* 
the response, which is getting longer.

Thanks.

-- 





[web2py] static files extending layout.html

2012-06-26 Thread Annet
I'd like to put some static files, like disclaimer.html and privacy.html in 
/static/files/. These files extend a default/layout.html view.

What is the best way do this? Have a controller with a function for every 
static file and in the layout file have {{include 
'static/files/disclaimer.html'}}? Or is there a better way to do this?


Kind regards,

Annet

-- 





[web2py] Re: Using jquery to put default value in a field

2012-06-26 Thread Johann Spies

Sorry for the noise. The following code did the job:

$(document).ready(function() {
$('#no_table_surname').change(function() {
var van = $('#no_table_surname').val();
var fn = $('#no_table_firstname').val();
$('#no_table_name').val(van + ' , ' + fn);
});
$('#no_table_firstname').change(function() {
var van = $('#no_table_surname').val();
var fn = $('#no_table_firstname').val();
$('#no_table_name').val(van + ' , ' + fn);
});
});


Regards
Johann

-- 





[web2py] Using jquery to put default value in a field

2012-06-26 Thread Johann Spies
Using the following model:

db.define_table('akb_authors',
 Field('surname'),
 Field('firstname'),
 Field('name'),
 )
self.db.akb_authors.surname.widget = suggest_widget(self.db.
akb_authors.surname,
limitby = (0, 20
), min_length = 2)
self.db.akb_authors.firstname.widget = suggest_widget(self.db.
akb_authors.firstname,
limitby = (0, 20
), min_length = 2)


Using SQLFORM.factory which includes other fields not shown here I want to 
the 'name' field to have a default value formed by the first two fields 
like this:  'surname' + ' , ' + 'firstname' 

I have tried with the following code and it is doing nothing for what I can 
see and I am too much of a beginner with jquery/javascript to know how to 
debug it using Firebug:


$(document).ready(function() {
$('form:input[name = "surname"]').change(function() {
var van = $('#no_table_surname').val();
var fn = $('#no_table_firstname').val();
$('#no_table_name').val(van + ' , ' + fn);
});
$('form:input[name = "firstname"]').change(function() {
var van = $('#no_table_surname').val();
var fn = $('#no_table_firstname').val();
$('#no_table_name').val(van + ' , ' + fn);
});

   

What am I doing wrong?

Regards
Johann

-- 





[web2py] Image Optimization

2012-06-26 Thread Sanjeet Roy
Can anyone tell me how can i optimize the image when the user will be 
uploaded ? Acually i want to create a web application where the user can 
upload and see the image on the categorization of album.i want optimize 
image should be appeared in the thumbnail 

-- 





[web2py] Re: Parsing python from db fields?

2012-06-26 Thread Cliff Kachinske
What is the purpose of this line of code?

{{pass}}


What happens if you delete it?

On Monday, June 25, 2012 2:17:32 PM UTC-4, RKS wrote:
>
> BTW, it's EVERYTHING in html after that snippet. It won't display the 
> footer or anything.
>

-- 





[web2py] Re: which files are checked for menu?

2012-06-26 Thread song
Thanks a lot,  Massimo !!!



2012년 6월 26일 화요일 오전 10시 45분 9초 UTC+9, song 님의 말:
>
> Hi!
>
> I'm studying  hard.
> I will change the  menu in the top of the screen. There are some menus 
> like Login, Lost Password.
> But unhappily there are no menu.py ( in  models directory).
>
> I want to change the menus including some others like the Login, Lost 
> Password, Register   etc..
>
> Which files will be changed ?  main  db files, or controllers ?
>
>

-- 





[web2py] Re: How capable is the ajax function in web2py.js?

2012-06-26 Thread Daniel Gonzalez
Thanks for both your comments, they are good food for thought.

My experience with Javascript is very limited and I want to avoid it as 
much as possible. That is why I have considered - and tried - pyjamas 
(which has been working very well for me: very easy to use, and up to now 
very robust). I have some worries:

   1. This approach means I must keep coding, and integrating, two 
   technologies: web2py and pyjamas. It is still way better than having to 
   code in javascript.
   2. One thing that worries me about implementing all this logic 
   client-side is that a big chunk of my code will be autogenerated 
   javascript. That means, if I run into trouble, I guess it will be very 
   difficult to solve any problems I may have.
   3. And this a side issue, but I need to mention it nevertheless: I am 
   having a hard time integrating the CSS from pyjamas and web2py. Since some 
   styles from web2py (table, td, ...) override my styles, suddenly all my 
   pyjamas components are looking very bad. This is a very painful problem, 
   which I do not know how to solve. Do you have any suggestions on how to 
   debug CSS issues? I am limited to Chrome inspector basically.

So what I was aiming at now is to use as little client side logic as 
possible: just perform some AJAX calls to get the data ready for 
presentation. Actually, I was even planning to do (for example) HTML table 
rendering on the server (I am considering 
markup.py for 
that) and send it via AJAX to the client to be displayed. Basically, the 
server would be in charge of updating the html in the client. The same that 
web2py does with controllers/views/functions, but for dynamic content, 
which must be sent via AJAX.

I have not yet decided which approach to take. If you have experience in 
this scenario, your comments are welcome!

Thanks,
Daniel

-- 





[web2py] Re: How capable is the ajax function in web2py.js?

2012-06-26 Thread stefaan

>
>
> Now I realize that in order to interact with the table, which is managed 
> by pyjamas, for example to select a certain row, I need to define a complex 
> JSONRPCs interface (select row, un-select, paginate to next page, previous 
> page, last page, page number, ...), passing back and forth parameters and 
> results between web2py and pyjamas. This looks quite complex.
>
>
One thing that can reduce playing ping-pong with the server (and therefore 
also reduce complexity + enhance performance): 
think about when you really need to contact the server, and accumulate 
other changes in the client until you actually contact it.

In an application I'm currently prototyping, I allow a user to do lots of 
manipulations on a table (selecting rows, filtering visible data, sorting 
columns, ...) purely in the client.
When the user selects a row, I dynamically change its css style so it looks 
differently on screen. No need to contact the server for that. 
Inside the client (pyjamas) I maintain a data structure in response to the 
user interactions that encodes updates to the current state of the 
application 
(think: a list of currently selected rows).

Only when absolutely needed, the new state of the application is sent back 
to the server (i.e. to web2py using JSONRPC) and processed, or new data is 
requested from the server.

As explained by Anthony ("most of the effort will be on the client side"), 
I think using Ajax/JQuery directly won't make things fundamentally easier 
(on the contrary: unless you find a pre-made component that already does 
what you want you will now have to write your client side stuff in 
javascript instead of python, which - depending on your background - may 
sound scary).

-- 





[web2py] Re: why is form self submit getting executed on cancel? [Closed]

2012-06-26 Thread weheh

>
>
>>>

-- 





[web2py] Re: why is form self submit getting executed on cancel?

2012-06-26 Thread weheh
@Cliff, thanks for the suggestion but it doesn't work because the onclick 
event can not be associated with the insert method. Likewise, for the 
reason stated by Anthony, it is the return false that is needed to prevent 
the update action from executing.
@Anthony, thanks, as usual, for your suggestions and illuminating 
responses. As expected, your suggestion works.

On Monday, June 25, 2012 8:35:49 PM UTC+8, Anthony wrote:
>
> The onclick event doesn't cancel the standard submit behavior -- it just 
> adds the onclick behavior before submitting. If you want to prevent the 
> submit action, do:
>
> _onclick='ajax("%s",[],":eval");return false'
>
> "return false" prevents the submit. An alternative to using onclick is to 
> register a jQuery event handler and call preventDefault() at the end of the 
> handler. That is sometimes preferable because although it prevents the 
> submit, it does not  stop the propagation of the event itself, in case 
> there are other handlers set up to catch the same event ("return false" 
> will prevent any other event handlers from being triggered).
>
> Anthony
>
> On Monday, June 25, 2012 6:13:31 AM UTC-4, weheh wrote:
>>
>> My controller has a componentized form with an added Cancel button 
>> like this (this is an excerpt, so sorry for any typos):
>>
>> def update( ):
>>
>>   myform = SQLFORM.factory(
>> Field('text_in','text',requires=IS_NOT_EMPTY()),
>> buttons=[INPUT(_type='submit',_value=T('Update'))],
>> _id='myform',
>> formstyle='divs'
>> )
>>   form.element('input[type=submit]').parent.append(
>> TAG.BUTTON(T('Cancel')),_onclick='ajax("%s",[],":eval");' % URL(
>> c='my_controller', f='cancel_update')
>> )
>>   if myform.process(formanem='myform').accepted:
>> ...do stuff...
>>  return dict(myform=myform)
>>
>>
>>
>> The form submits 
>> properly when the Update button is pressed. However, when the Cancel 
>> button is pressed, not only does 
>> the "cancel_update" callback get called, the form also gets submitted 
>> erroneously. The question is, why does the "update" action get called and 
>> its form get submitted at all when the Cancel button is pressed?
>>
>>

-- 





[web2py] Re: Best practice using scheduler as a task queue?

2012-06-26 Thread Niphlod
well, after all the time you spent after it, it's quite a bold statement.
Current scheduler (in trunk there has been a problem, attached the correct 
one) reassign "RUNNING" tasks if a worker is killed in action, but you may 
want to check if in scheduler_worker table you have entries for dead 
workers too (there should be only active schedulers on it).

PS: bugs get eventually solved, if you can point to some of them :D
PS 2 : I use scheduler in production both for "one-time-only" tasks and for 
recurring ones, and never incurred in such problems.

-- 



#!/usr/bin/env python
# -*- coding: utf-8 -*-

USAGE = """
## Example

For any existing app

Create File: app/models/scheduler.py ==
from gluon.scheduler import Scheduler

def demo1(*args,**vars):
print 'you passed args=%s and vars=%s' % (args, vars)
return 'done!'

def demo2():
1/0

scheduler = Scheduler(db,dict(demo1=demo1,demo2=demo2))
## run worker nodes with:

   cd web2py
   python web2py.py -K myapp
or
   python gluon/scheduler.py -u sqlite://storage.sqlite \
 -f applications/myapp/databases/ \
 -t mytasks.py
(-h for info)
python scheduler.py -h

## schedule jobs using
http://127.0.0.1:8000/scheduler/appadmin/insert/db/scheduler_task

## monitor scheduled jobs
http://127.0.0.1:8000/scheduler/appadmin/select/db?query=db.scheduler_task.id>0

## view completed jobs
http://127.0.0.1:8000/scheduler/appadmin/select/db?query=db.scheduler_run.id>0

## view workers
http://127.0.0.1:8000/scheduler/appadmin/select/db?query=db.scheduler_worker.id>0

## To install the scheduler as a permanent daemon on Linux (w/ Upstart), put the
## following into /etc/init/web2py-scheduler.conf:
## (This assumes your web2py instance is installed in 's home directory,
## running as , with app , on network interface eth0.)

description "web2py task scheduler"
start on (local-filesystems and net-device-up IFACE=eth0)
stop on shutdown
respawn limit 8 60 # Give up if restart occurs 8 times in 60 seconds.
exec sudo -u  python /home//web2py/web2py.py -K 
respawn

## You can then start/stop/restart/check status of the daemon with:
sudo start web2py-scheduler
sudo stop web2py-scheduler
sudo restart web2py-scheduler
sudo status web2py-scheduler
"""

import os
import time
import multiprocessing
import sys
import cStringIO
import threading
import traceback
import signal
import socket
import datetime
import logging
import optparse

if 'WEB2PY_PATH' in os.environ:
sys.path.append(os.environ['WEB2PY_PATH'])
else:
os.environ['WEB2PY_PATH'] = os.getcwd()

if not os.environ['WEB2PY_PATH'] in sys.path:
sys.path.append(os.environ['WEB2PY_PATH'])

try:
from gluon.contrib.simplejson import loads, dumps
except:
from simplejson import loads, dumps


from gluon import DAL, Field, IS_NOT_EMPTY, IS_IN_SET
from gluon.utils import web2py_uuid

QUEUED = 'QUEUED'
ASSIGNED = 'ASSIGNED'
RUNNING = 'RUNNING'
COMPLETED = 'COMPLETED'
FAILED = 'FAILED'
TIMEOUT = 'TIMEOUT'
STOPPED = 'STOPPED'
ACTIVE = 'ACTIVE'
INACTIVE = 'INACTIVE'
DISABLED = 'DISABLED'
EXPIRED = 'EXPIRED'
SECONDS = 1
HEARTBEAT = 3*SECONDS
MAXHIBERNATION = 10

class Task(object):
def __init__(self,app,function,timeout,args='[]',vars='{}',**kwargs):
logging.debug(' new task allocated: %s.%s' % (app,function))
self.app = app
self.function = function
self.timeout = timeout
self.args = args # json
self.vars = vars # json
self.__dict__.update(kwargs)
def __str__(self):
return '' % self.function

class TaskReport(object):
def __init__(self,status,result=None,output=None,tb=None):
logging.debug('new task report: %s' % status)
if tb:
logging.debug('   traceback: %s' % tb)
else:
logging.debug('   result: %s' % result)
self.status = status
self.result = result
self.output = output
self.tb = tb
def __str__(self):
return '' % self.status

def demo_function(*argv,**kwargs):
""" test function """
for i in range(argv[0]):
print 'click',i
time.sleep(1)
return 'done'

#the two functions below deal with simplejson decoding as unicode, esp for the dict decode
#and subsequent usage as function Keyword arguments unicode variable names won't work!
#borrowed from http://stackoverflow.com/questions/956867/how-to-get-string-objects-instead-unicode-ones-from-json-in-python
def _decode_list(lst):
newlist = []
for i in lst:
if isinstance(i, unicode):
i = i.encode('utf-8')
elif isinstance(i, list):
i = _decode_list(i)
newlist.append(i)
return newlist

def _decode_dict(dct):
newdict = {}
for k, v in dct.iteritems():
if isinstance(k, unicode):
k = k.encode('utf-8')
if isinstance(v, unicode):
 v = v.encode('utf-8')
elif isinstance(v, list):
v = _decode_list(v)