Re: [Zope3-Users] Re: Invariants and forms

2007-08-14 Thread Maciej Wisniowski

> The standard error message is:
> There were errors
>   
'There were errors' is default 'status message' when there are some errors.
Do you have any custom template in use?

Please, take a look at:

zope/formlib/form.py
around line 717 there is 'update' function that is interesting for you:

def update(self):
self.setUpWidgets()
self.form_reset = False

data = {}
errors, action = handleSubmit(self.actions, data, self.validate)
self.errors = errors

if errors:
self.status = _('There were errors')
result = action.failure(data, errors)
elif errors is not None:
self.form_reset = True
result = action.success(data)
else:
result = None

self.form_result = result


As you can see there is a call to 'handleSubmit' which in turn calls
validation function, that calls function to check invariants.
As a result in 'errors' list you should have your error message
from invariants. Seems for me that this message is there
because self.status is set to 'There were errors' (so 'errors'
list is not empty).
'errors' list is used by ZPT: pageform.pt to display errors by default.
That's why I asked if you have custom template...

If above doesn't help then... do you know 'pdb'?
I think you should use pdb to debug code and see what happens.
Just put line:

import pdb;pdb.set_trace()

into above 'update' method from 'form.py' after a call to handleSubmit
and check what is in errors list.

Read about pdb here:
http://plone.org/documentation/how-to/using-pdb

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Invariants and forms

2007-08-13 Thread Maciej Wisniowski
> I've found two different examples(see below), but both don't display my given 
> exception message. The only thing i get is the standard error message.
What do you mean by standard error message?


> Second example
> (taken from:
> http://blog.gocept.com/zope3-testen-von-felderuebergreifenden-bedingungen-invariants-in-interfaces-mit-zope-formlib-aktualisiert)
> 
> import zope.interface
> 
> class IUser(zope.interface.Interface):
> password = zope.schema.Password(title=u"Passwort")
> password2 = zope.schema.Password(title=u"Wiederholung des Passworts")
> 
> @zope.interface.invariant
> def arePasswordsEqual(user):
> if user.password != user.password2:
> raise zope.interface.Invalid(
> u"""Das Passwort und die Wiederholung sind nicht gleich.""")

I think this should work.
Take a look at formlib/form.txt  - section about Invariants. If
it doesn't then I think your error is from somewhere else (again - what
is standard error message for you?)

There is also another possibility to do some checks between distinct
fields. To do this, in your action handler you may do your check
using values from 'data' dictionary, and if there is error you should
set:

self.form_reset = True
self.errors.append(u'your error message')


If you want to use this kind of validation (at action handler) to set
error messages for specific field you may do this either. I've added
function to my Form class for this:


from zope.app.form.interfaces import WidgetInputError
(...)
def setWidgetError(self, name, v):
""" Helper function for validation purposes.
Sets error for widget
 @name - field name
 @v - error message
"""
w = self.widgets.get(name)
if w:
w._error = WidgetInputError(
  self.context.__name__, w.label, v)
return w._error


In this case, if you validate your values in action handler you may do:


self.setWidgetError('password_confirmation',
u'Confirmation doesn\'t match')
self.form_reset = True


and error message will be bound to 'password_confirmation' field.


-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] ForbiddenAttribute error

2007-07-06 Thread Maciej Wisniowski
> I get a
> ForbiddenAttribute error when viewing the class
AFAIR ForbiddenAttribute means that you have no
permissions for attribute you want to access.
No permissions means that it is neither allowed
nor denied :)

You're using feed.entries:

> result+=[(e.updated_parsed, feed.channel, e) for e in
> feed.entries ]


Seems that 'entries' are the cause of error (as Dennis already said)
or something in this line.

If 'feed' above is of type Feed then your's IFeed doesn't
specify 'entries' attribute in it. This means no permissions
are set to 'entries' and this may cause ForbiddenAttribute
error.

You may use pdb to simply debug what exactly causes the error.

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] z3c.form and subforms in an AddForm?

2007-07-05 Thread Maciej Wisniowski

> On Tuesday 03 July 2007 05:38, Maciej Wisniowski wrote:
>   
>> TraversalError: (, 'widget')
>> 
>
> People that got this error had either old versions of the code (run buildout 
> without -N) and/or had a PYTHONPATH set. Please make sure you have no entry 
> in PYTHONPATH.
My PYTHONPATH is empty. I've not used buildout. I have
my old zope 3.3.1 installed and I've downloaded
packages from http://download.zope.org/distribution/
I have:
z3c.form
z3c.formui
z3c.macro
z3c.pagelet
z3c.template
z3c.viewlet
z3c.zrtresource

I've extracted these packages into my instance's /lib/python folder.
I've also put z3c.formdemo into my instance.
 
My code still fails when submiting empty value for required field.
Formdemo fails as well.

I found in another post that you've changed something in i18n
so I have tried to get new zope.i18n package but with no effect.
What else should I have?

-- 
Maciej Wisniowski

___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] z3c.form and subforms in an AddForm?

2007-07-03 Thread Maciej Wisniowski

> On Friday 22 June 2007 14:36, Mats Nordgren wrote:
>   
>> I'm still having the ErrorViewSnippet problem.  I've gone over and over the
>> message example in formdemo and can't see anything different in my setup
>> from the demo.  The demo works fine but mine throws the ErrorViewSnippet
>> error when I submit an AddForm with missing input.  EditForm works correct
>> though.
>> 
>
> This is really strange and makes no sense. It seems that the error view 
> snippet has no widget attribute. But this is impossible, since it is always 
> assigned in the constructor.
>
> Could you send me some working code, like the package you are working on?
>   

Did you find cause of this problem? I get same error and
still can't realize what is wrong.


End of my error traceback is:

  File "/opt/Zope/Zope-3.3.1/lib/python/zope/tales/tales.py", line 696,
in evaluate
return expression(self)
   - /opt/Zope/instancje/z331/lib/python/z3c/formui/div-form.pt
   - Line 38, Column 12
   - Expression: 
   - Names:
  {'args': (),
   'context': ,
   'default': ,
   'loop': {},
   'nothing': None,
   'options': {},
   'repeat': {},
   'request': http://localhost:8080/++skin++MyTest/@@addMyTest.html>,
   'template':
,
   'usage': ,
   'view': ,
   'views': }
  File "/opt/Zope/Zope-3.3.1/lib/python/zope/tales/expressions.py", line
217, in __call__
return self._eval(econtext)
  File "/opt/Zope/Zope-3.3.1/lib/python/zope/tales/expressions.py", line
194, in _eval
ob = self._subexprs[-1](econtext)
  File "/opt/Zope/Zope-3.3.1/lib/python/zope/tales/expressions.py", line
124, in _eval
ob = self._traverser(ob, element, econtext)
  File
"/opt/Zope/Zope-3.3.1/lib/python/zope/app/pagetemplate/engine.py", line
68, in __call__
request=request)
  File "/opt/Zope/Zope-3.3.1/lib/python/zope/traversing/adapters.py",
line 164, in traversePathElement
return traversable.traverse(nm, further_path)
   - __traceback_info__: (, 'widget')
  File "/opt/Zope/Zope-3.3.1/lib/python/zope/traversing/adapters.py",
line 52, in traverse
raise TraversalError(subject, name)
   - __traceback_info__: (,
'widget', ['label'])
TraversalError: (, 'widget')

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] z3c.form 1.3.0, z3c.formui 1.0.1, and z3c.formdemo 1.1.0 released!

2007-06-28 Thread Maciej Wisniowski

> Again for the curious and impatient ...
> ---
>
> We have added two more demos:
>
> * An "Address Book" implements a non-trivial example of an address book,
>   including multiple addresses and E-mails. It demonstrates the use of
>   sub-forms, writing custom widgets and composite content.
>   
This demo is really impressive!

> * An "SQL Message" demo reimplemnets the simple "Hello World!" demo only using
>   queries to the Gadfly database. The example adds to the original demo by 
>   also providing a message overview screen, since the ZMI is not helpful for 
>   pure SQL data.
>   
Thanks for this one :)

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Re: [Zope] z3c.form 1.3.0, z3c.formui

2007-06-28 Thread Maciej Wisniowski

> In my case, I use archgenxml very often which now requires a Zope 3.3
> installation or a Zope 2.10 one, so I have this set in my bashrc.
> Also, when trying to access Zope 3 libraries from python console,
> since I am still in Zope 3.3, there are no eggs available for that
> installation so I need to set my PYTHONPATH to test things.
> IOW, specific things. So I believe it is common to have this unset.
There is 'workingenv' tool that allows you to have distinct
environments.

Maybe I'm missing something
obvious... but how should I install z3c.form if I want
to use this with my existing zope instance.

I mean I have zope 3.3.1, downloaded from zope.org
in tar.gz file and installed in my system.
If I execute easy_install z3c.form then i get a lot of
eggs that I don't want because I already have my zope
and new eggs seems to be from zope 3.4 alpha
version, eg.:
(...)
zope.app.i18n-3.4.0a1-py2.4.egg
zope.app.http-3.4.0a1
(...)

Should I manually download just necessary eggs?
What is preffered way to do it?

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-dev] Re: [Zope3-Users] z3c.form 1.0.0 released!

2007-05-31 Thread Maciej Wisniowski

> I also still struggle with this issue. In my case, I have the following 
> scenarios:
>
> I currently try to solve these issues with a self-made Form class, which 
> descends from form.Form. In case you are interested, here is my docstring 
> which somehow explains the basic idea:
>   
Thanks for the code. I'm using old (?) way with SQLScripts not
with ORM's so may case is a bit different. I've also created my
own library that extends formlib: 'dbformlib' (available at google code)
for such things.

I'm not sure why do you have to clone fields, possibly because of
ORM specifics?

Idea of widget_template_files is very interesting.

I need to see docs and code for z3c.form now :)

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-dev] Re: [Zope3-Users] z3c.form 1.0.0 released!

2007-05-30 Thread Maciej Wisniowski

>> It would be very interesting to see RDBMS interaction. Formlib for
>> example is not trivial to use with RDBMS especially because of a lack
>> of documentation and because everything seems to be written with ZODB
>> objects in mind.
>> 
>
> It works together with a mapper like SQLAlchemy (and z3c.zalchemy).
>
> IMHO, it is not formlib's task to do mappings like that.
>   
Not sure what mappings you're talking about. I just want to
know how can I get some data from somewhere (it may be a
file, RDBMS or other external source) and display it in a form,
then edit this data etc. Formlib default forms (EditForm, AddForm)
assume that it works with content objects and I just want to call
SQLScript to get data for my form and to commit it back to RDBMS.
Not so difficult but there are no docs and no demos for this with
formlib. Thats why  I'd like to know how to do such things
with z3c.form.

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] z3c.form 1.0.0 released!

2007-05-30 Thread Maciej Wisniowski

> Thanks. BTW, I am still looking for 1-2 demos to write but I am out of ideas. 
> Do have anything related to forms that you would like to see demoed?
It would be very interesting to see RDBMS interaction. Formlib for
example is not trivial to use with RDBMS especially because of a lack
of documentation and because everything seems to be written with ZODB
objects in mind.

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Blog naming proposals

2007-05-28 Thread Maciej Wisniowski

> "Bitacora", spanish for log. Since all names with "blog" in it seem already
> taken.
Bitacora sounds good to me but I'm not sure if I can remember this
easily although I still like it.

I would propose simple: 'ZOG' which may be considered 'Zope blOG' or
'ZOpe bloG'.

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Re: Remote authentication

2007-05-13 Thread Maciej Wisniowski
> Hi Maciej. Thank you for your reply and outlining the authentication
> process. This does make things clearer. There are a variety of backends,
> I read that something as simple as reading fom a file is possible. 
> ldappas and dl.ldapauth provide some good hints for plugins and user
> management from infrae's documentlibrary. I became aware of these
> packages working on documentlibrary recently.
I don't know documentlibrary but with cas you'll get only the user
name and with this it is necessary to
get user roles/permissions from specific backend.


> I want to be clear that https enters into the picture as soon as
> authentication is required or someone were to click on a login link. I
> am seeing links such as this in the docs I have been reading:
> 
> https://secure.its.yale.edu/cas/login?service=http://my/url
> 
> Reading the plone code, I noticed a replacement for login portlet (to
> replace it with a link to CAS server) so I am assuming at this point
> folks would be coming to portal unauthenticated and no https until you
> were to login or attempt to gain access to an area where you need
> authorization (then you are redirected - and now https on CAS server)
> Have I got this right?
CAS authentication will work with http, but single sing on will not.
I mean if you have CAS server like:

https://secure.its.yale.edu/cas

and applications:
http://my/url
http://my/url2

then you'll have to login while trying to acces http://my/url2
even thought you already are logged in to http://my/url. With
https you'll be automatically logged into url2 via SSO.

There were discussions about turning off https on CAS users
list but I don't know if it is possible in recent CAS versions.

Also you may send 'service url' as https one. This way users
accesses http site but after successfull login at CAS user is
redirected to https one.


> I thought sessions should be used but maybe there are some other
> opinions. I realize there were some issues with sessions some years back
> with z2. I have not heard anything negative about sessions in z3.
Hm... I'm not sure about session implementation in zope3 but
I had some issues with sessions with zope 2 (conflicts).
I think that accessing session with every request is not too good as
this causes session buckets to be moved in oobtree because of
expiration, starts garbage collections etc. But I'm not sure how
this exactly goes.


> I was also thinking to some extent about the url redirection etc for
> this CAS activity and it made me wonder whether some of this should not
> be occurring as part of a WSGI middleware (but this is just a random
> thought at the moment).
I have no experience with that but like to get to know more :)

> I am interested in setting up a project for this shortly. I'll likely
> get this going in the next day or so and will be grateful for your help
> since you have experience with this. I'll provide details for the
> project as soon as I have them but will likely put it in zif collective
> on sourceforge in svn.
OK, but possibly I will have no internet access for few days so I may
answer with delays.


> BTW, I recently noticed that the authentication server need not be java
> so long as it complies with the CAS protocol. In fact I was reading code
> for rubyCAS server earlier today. It makes me wonder why the
> authentication server itself could not be written in python and served
> using zope or twisted. Gives me something to think about for later if
> things work. Many thanks,
Would be great to have this server in python :)

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Re: Remote authentication

2007-05-12 Thread Maciej Wisniowski

> Hi Maciej. I have been reading quite a bit about CAS today. It looks
> like a good way to go. Couple of questions with how you having it
> working in z2. Are you using LDAP as a user store with CAS. 
We're not using LDAP. We have propertiary system to manage user
accounts in our applications (user data and permissions in
specific applications). This system uses RDBMS to store its data so
for CAS it is just external database with user names and passwords.
Our CAS server authenticates users against this database with just one
simple select statement I think.


> I have downloaded a few of the z2 products to study the code
> in the interim since a plugin for z3 would be a good thing. I've got to
> look at how this works with users and groups code particular with
> additional info you need for an app.
In fact i think that default plugin for CAS can't do more than just
authentication.
So first step should be to rewrite CAS4PAS to zope3 PAU which should be
rather easy. Only thing I'm not sure obout is if this should use session
or maybe cookies? Sessions are nasty in Zope...

Another thing is a second plugin for user management. But this depends
on where
your user database is. This plugin may enumerate users, set roles for users
etc. Depending on specific solution this plugin may connect to LDAP
or RDBMS to get user data, roles and permissions from and map them to
Zope ones.
In our system we have a special permission in database that is mapped into
user role in Zope. In fact our plugin has parameter that says what is
the name
for this role so it is easy to customize that via ZMI.

Not sure if you already realised how CAS works (I had some problems to
realise that at the begining) so a quick description is at the bottom of my
post. Important thing to note is that all addresses have to be https ones.

> Anybody out there interested in helping with something like this? I'm
> likely to start a project for this for z3 package but with zpl or mit
> licensing since something this generic should have few barriers to
> anyone using Yale's system. Many thanks.
>
I'm interested in helping you with that.



Order of actions in CAS authentication

1. User tries to enter into Zope application via url like https://xyz/myapp

2. CAS4PAS checks if there is a special object in session
that says user is already authenticated

3. If there is no object in session CAS4PAS checks if there is a 'ticket'
parameter in request

4. If there is neither special object in session nor 'ticket' in request
CAS4PAS
redirects user to CAS login page with 'service' parameter in redirect URL
which is address of zope application itself (CAS4PAS has to know address
of CAS login page)
https://casserver/login?service=https://xyz/myapp

5. User authenticates at CAS login page

6. CAS checks credenitals in RDBMS (LDAP etc)

7. If everything is OK CAS sets secure cookie in browser that indicates
user is authenticated

8. CAS redirects user to 'service' URL with additional 'ticket' parameter
https://xyz/myapp?ticket=PT-838288428348284

9. Zope (which is under 'service' URL) checks again if there is a special
object in session, and if not, checks if there is a 'ticket' parameter
in request.

10. CAS4PAS in Zope gets data form the 'ticket' in request and goes to
'service url' (with
'ticket' and 'service' parameters) at CAS server to confirm authentication
 (CAS4PAS has to know 'service url'):
https://casserver/serviceValidate?ticket=PT-8838828388...&service=https://xyz/myapp

11. CAS confirms user authentication and responds with name of
authenticated user.
12. CAS4PAS sets special object in session to indicate user authentication.

Now another application (in short)
13. User tries to enter to another application that is protected by CAS.
14. Application redirects to CAS login page.
15. CAS finds that there already is secure cookie set so this user is
authenticated!
16. CAS redirects user back to application with 'ticket' parameter in
URL... etc.


-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Re: Remote authentication

2007-05-11 Thread Maciej Wisniowski
Hi!

For single sign on there is also CAS (Central Authentication Service).
We're sucessfully using this in our Zope2 apps. It has plugin for PAS
in Zope2 (CAS4PAS). CAS also works with other systems - plugins for
java, php and other exists.

Important thing here is to distinguish between authentication and
authorization. For example SSO like CAS can only tell you if your
user is authenticated. It won't tell you if he has some permissions
and/or roles to do something. But with PAS you can write another plugin
that will set proper roles for user etc.


-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Arranging widgets in a form / Limit size of input fields

2007-05-03 Thread Maciej Wisniowski

> In my case, I have several forms with e.g. 10-15 fields, so this adds up and 
> in the end the templates are quite complex. If there were some shortcut or 
> macro which generates the above HTML-code, it would be a lot easier, perhaps 
> there's a decent solution? If it would looke something like this, it would be 
> much easier to manage:
>
> 
  

Label
  
  Error
  
  
  


If you need specific widgets order then you may use:

form.FormFields(interfaces.ISomeInterface).select('field1', 'field2',)


Another possibility io define function in your view class like:

widgetTempl = ViewPageTemplateFile('widgetsection.pt')
def genWidgetHtml(self, widget):
 return self.widgetTempl(widget=widget)

and create file widgetsection.pt with content like:


  

Label
  
  Error
  
  
  



Then in your pageform.pt just call for every widget something like:




Above code is from head so may be buggy or incomplete.

-- 
Maciej Wisniowski

___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Arranging widgets in a form / Limit size of input fields

2007-05-03 Thread Maciej Wisniowski

>> One way would be to create a custom template file, where each widget is 
>> placed 
>> via HTML. However, this is quite some work. 
>> 
>
> I've often done this and it doesn't seem like too much work. But I don't
> dispute your evaluation.
>   
I've used my own templates as well. It is more work than having
autogenerated form but it is not so hard. In fact you may change
template to use divs instead of tables and then play with css
only to arrange your forms.
> My approach is different to Fred's because I rarely call setUpWidgets in
> my form code. I have a bunch of custom widgets in a known place and use
> custom_widget. Some widgets are for special fields or needs and some are
> as simple as this one. I reuse it very often.:
>
> class DescriptionWidget(TextAreaWidget):
> def __init__(self, context, request):
> super(TextAreaWidget, self).__init__(context, request)
> self.height = 3
> self.width = 85
I've used this kind of solution as well.
AFAIK for textarea html fields you can't set something like
maxlength. You have to use javascript for that.

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Problem with @@absolute_url

2007-04-30 Thread Maciej Wisniowski
> class StudentDetails:
> """Helper to return a student photo."""
> def getPhoto(self):
> student = self.context
> return StudentPhoto(student)
> 
> In my page template, I can see that the IImage object is being created 
> correctly..
> 
> 
> #
> 
> 
> gives me .  But to turn this 
> object into a URL so that I can put it in an  tag is beyond me.  When I 
> try to do an @@absolute_url on the photo object I get the error saying 
> there's not enough context.
> 
> Am I going about this the wrong way?  Is there some other thing I need to be 
> doing in order for there to be enough context?
Hm... not sure if it is good solution but it is just a quick though so
possibly somebody may give you something better. Maybe there are ready
solutions for this. In general if you want
to return image then you have to return it's data to the browser (not
Image object) and you also have to set proper headers like content-type
and content-length. I don't remember exactly how it should go but you
should find examples with google or see how z3c.image does this etc.
This should be something like:


class StudentDetails:
 """Helper to return a student photo."""
 def __call__(self):
 student = self.context
 self.request.setHeader('content-type', 'image/png')
 # determine and set content-length here
 return StudentPhoto(student).data # not sure if it was 'data'
   # check image.py

If you declare this in zcml as:

http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Field validation errors in formlib action handlers

2007-04-29 Thread Maciej Wisniowski
> I've done interface constraints before and raised ValidationErrors.
> However, in this case that won't work because the error can only occur
> during the action handler (and without access to the request, which
> carries a particular foreign key, I can't look in the database to
> predict whether it would fail).
> 
> Is there some way of doing this?
Unfortunatelly formlib seems to be concerned mainly on ZODB.
But it is possible to do validation on success handler level.
Darryl Cousins already asked about this on zope3-users and
I suggested to use something like:

Function defined in view class eg. descendant of EditForm:

 from zope.app.form.interfaces import WidgetInputError

 def setWidgetError(self, name, v):
 """ Helper function for validation purposes.
 Sets error for widget
  @name - field name
  @v - error message
 """
 w = self.widgets.get(name)
 if w:
 w._error = WidgetInputError(
   self.context.__name__, w.label, v)
 return w._error

In function used as success handler I did:

 if not data['myfield']:   # some errors from rdbms with myfield etc.
 error = self.setWidgetError('myfield',
 'value can\'t be above a number N')

 # it is necessary to manually handle form reset here
 self.errors.append(error)
 self.form_reset = False


AFAIK it may be also necessary to set self.status to have error messages
visible.

There is also another thing you may do.
If you take a look at 'update' method of FormBase in form.py
then you can see that success handler method is not even supposed to
return any errors but it is easy to change this behaviour. For example
I changed my 'update' method to this:

if errors:
self.status = _('There were errors')
result = action.failure(data, errors)
elif errors is not None:
result = action.success(data)
if not self.errors:
self.form_reset = True
else:
self.status = _('There were errors')
result = action.failure(data, errors)
else:
result = None

this way you only have to set self.errors in your success handler
function. status and form_reset are handled 'automatically'

-- 
Maciej Wisniowski

___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] vary formlib render_submit_button by skin

2007-04-19 Thread Maciej Wisniowski

>  
> I think I have similar problem with action renderer: I would like to
> attach a javascript handler for my action button.
> Unfortunately the renderer seems to not allow to pass any additional
> attributes for the html button (like onclick attribute).
For this case (and a lot of others) behaviour.js may be very helpful.
Action buttons (after they're rendered) possibly have id's so it is
easy to just attach some javascript to them.
You don't have to modify anything in rendering code, zpt template etc.
Just write some JS code and attach it to the html element like you do with
css classes.

Behaviour.js page is: http://bennolan.com/behaviour/

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] execution time of a request?

2007-04-06 Thread Maciej Wisniowski
> does anyone know a method to get or compute the execution time of a
> request?
Lori - plugin for firefox, or firebug etc?
Or do you want to display this on page?

-- 
Maciej Wisniowski

___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Re: lovely.remotetask question

2007-04-04 Thread Maciej Wisniowski

> Or use zopectl start/stop.
>
Right, this works. Problem is when using

zopectl fg

I can't stop zope via ZMI or ctrl+c without
stopping RemoteTask first or killing zope process.

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Re: lovely.remotetask question

2007-04-03 Thread Maciej Wisniowski

> For startup do this :
>
> @component.adapter(IDatabaseOpenedEvent)
> def startRemoteTask(event):
> """Start the amazon remotetask on startup."""
> db = event.database
> connection = db.open()
> root = connection.root()
> root_folder = root.get(ZopePublication.root_name, None)
> for site in root_folder.values():
> service = component.queryUtility(
> ITaskService, context=site)
> if service is not None:
> if not service.isProcessing():
> service.startProcessing()
>
> I assume here that the remote tasks are located in one of the site
> directly contained in root.
Works for me now :)
>
>
> For shutdown :
>
> I have no solution for this right now.
So seems that now it is best to manually click on stop processing button
via
ZMI before shutting Zope down.

Thanks!

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


[Zope3-Users] lovely.remotetask question

2007-04-03 Thread Maciej Wisniowski
Hi

I want to use lovely.remotetask in Z3 application.
Use case is very simple:
User views page, this causes long running function to be started
and Ajax calls from the page check every second if there is a result.

I have:
1. content object (Folderish) with instance of remotetask.TaskService()
called 'monitor_service' inside

2. mytask = remotetask.task.SimpleTask(myLongRunningFunction)

3. named utility for 'mytask'

The question is how should I start and stop remotetask jobs?
Currently, when user enters a page I call (every time):

jobid = self['monitor_service'].add(u'mytask', appdict)
self['monitor_service'].startProcessing()

Then ajax is repeadetly checking for result and when
status is Completed I call

self['monitor_service'].stopProcessing()

It works nice, but after looking into service.py code I see
it will break when I'll have few concurrent users.

Seems that I should call startProcessing() on zope startup
and stopProcessing on zope shutdown?

How should I use that (in my use case)?
Without call to stopProcessing I'm unable to stop Zope.

-- 
Maciej Wisniowski

___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Guidance on accessing MySQL db.

2007-03-31 Thread Maciej Wisniowski
> I've read examples from Zope 2 where they used a DTML
> page that called a ZSQL method such as the following:
> 
> 
> 
> 
> 
> 
> ZSQL method would then contain:
> SELECT river_id, river_name FROM river_info
> 
> In Zope 3, I only see an option to add a SQL script
> which I'm pretty sure is not the same thing as a ZSQL
It is the same thing, at last in the way it works.

> method since I've copied the above into a SQL script
> and "Test"ing the script by itself does in fact read
> from the MySQL database, but I can not access the SQL
> script from a DTML page.  I get the following error:
> 
> "KeyError
> A server error occurred."
Take look at site error log or at log/transcript.log
to see full traceback.

Simplest thing you should do is to

1. Create database
connection object. For MySQL you should use:
http://www.zope.org/Products/Zope3-Packages/mysqldbda/view

Create this object TTW, enter proper connection string and
check if it works with Test tab. Then click at Registration
tab and register connection object under specific name.

2. Create SQLScript object
At the add form you should see Connection field and you should be
able to chose connection you've created at point 1 (that is why
your connection had to be registered).

3. Enter SQL statements into SQLScript object, save and test it
4. create view to display data from SQLScript

Read about relational database connectivity in Zope2 book.
A lot of thing is valid with zope3 too.

> So, some very basic questions :
> What is the suggested way to access a MySQL database
> from Zope 3.  
In fact you may use traditional way (as above) or use
ORMs like SQLObject or SQLAlchemy. Not sure what is
preffered. For me this is up to personal preferences.

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Re: Formlib - handleSubmit, custom validator on action

2007-03-29 Thread Maciej Wisniowski

> So I am always getting an empty dictionary back to my action method.
>
> Sorry for the noise. In the meantime I've just gone back to creating an
> interface with and @interface.invariant which is working for me. I was
> just keen to find out if validator could be used.
>   
I used validation directly in action function especially because
I had some rdbms operations here. I've written a bit about this
recently. Search for
'Formlib and custom validation constraints' thread. It is something like:

Function defined in my view class eg. descendant of EditForm

from zope.app.form.interfaces import WidgetInputError

def setWidgetError(self, name, v):
""" Helper function for validation purposes.
Sets error for widget
 @name - field name
 @v - error message
"""
w = self.widgets.get(name)
if w:
w._error = WidgetInputError(
  self.context.__name__, w.label, v)
return w._error

In function used as success handler I did:

if not data['myfield']:
error = self.setWidgetError('myfield', 'Required field is empty')
self.errors.append(error)
self.form_reset = False


-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Formlib and custom validation constraints

2007-03-19 Thread Maciej Wisniowski
> So my question is simple : how do I have to handle such custom
> constraints, which are applied to only one field and which I don't want
> to define via invariants (because I'd like the error message to be
> displayed correctly next to the required widget) ?
> Until now I've tried a few methods (via "widget._error" property for
> example) not nothing gave me correct results...
1. You may use __call__ method of your form (view) to create field
as required or not required depending on parameters. Creating individual
fields is described in formlib.txt

2. widget._error
In validation function or in action handler function you may set
widget._error for field. I've created function for this like:


from zope.app.form.interfaces import WidgetInputError

def setWidgetError(self, name, v):
""" Helper function for validation purposes.
Sets error for widget
 @name - field name
 @v - error message
"""
w = self.widgets.get(name)
if w:
w._error = WidgetInputError(
  self.context.__name__, w.label, v)
return w._error

You may use this function in success handler method like:

if not data['myfield']:
error = self.setWidgetError('myfield', 'Required field is empty')
self.errors.append(error)
self.form_reset = False



To avoid setting form_reset etc. I am using slightly modified
implementation of formlib's update function (but you don't have to do
it). Original is like:

if errors:
self.status = _('There were errors')
result = action.failure(data, errors)
elif errors is not None:
self.form_reset = True
result = action.success(data)
else:
result = None

self.form_result = result


action.success method is the one that has filled data dictionary
passed as parameter. In opposite, validate function only gets empty
data dictionary. So it becomes natural to do some validation in
success handler (although it is possibly not supposed to be done here?).
More, if for example succes handler function does
insert or update to a RDBMS wchich may cause some errors (or receive
error message from stored procedure etc.) it is desirable to set form
errors too. My modified update method is like:

if errors:
self.status = _('There were errors')
result = action.failure(data, errors)
elif errors is not None:
result = action.success(data)
if not self.errors:
self.form_reset = True
else:
    self.status = _('There were errors')
result = action.failure(data, errors)
else:
result = None


-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] formlib with no zodb

2007-03-16 Thread Maciej Wisniowski
ppend(u'db error...')


views.py
---
from zope.formlib import form
from zope.app.form.browser import BytesWidget
from zope.traversing.browser.absoluteurl import absoluteURL
from dbformlib.browser import DBFormlibEditForm
from monitor.interfaces import IAccount

class WideBytesWidget(BytesWidget):
displayWidth = 80

class AccountEditForm(DBFormlibEditForm):
label   = u'Edit my data'
actions = DBFormlibEditForm.actions

def define_fields(self):
self.form_fields = form.Fields(IAccount)
self.form_fields['adres'].custom_widget = WideBytesWidget

@form.action(u'Cancel', validator=lambda *a: ())  # hack to omit
validation
def handle_cancel_action(self, action, data):
data = self.get_data_obj().get_data()
absoluteURL(self.context, self.request)

if data['cancel_url']:
self.request.response.redirect(data['cancel_url'])
return None


configure.zcml
-
...

...

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] keeping GET data in a formlib based form

2007-03-14 Thread Maciej Wisniowski

> I need a way to keep 'myarg' information in my form for subsequent
> calls. Ideally I would like some mechanism that ends writing an  type="hidden" id="myarg" value="23"/> tag in the html because that way
> my code:
>
> def update(self):
>   [..]
>   data = self.request['myarg']
>   [..]
>
> will still work, right?
>
> I have thought about extending the formlib template to just do that or
> maybe adding a form.Field to my form with a special Widget associated to
> it. No idea of what's the best aproach.
>
> Anyone has pointer for this?
Maybe the simplest solution is to use session for storing this data,
eg.:

in update you check if there is 'myarg' in request, and if so then
put this into session. If there is no 'myarg' in request
you get this from session.

If you want this passed via POST/GET then you may try with
hidden() method of widgets, or write own widget that
renders as a hidden input, like:

class EntryWidget(SimpleInputWidget):   
   
def _toFieldValue(self, input):
return unicode(input)   
   
def __call__(self):
return self.hidden()

and assign this widget to field that will represent 'myarg':

self.form_fields['myarg'].custom_widget=EntryWidget

You will possibly have to change the line:
data = self.request['myarg']

because your input will have form prefix.
I'm not sure, but you may have some issues with this solution
when doing resetForm etc.

-- 
Maciej Wisniowski

___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Crash

2007-03-12 Thread Maciej Wisniowski

>
> The last entry in the access.log is the following:
> 218.160.132.172 - - [10/Mar/2007:22:11:45 -0500] "CONNECT
> sextw.com.tw:25 HTTP/1.0" 404 0 "-" "-"
>
> There is no other information to indicate why as far as we can tell.
> No exceptions, nothing.
Anything in /var/log/messages? Segfault or something like that maybe?

We had similiar issues with Zope2 and there were segfault errors in
messages file
(due to 64 bit architecture and DCOracle2)

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Re: Default value for an interface attribute

2007-03-11 Thread Maciej Wisniowski

>>> How about checking whether the value of 'default' is a
>>> callable and if so call it to obtain the default value.
>>>   
>> Yup... but evaluation of this is done internally by Zope schema
>> package in Field class I think. Seems for me that there is no way
>> to define 'default' as callable.
>> 
>
> Right. This is an unsupported use case. I bet if someone writes up a
> proposal and brings it up to discussion on zope3-dev@zope.org we'll find
> a common solution to this.
>
> Please also notice that we're moving to using launchpad more heavily. So
> if you write a proposal in the wiki, please also submit it as a feature
> request (blue print) in launchpad for the Zope 3 product.
I was playing a bit more with this issue and I realized that formlib
fields have 'get_rendered' method which is called to get default
values for a field. It is described at 'Computing default values'
section in formlib/form.txt.

Example from form.txt:

>>> class MyAddForm(form.AddFormBase):
... actions = ()
...
... def now(self):
... return datetime.datetime(2002, 12, 2, 12, 30)
...
... form_fields = form.Fields(
... form.Fields(IOrder).omit('now'),
... form.Field(IOrder['now'], get_rendered=now),
    ...     )
    ...
... def setUpWidgets(self, ignore_request=True):
... super(MyAddForm, self).setUpWidgets(ignore_request)

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Zope3 with RDBMS (avoiding ZODB)?

2007-03-05 Thread Maciej Wisniowski

> We do mostly SQL/RDBMS.  We have tried ZAlchmey, and SQLOs, but we
> find them both a bit limiting and simultaneous complex to get them to
> work they way we wanted.  In general when one develops and RDBMS
> application of any size, the database structure can get very complex. 
> In order to integrate them into Zope 3 just right, it's best to
> manually code the containers and objects.  We have been able to
> simplify the process quite a bit and we are very happy with it.  It's
> amazing scalable.If you do decide to go this way, I would be glad
> to share our RBDMS package and procedures.  We've developed some
> guidelines to improve development.  We use MySQL exclusively.
It would be really nice to see your RDBMS package, so if this is
possible then please show it to us :)

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Widget for displaying Text das HTML

2007-03-01 Thread Maciej Wisniowski
> If not, how would you implement it? (just the concept, not the code) ;-)
Take a look at 'Zope3 developer's handbook' by Stephan Richter (there is
online version I think). You'll find a example of custom HTML field and
widget there. It is not exactly what you're looking for but I think
it may be helpful.

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Re: Default value for an interface attribute

2007-03-01 Thread Maciej Wisniowski

> How about checking whether the value of 'default' is a
> callable and if so call it to obtain the default value.
Yup... but evaluation of this is done internally by Zope schema
package in Field class I think. Seems for me that there is no way
to define 'default' as callable.

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Default value for an interface attribute

2007-03-01 Thread Maciej Wisniowski

> I have this interface:
>
> class INews(IPage):
> """A news page for the application.
> """
>
> date = Date(
> title=_(u"Publication Date"),
> description=_(u"The intended date for this news"),
> default=date.today(),
> required=False
> )
>   
With formlib (in Five in fact, not with Zope3) I was creating
form_fields that should have dynamic defaults in __call__
method of formlib's AddForm (EditForm)
view. I think it is not nice solution so I'd love to see
better way of doing this.

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] External content with ZPT

2007-02-26 Thread Maciej Wisniowski

> Is there a simple way to use ZPT to include external content?
> Something that resembles Apache SSI--I was hoping there is something
> along the lines of tal:include="addr" but it does not appear to be
> quite this easy. The content in question is a script that I'd rather
> not rewrite.
The 'script' you're talking about returns HTML?? Is this a web page?
web service? file? It is available under URL? The  content is script
itself or something that this script returns?

Not sure if I understand correctly but if you want to "paste some html
from url", then AFAIK ZPT has no statement (shortcut) for this kind of
things.

> Search has turned up wrapping the functionality in python code. Can I
> do this without a urllib2 wrapper?
Depends what 'external' is for you... In general you may use different
protocol, something with xml-rpc, json and this stuff. What is wrong
with urllib2? On the other hand you may just use iframes or some
javascripts/ajax things on the client side.

-- 
Maciej Wisniowski


___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Re: formlib vs. cancel button

2007-02-15 Thread Maciej Wisniowski

> Yes. I think you misunderstand my suggestion.
I knew someone will write this :)
I didn't think about default validator value before sending
my previous email. I found this pattern after later... at bed :)
so I agree that this might be a good solution that has
enough backward compatibility and seems to be rather
easy to implement

+1

-- 
Maciej Wisniowski

___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Re: formlib vs. cancel button

2007-02-15 Thread Maciej Wisniowski

>> @form.action("Cancel", validator=None)
-1 from me

Currently above code is same as:
>> @form.action("Cancel")

So I think this is a very common pattern that means:
do standard validation, do not use additional action validator.

In general there are two
validators. Action validator (one we are assigning in the
above code) and default validator of the form.

handleSubmit is responsible
for handling action submits and this looks like that:

def handleSubmit(actions, data, default_validate=None):
for action in actions:
if action.submitted():
errors = action.validate(data)  # validator we want set to
# None is used here
if errors is None:
errors = default_validate(action, data)
return errors, action

So first action.validate is called:

def validate(self, data):
if self.validator is not None:  # THIS MAY BE NONE
return self.validator(self.form, self, data)

and when there are no errors (None is returned) then default
validator is executed which is:

def validate(self, action, data):
return (getWidgetsData(self.widgets, self.prefix, data)
+ checkInvariants(self.form_fields, data))

I might be wrong somewhere, so somebody better check this :)

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Standard Macros

2007-02-11 Thread Maciej Wisniowski
> Any Ideas are appriciated. and more importantly, do other people get the
> same error as I get??? I would really appriciate if someone tried the
> above code in a ZPTPage through ZMI and tell me the results...
Yup, I get same error about UnauthenticatedPrincipal and 'title'.
Have you tried if this works when this code is in
view? I wonder if UnauthenticatedPrincipal object has 'title'
attribute when called from page template registered as view?

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Standard Macros

2007-02-10 Thread Maciej Wisniowski
> I have the same problem. I just know the problem is with the
> principal_info macro and it only occurs when one is logged in with a PAU
> principal (ZCML principals do fine as far as I remember).
'same problem' is not enough I think. What is the traceback etc?

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Standard Macros

2007-02-10 Thread Maciej Wisniowski
> Any ideas?

bla bla bla


Take a look at: zope/app/basicskin/configure.zcml and you'll
see how standard_macros view is registered.

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Will zope server crash when uploading huge filesinthe same time?

2007-02-06 Thread Maciej Wisniowski
> yes, but you don't get the HTTP headers (in a zope application) until
> after the file upload is completed.  If you use Apache's 
> LimitRequestBody directive you can limit file sizes uploaded by a user,
> but if the user exceeds this limit they get an apache error response (as
> opposed to something a little more user-friendly issued by the zope
> application).
I've written about this in my answer to previous Alex Cheng post.
There is tramline (http://www.infrae.com/products/tramline) product
from infrae. It deals with uploading large files via apache.
They say something like:
to handle upload:
 * file contents will contain the unique file id.
 * send out 'tramline_ok' header if file is accepted. Failure to send
out this header will cause the file to be rejected.

Interestin line for you may be: "'tramline_ok' header should be sent if
file is accepted" because seems that you have some kind of control
before upload. But I don't know how it works. Maybe it does what you're
looking for.

Also Tramline seems to be almost separate from application server so
possibly Zope is not in danger while few users is sending large files.

-- 
Maciej Wisniowski

___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] How to provide user to upload a large file(100M) with zope

2007-02-06 Thread Maciej Wisniowski

> I create a website with zope, but I need let my customers upload files
> from HTTP. How to provide user to upload a large file(100M) with zope?
Maybe http://www.infrae.com/products/tramline can help you.

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] css question

2007-02-05 Thread Maciej Wisniowski

> i've downloaded the package, tried to modify the css file according to
> readme.txt, but something i miss
> i receive the folllowing exception:
> TypeError: ('Could not adapt',  instance
> URL=http://localhost:8080/ap_test/@@/++resource++>,  zope.app.rot
> terdam.Rotterdam>)
Have you copied:
zc.resourcelibrary-configure.zcml,
zc.resourcelibrary-ftesting.zcml,
zc.resourcelibrary-meta.zcml

into your /etc/package-includes ?

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] newbie database adapter questions

2007-02-02 Thread Maciej Wisniowski

> It seems like most of the examples only explain how to create forms by
> using interfaces and objects.  
I've noticed this too.

> I don't want a user within zope to create a form in the ZODB, I just
> want to them to open up a location to url and see results from my
> database.  
Currently I'm doing something like that. It it supposed to work this way:
1. You enter url like
http://localhost:8080/manage_customer_form?in.customer_id=23
2. Form is displayed that contains data from underlying RDBMS
3. If you want another customer then you need to change in.customer_id
parameter value

There also other possiblities, eg. "Container/Folder that contains
object from a database.
The container is persistent.  The container however loads the content
from an SQL database"
This is from David Johnson post to this list at: 2007.01.26 in thread:
"Access to request in content object and object path in doctests". David
declared that
he may share his code but so far I don't have it. I'll try to remind him.


My implementation is like:

I've created content object that has two functions:
1. to get data from RDBMS (but this is not necessarily RDBMS)
2. to store data to RDBMS
Typically these functions will do 'select ... from' and 'update ...'

Then I've attached formlib view based on FormBase to this content object.
My setUpWidgets function gets input parameters from request, passes
them to get_data function of content object to receive data from RDBMS
and then uses setUpDataWidgets to set up widgets. Save action causes
to save_data function to be called.
There are some drawbacks, eg. you need to remember input parameters
somewhere etc.

My code is not ready yet but should be soon.
I'll try to publish it somwhere if somebody is interested.

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


[Zope3-Users] Doctests and authenticated principal

2007-01-31 Thread Maciej Wisniowski
Hi

I'm writing doctest using DocFileSuite.
Code that I'm testing needs information
about currently authenticated principal.
It uses: request.principal.id to get it.

In doc test I may use:

>>> request = TestRequest()
>>> class User(object):
... id = 'Jan'
... title = 'Jan Kowalski'
>>> request.setPrincipal(User())
..rest of the test..

and after this everything works.
Is this correct way?


I also have some code that uses:

from zope.app.security.interfaces import ILoginPassword
ILoginPassword(self.request).getLogin()

During tests, I always get None as result of the above
statement.

So another question, what is the correct way to
get currently authenticated principal id:
request.principal.id or ILoginPassword(self.request).getLogin()?

-- 
Maciej Wisniowski



___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Tests are not working Was: Access to request in content object and object path in doctests

2007-01-29 Thread Maciej Wisniowski

> I'm trying to create doctests and I'm not able to get
> my view with getMultiAdapter. I can't find why...
> Do I have to explicitly call XMLConfig or something
> like that? What is wrong?
>   
I've found that modifying setUp function like
below helped, an my test now executes properly:

def setUp(test):
setup.placelessSetUp()
setup.setUpTraversal()
XMLConfig('meta.zcml', zope.component)()
XMLConfig('meta.zcml', zope.app)()
XMLConfig('configure.zcml', zope.app)()
XMLConfig('configure.zcml', basic)()


Although I'm still not sure if this is correct way.

---
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Tests are not working Was: Access to request in content object and object path in doctests

2007-01-28 Thread Maciej Wisniowski
Marius, thanks for your answers, it was helpful :)

Although I still have some silly problems with tests...

I've created simplest possible structure with
view, content class and interface and a bit of
zcml to register view as index.html. This works
in Zope because after creating content object
I'm able to go to index.html and see what I expected.

I'm trying to create doctests and I'm not able to get
my view with getMultiAdapter. I can't find why...
Do I have to explicitly call XMLConfig or something
like that? What is wrong?


basic/basic.py:

from persistent import Persistent
from zope import schema
from zope.interface import implements, Interface
import zope.publisher.browser
 
class IMyInterface(Interface):
''' interface
'''
  
class MyContent(Persistent):  #MyBaseContent):
''' content
'''
implements(IMyInterface)

class MyView(zope.publisher.browser.BrowserPage):
''' view
'''
def __call__(self):
return ''


basic/configure.zcml
-
http://namespaces.zope.org/zope";
xmlns:zcml="http://namespaces.zope.org/zcml";
xmlns:browser="http://namespaces.zope.org/browser";> 
 
  

   



basic/tests/test_basic.py
--
import unittest
from zope.app.testing import setup

def setUp(test):
setup.placelessSetUp()
setup.setUpTraversal()
   
def tearDown(test):
setup.placelessTearDown()
   
def test_basic():
"""\

  >>> from basic.basic import MyContent
  >>> from zope.publisher.browser import TestRequest
  >>> from zope import component
  >>> from zope.interface import Interface
 
  >>> test_content = MyContent()
  >>> request = TestRequest(form={'tfl.row_id':1})
  >>> rview = component.getMultiAdapter(
  ... (test_content, request), Interface, 'index.html')
  >>> rview()
  'a'  
"""
   
def test_suite():
from zope.testing import doctest
suite = unittest.TestSuite()
suite.addTest(doctest.DocTestSuite(
  setUp=setUp, tearDown=tearDown,
 ))
return suite

if __name__=='__main__':
unittest.main(defaultTest='test_suite')



Another question is how to get
request.principal? I did:
  >>> request = TestRequest(form={'tfl.row_id':1})
  >>> class User(object):
  ... id = 'Jan'
  >>> request.setPrincipal(User())

but is this correct way? Shouldn't this be done by testing
framework already?

---
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Access to request in content object and object path in doctests

2007-01-26 Thread Maciej Wisniowski

> 2. Generally you will want to create content with methods that can
> perform the database operations you would like.  For example, I
> recently created a Container/Folder that contains object from a
> database.  The container is persistent.  The container however loads
> the content from an SQL database. I can then edit and view the objects
> from the SQL database like ZODB objects.  I have some code that I can
> share here.
I'm interested in it! If you can send it to me or publish somewhere I
would be really gratefull.

> In another example, which may suite your needs, I created a Zope site
> in which customers can lookup orders by an order id.  My content
> object is effectively a class "Order", which has a method,
> "getOrderById", and that takes an order id as the parameter. 
> getOrderById() queries the database and returns the order as a
> dictionary.  
Yup, that's similiar to what I'm trying to accomplish. I want to create
something general for this kind of forms (with caching etc). I had
something like that in Zope 2.x.

Thanks for the pointers.

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Access to request in content object and object path in doctests

2007-01-25 Thread Maciej Wisniowski

> line 154, in getPath
> raise TypeError("Not enough context to determine location root")
> TypeError: Not enough context to determine location root
I've added Contained as the base class of my content
and it works now... uff...

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Access to request in content object and object path in doctests

2007-01-25 Thread Maciej Wisniowski

> )
>
> Ehm...? Ideas?
OK, I forgot about:
setup.setUpTraversal()

Now it works with:

>>> from zope.app.folder import rootFolder 
>>> from zope.traversing.api import getPath
>>> root = rootFolder()
>>> root['test_content'] = DBCrudContent()
>>> test_content = root['test_content']
>>> getPath(root['test_content'])
/test_content

but unfortuantelly when my object is trying to get
path to itself like:

class DBCrudContent():
def myfunction(self):
getPath(self)

>>> test_content.myfunction()

I get error:

File "dbcrudbase.txt", line 86, in dbcrudbase.txt
Failed example:
test_content.myfunction()
Exception raised:
Traceback (most recent call last):
  File
"/home/downloads/Zope/Zope-3.3.0/build/lib.linux-i686-2.4/zope/testing/doctest.py",
line 1256, in __run
compileflags, 1) in test.globs
  File "", line 1, in ?
test_content.myfunction()
  File "", line 18, in myfunction
getPath(self)
  File
"/home/downloads/Zope/Zope-3.3.0/build/lib.linux-i686-2.4/zope/traversing/api.py",
line 62, in getPath
return IPhysicallyLocatable(obj).getPath()
  File
"/home/downloads/Zope/Zope-3.3.0/build/lib.linux-i686-2.4/zope/location/traversing.py",
line 154, in getPath
raise TypeError("Not enough context to determine location root")
TypeError: Not enough context to determine location root

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Access to request in content object and object path in doctests

2007-01-24 Thread Maciej Wisniowski

> Yes.  You're not supposed to do that.  Views work with requests, not
> content objects.
>
> If you told us what you want to achieve, we could help you find a way to
> do it that works with Zope 3 rather than against it.
>   
I'am creating form (CRUD) based on formlib, but this
is supposed to work with relational database.
Design is simple:
content_object -> view(based on formlib.form)

My content_object gets data from RDBMS and stores
data into RDBMS. So I want to be able to call something like:
content_object/@@editview?row_id=1
to get and set data for row with row_id = 1 in RDBMS or
content_object/@@delview?row_id=2
to remove data from RDBMS etc.

Simply, I don't have x content objects that are
mappings of x rows in RDBMS, but I have one
object to do CRUD operations on every row in database.

content_object is responsible for calling sql statements
so it needs data from the request. Possibly I have to pass
them (or the whole request) from the view?

>> >>> root = rootFolder()
>> >>> root['my_object'] = my_object = MyObject()
>> >>> getPath(my_object)
>> '/my_object'
>> 
Hm... My doctest:

  >>> from zope.app.folder import rootFolder 
  >>> from zope.traversing.api import getPath
  >>> root = rootFolder()
  >>> root['test_content'] = test_content = DBCrudContent()
  >>> getPath(test_content)

and I get:

File "dbcrudbase.txt", line 83, in dbcrudbase.txt
Failed example:
getPath(root['test_content'])
Exception raised:
Traceback (most recent call last):
  File
"/home/downloads/Zope/Zope-3.3.0/build/lib.linux-i686-2.4/zope/testing/doctest.py",
line 1256, in __run
compileflags, 1) in test.globs
  File "", line 1, in ?
getPath(root['test_content'])
  File
"/home/downloads/Zope/Zope-3.3.0/build/lib.linux-i686-2.4/zope/traversing/api.py",
line 62, in getPath
return IPhysicallyLocatable(obj).getPath()
TypeError: ('Could not adapt',
,
)

Ehm...? Ideas?

-- 
Maciej Wisniowski

___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


[Zope3-Users] Access to request in content object and object path in doctests

2007-01-24 Thread Maciej Wisniowski
Hi

Two questions...

Is this possible to get
request object in content class. In Zope2 this
was possible with simple self.REQUEST. In Zope3
I tried self.request but I only get errors.
Maybe this is a feature, and I'm not supposed
to access request object from content class?


Another question. I'm trying to write tests
for my content object.
Because I want some caching facilities
I'm using getLocationForCache from
zope.app.cache.caching.
and because of this: zapi.getPath(obj)

In short it is like:

class MyClass(Persistent):
(...)
def myfunction(self):
location = zapi.getPath(self)
return location

In the tests I always get location == None.
I'm using doctests like:

   >>> test_content = MyClass()
   >>> test_content.myfunction()

placefulsetup adds some objects like root etc.
but I'm not sure how I should add my object to this.
Any clues?

-- 
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] Zope3.3.0-zope.rdb implementation - bug, feature?

2006-10-15 Thread Maciej Wisniowski


A workaround would be to rename any offending columns (forgive my 
rusty SQL if this isn't quite right):


  select 1 as one from dual

Yes, I've even written this in my previous email :)


the names of numeric attributes (like '1') to prefixed ones
(like '_1') It works but I'm not sure whether it is proper
solution for something other than tests, but in general
who may use this kind of dynamically created labels for
something useful...?
Personally, I don't see zope.rdb being as very useful and would expect 
to see third-party RDB interfaces supersede it.

As I can see in Zope3 ResultSet's are used
directly by SQLScripts.
Do you mean that third-party RDB interfaces should have it's
own SQLScripts implementation or some other
changes should be done?




I'd submit a bug report with the details you included in your email.

OK

--
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] zc.winauth takes too much time to authenticate every page load

2006-10-15 Thread Maciej Wisniowski


I digged through google and found many things called CAS or similar... 
did you mean this: http://www.zope.org/Members/mrlex/ACUF ?
I meant http://www.zope.org/Members/regebro/CAS4PAS. It's Zope2 stuff, 
but may be somewhat helpful because it's a plugin for PAS (pluggable 
authentication services) which (I think) is similiar to PAU in Zope3.


In general you should take a look at Readme and interfaces.py in PAU 
directory.


HTH

--
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] zc.winauth takes too much time to authenticate every page load

2006-10-13 Thread Maciej Wisniowski


I'd like to see a plugin that stores that information in a session, 
that way the plugin could be used with zc.winauth or any other 
credential mechanism.
I know nothing about PAU architecture... yet ;) If you, or some other 
PAU experts, could give some suggestions how to wire such a thing with 
zc.winauth and PAU, I would be grateful

You may want to take a look at CAS plugin for PAS in
Zope2 (I think PAS is similiar to PAU) or maybe there
already is CAS plugin for PAU.
CAS plugin, after initial authentication in external
server, stores this information in session so further
requests don't have to create any background
connections.

Pozdrowienia ;)

--
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


[Zope3-Users] Zope3.3.0-zope.rdb implementation - bug, feature?

2006-10-13 Thread Maciej Wisniowski

Hi!

I've asked this question on Zope-DB already but get
no answer, so maybe this list is better to ask for this issue.

I've just tried to use Zope3.3.0 with cx_Oracle adapter
and to check whether connection works I've used
typical for Oracle statement:

select 1 from dual

I've received error:
TypeError: __slots__ must be identifiers

The problem is (I think) with class Row or
RowClassFactory defined
in zope/rdb/__init__.py.

There is current implementation of RowClassFactory:

def RowClassFactory(columns):
"""Creates a Row object"""
klass_namespace = {}
klass_namespace['__Security_checker__'] = InstanceOnlyDescriptor(
NamesChecker(columns))
klass_namespace['__slots__'] = tuple(columns)

return type('GeneratedRowClass', (Row,), klass_namespace)

in my case:

klass_namespace is {'__slots__':('1',)}

and '1' causes error (number is not a proper identifier).

select 1 as abc from dual

executes correctly.

I've implemented temporary solution that simply changes
the names of numeric attributes (like '1') to prefixed ones
(like '_1') It works but I'm not sure whether it is proper
solution for something other than tests, but in general
who may use this kind of dynamically created labels for
something useful...?

Is this issue a bug or feature or something else? I'm not able to
recognise them myself (especially after submitting
request.locale issue on z3-five list :)).

I would like to know your's opinions
before submiting a bug and/or trying to create a patch.

--
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] long lasting transactions

2005-12-15 Thread Maciej Wisniowski

> Not everyone is fooled into thinking they need an RDB ;-)
You're right. I should add 'just in case it is the problem with
relational DB'.

--
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users


Re: [Zope3-Users] long lasting transactions

2005-12-15 Thread Maciej Wisniowski



I need a way to keep a transaction active over several
requests and commit it manually afterwords. Currently
the object publisher (or whatever responsible for that)
commits a transaction



One request = one transaction. I think there is no way to get around 
(this limitation from your point of view). You should store your data 
in a session and perform the necessary actions at the end of the last 
step. 


AFAIR there is a suspend transaction feature in SQLRelay database connector
but I've never tried this feature in Zope. SQLRelay has DA for Zope 2.x. so
I think it would be necessary to write such thing for Zope 3.x.

--
Maciej Wisniowski
___
Zope3-users mailing list
Zope3-users@zope.org
http://mail.zope.org/mailman/listinfo/zope3-users