jsonify

2010-07-28 Thread Eric Lemoine
Hello

Does anyone know why jsonify does

response.headers[Content-Type] = application/json

instead of

response.content_type = application/json

Is there a good reason for that?

Thanks,

-- 
Eric Lemoine

Camptocamp France SAS
Savoie Technolac, BP 352
73377 Le Bourget du Lac, Cedex

Tel : 00 33 4 79 44 44 96
Mail : eric.lemo...@camptocamp.com
http://www.camptocamp.com

-- 
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-disc...@googlegroups.com.
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en.



Re: jsonify

2010-07-28 Thread Gael Pasgrimaud
On Wed, Jul 28, 2010 at 11:03 AM, Eric Lemoine
eric.lemo...@camptocamp.com wrote:
 Hello

 Does anyone know why jsonify does

 response.headers[Content-Type] = application/json

 instead of

 response.content_type = application/json

 Is there a good reason for that?

I don't think. That's two way to get exactly the same result.
You probably win 0.0001s by setting the headers key directly.

--
Gael


 Thanks,

 --
 Eric Lemoine

 Camptocamp France SAS
 Savoie Technolac, BP 352
 73377 Le Bourget du Lac, Cedex

 Tel : 00 33 4 79 44 44 96
 Mail : eric.lemo...@camptocamp.com
 http://www.camptocamp.com

 --
 You received this message because you are subscribed to the Google Groups 
 pylons-discuss group.
 To post to this group, send email to pylons-disc...@googlegroups.com.
 To unsubscribe from this group, send email to 
 pylons-discuss+unsubscr...@googlegroups.com.
 For more options, visit this group at 
 http://groups.google.com/group/pylons-discuss?hl=en.



-- 
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-disc...@googlegroups.com.
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en.



Re: jsonify

2010-07-28 Thread Eric Lemoine
On Wed, Jul 28, 2010 at 12:37 PM, Gael Pasgrimaud g...@gawel.org wrote:
 On Wed, Jul 28, 2010 at 11:03 AM, Eric Lemoine
 eric.lemo...@camptocamp.com wrote:
 Hello

 Does anyone know why jsonify does

 response.headers[Content-Type] = application/json

 instead of

 response.content_type = application/json

 Is there a good reason for that?

 I don't think. That's two way to get exactly the same result.
 You probably win 0.0001s by setting the headers key directly.

Thanks Gaël.

For the record, my question was related to a ticket I was working on.
See http://pylonshq.com/project/pylonshq/ticket/632. I've got a
patch that I deem ready for review.


-- 
Eric Lemoine

Camptocamp France SAS
Savoie Technolac, BP 352
73377 Le Bourget du Lac, Cedex

Tel : 00 33 4 79 44 44 96
Mail : eric.lemo...@camptocamp.com
http://www.camptocamp.com

-- 
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-disc...@googlegroups.com.
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en.



Filter of @jsonify

2010-04-26 Thread Alexander Zhabotinskiy
How to filter log messages
JSON responses with Array envelopes are susceptible to cross-site
data leak attacks, see http://pylonshq.com/warnings/JSONArray;

The log's is too large

-- 
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-disc...@googlegroups.com.
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en.



Re: Filter of @jsonify

2010-04-26 Thread cd34
You might find this thread might solve the issue:
http://groups.google.com/group/pylons-discuss/browse_thread/thread/744a1bea7928a223/

The URL in the error is also incorrect and should probably point to:
http://wiki.pylonshq.com/display/pylonsfaq/Warnings

-- 
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-disc...@googlegroups.com.
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en.



Re: searching for some jsonify example or tutorial

2009-12-20 Thread Paweł Stradomski
W liście Mike Orr z dnia sobota 19 grudnia 2009:
 On Sat, Dec 19, 2009 at 7:55 AM, Graham Higgins gjhigg...@gmail.com wrote:
  A decorator is a Python object that can be called with a single
  argument and which modifies a function or a method.
 
 wraps would be a better term.  The decorator wraps the original
 function in another function, which can do preprocessing,
 postprocessing, or even not call the original function if it chooses.
 
Not strictly correct. There are decorators (eg. CherryPy's @expose) that 
return the same function they received, just with additional attributes. So no 
wrapping occurs.

-- 
Paweł Stradomski

--

You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-disc...@googlegroups.com.
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en.




Re: searching for some jsonify example or tutorial

2009-12-19 Thread Krishnakant
On Thu, 2009-12-17 at 22:21 +, Graham Higgins wrote:
 -BEGIN PGP SIGNED MESSAGE-
 Hash: SHA1
 
 
 On 17 Dec 2009, at 21:20, Marius Gedminas wrote:
 
  I recall some fun times being had by all when the json dumper  
  generated
 
   {title: something irrelevant, date: 2004-01-17}
 
  which the browser nicely and silently evaluated to
 
   {title: something irrelevant, date: 1986}
 
 
 
 'Tis true, computers are even more pitilessly literal than children.
 
 Cheers,
 
 Graham

HI Graham,
I thought I would put this question in a different way, not just to keep
it on-topic for pylons list and make my mis-understanding clear about
the issue at hand.

I know that json objects are nothing but key value paers like the dict
in python.
My ownly question is that when we do @jsonify, do we need to say which
action we want to use for returning a json response or just putting the
@jsonify asumes that the action following that line is the one to be
used for responding to json requests?

Secondly, is it necessary to attach the json objects to the tmpl_context
(c) for sending across?

Happy hacking.

Krishnakant.


--

You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-disc...@googlegroups.com.
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en.




Re: searching for some jsonify example or tutorial

2009-12-19 Thread Mario Romero
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA224

 My ownly question is that when we do @jsonify, do we need to say which
 action we want to use for returning a json response or just putting  
 the
 @jsonify asumes that the action following that line is the one to be
 used for responding to json requests?

@jsonify will convert to json whatever object that function returns.
I dont know what you mean by the one that will be used to answer json  
requests
I assume that more than one of your actions will return json objects.
did you read at all the book chapter that was linked to you?


 Secondly, is it necessary to attach the json objects to the  
 tmpl_context
 (c) for sending across?

No, you dont need to use templates, you just return the json object  
directly.



On Dec 19, 2009, at 3:35 AM, Krishnakant wrote:

 On Thu, 2009-12-17 at 22:21 +, Graham Higgins wrote:
 -BEGIN PGP SIGNED MESSAGE-
 Hash: SHA1


 On 17 Dec 2009, at 21:20, Marius Gedminas wrote:

 I recall some fun times being had by all when the json dumper
 generated

 {title: something irrelevant, date: 2004-01-17}

 which the browser nicely and silently evaluated to

 {title: something irrelevant, date: 1986}



 'Tis true, computers are even more pitilessly literal than children.

 Cheers,

 Graham

 HI Graham,
 I thought I would put this question in a different way, not just to  
 keep
 it on-topic for pylons list and make my mis-understanding clear about
 the issue at hand.

 I know that json objects are nothing but key value paers like the dict
 in python.
 My ownly question is that when we do @jsonify, do we need to say which
 action we want to use for returning a json response or just putting  
 the
 @jsonify asumes that the action following that line is the one to be
 used for responding to json requests?

 Secondly, is it necessary to attach the json objects to the  
 tmpl_context
 (c) for sending across?

 Happy hacking.

 Krishnakant.


 --

 You received this message because you are subscribed to the Google  
 Groups pylons-discuss group.
 To post to this group, send email to pylons-disc...@googlegroups.com.
 To unsubscribe from this group, send email to 
 pylons-discuss+unsubscr...@googlegroups.com 
 .
 For more options, visit this group at 
 http://groups.google.com/group/pylons-discuss?hl=en 
 .



-BEGIN PGP SIGNATURE-
Version: GnuPG/MacGPG2 v2.0.12 (Darwin)

iFYEARELAAYFAksssrYACgkQFXxYxga0LLnLQQDgoPB2NP+DbRaGsTaRtyyuZlHT
lFuPw4FymaD4oQDfd1iEBMt1OfU5kpsUVVBrsa872/xjg0EVa0UIyw==
=pW9k
-END PGP SIGNATURE-

--

You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-disc...@googlegroups.com.
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en.




Re: searching for some jsonify example or tutorial

2009-12-19 Thread Graham Higgins
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi Krishnakant,

On 19 Dec 2009, at 09:35, Krishnakant wrote:
 I thought I would put this question in a different way, not just to  
 keep
 it on-topic for pylons list and make my mis-understanding clear about
 the issue at hand.

Understood - and answered in a similar spirit ...

 My ownly question is that when we do @jsonify, do we need to say which
 action we want to use for returning a json response or just putting  
 the
 @jsonify asumes that the action following that line is the one to be
 used for responding to json requests?


Following up on Mario's post ...

@jsonify is an example of a Python decorator. Unfortunately, the  
concept of a decorator in Python is not terribly well documented as  
demonstrated by a couple of probes of the official Python  
documentation (don't bother following these two links, KK, they'd just  
be a waste of your time):

http://docs.python.org/search.html?q=decorators
http://docs.python.org/glossary.html#term-decorators

Probably the best overview description of decorators appears in  
Python's wikipedia entry (keep it for later, KK):

http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Decorators

Let's see if we can produce a succinct distillation from the wikipedia  
entry:

A decorator is a Python object that can be called with a single  
argument and which modifies a function or a method. Python decorators  
were inspired in part by Java annotations, and have a similar syntax;  
the decorator syntax is pure syntactic sugar and uses @ as the  
keyword, e.g. @jsonify. Decorators are a form of metaprogramming;  
they enhance the action of the function or method they decorate.

To decorate a function or a method, simply reference the decorator in  
the line immediately prior to the function/method definition, as shown  
in this pseudo-code:

 @jsonify
 def entityname(self, id):
 dbentity = model.Session.query(model.MyEntity).get(id)
 return {name: dbentity.name}

Decorators are often used as convenience functions (to use a broad  
term, broadly), here's the (slightly edited) Pylons code for @jsonify:

 import simplejson
 from decorator import decorator
 from pylons.decorators.util import get_pylons

 def jsonify(func, *args, **kwargs):
 Action decorator that formats output for JSON

 Given a function that will return content, this decorator will  
 turn
 the result into JSON, with a content-type of 'application/json'  
 and
 output it.

 
 pylons = get_pylons(args)
 pylons.response.headers['Content-Type'] = 'application/json'
 data = func(*args, **kwargs)
 if isinstance(data, (list, tuple)):
 msg = JSON responses with Array envelopes are susceptible  
 to  \
   cross-site data leak attacks, see  \
   http://pylonshq.com/warnings/JSONArray;
 warnings.warn(msg, Warning, 2)
 log.warning(msg)
 log.debug(Returning JSON wrapped action output)
 return simplejson.dumps(data)

 jsonify = decorator(jsonify)


[ BTW, the URL referenced in the warning doesn't actually resolve, so  
you'll just have to use your imagination as to exactly how dire is the  
detail of the warning about JSONArrays :-) ]

As you can see, it's a convenience. One could almost as easily set the  
response header oneself and similarly return the result of  
simplejson.dumps(data).

Note: as Mario observed, when using Pylons, you don't need to return a  
rendered template. If you wanted, your action could be as simple as:

 def test_action(self):
 return Hello world


or

 def test_action(self):
 return [Hello world]

Basically, you can return anything you like, just so long as it can be  
iterated. It's a WSGI thing rather than anything Pylons-specific but  
it explains why you can return just simplejson.dumps(data) without  
having to use a template as a vehicle for carrying the result.

Sometimes the convenience offered by decorators is significant. Here  
is the code for an @authorize decorator (used in the Shabti  
auth'n'auth augmented Pylons project template) which can be used to  
guard a controller action by imposing access-control permissions:

 def authorize(permission):

 Decorator for authenticating individual actions. Takes a  
 permission
 instance as argument(see lib/permissions.py for examples)
 def wrapper(func, self, *args, **kw):
 if permission.check():
 return func(self, *args, **kw)
 pylons.session['redirect'] = \
 pylons.request.environ['pylons.routes_dict']
 pylons.session.save()
 redirect_to_login()
 return decorator(wrapper)


Here's an example of a permission instance:

 class SignedIn(object):
 def check(self):
 return (get_user() is not None)


and the decorator is used typically thus (minimalist code, purely as  
an example):

 @authorize(SignedIn())
 def delete(self, id):
 dbentity = get_object_or_404(model.MyEntity, id=id

Re: searching for some jsonify example or tutorial

2009-12-19 Thread Mike Orr
On Sat, Dec 19, 2009 at 7:55 AM, Graham Higgins gjhigg...@gmail.com wrote:
 A decorator is a Python object that can be called with a single
 argument and which modifies a function or a method.

wraps would be a better term.  The decorator wraps the original
function in another function, which can do preprocessing,
postprocessing, or even not call the original function if it chooses.
Decorators are easy to use, but one of the most difficult things in
Python to write or understand the source.

-- 
Mike Orr sluggos...@gmail.com

--

You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-disc...@googlegroups.com.
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en.




Re: searching for some jsonify example or tutorial

2009-12-19 Thread Graham Higgins
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1


On 19 Dec 2009, at 22:32, Mike Orr wrote:

 On Sat, Dec 19, 2009 at 7:55 AM, Graham Higgins  
 gjhigg...@gmail.com wrote:
 A decorator is a Python object that can be called with a single
 argument and which modifies a function or a method.

 wraps would be a better term.

I think I prefer the description given in the wikipedia entry. Whilst  
wrapping does seem a reasonable metaphor at first glance, if it is  
used to describe the action of a decorator, it leaves one reaching  
with respect to the concept of wrapper functions defined inside  
decorators, such as that indicated by the functools.wrap()  
documentation:

http://docs.python.org/library/functools.html#functools.wraps

AIUI, the utility of wrapper functions inside decorators is that they  
provide access to the decorator function's variable scope, including  
the target function (culled from John Siafoo's article: 
http://www.siafoo.net/article/68) 
.

 Decorators are easy to use, but one of the most difficult things in
 Python to write or understand the source.


Personally, I think they're something of a poisoned pill in that  
respect. I use 'em but I don't particularly like 'em.

Cheers,

Graham

http://www.linkedin.com/in/ghiggins




-BEGIN PGP SIGNATURE-

iEYEARECAAYFAkstrmkACgkQOsmLt1NhivzM3QCcDiwfvgqP8gQErS+56c8a/eGT
9QEAoIEF0X/zAyxtso21jMbjJFf7XlRxiQCVAgUBSy2uaVnrWVZ7aXD1AQK3wgQA
o1RUuoW/3UDoHA8a2VzslwYAABQB881QpSjUatSoliv6z81hCAc/DNTdMtDzxx4r
+wvXdC1Mz69HIbV2KhJY08ZBS5LV7UDn0OC/1tuKwDJMdDzHwA5vrtopUuCKJc86
CUwY/Bzh34BXxonJOHzudwXqNdJ2ksvsHDFo2R8xXeA=
=7isB
-END PGP SIGNATURE-

--

You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-disc...@googlegroups.com.
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en.




searching for some jsonify example or tutorial

2009-12-17 Thread Krishnakant
Hello all,
I have been searching for some good json example for pylons application.

My case is that i have a list of accounts in a book keeping software and
when the user chooses one account, the opening balance has to be
displayed in a text field.

So i plan to right an onclick event for the list of accounts.  I want to
make an ajax call to some python action which can send back json
response.

Can any one suggest some tutorial or any example?


Happy hacking.
Krishnakant.


--

You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-disc...@googlegroups.com.
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en.




Re: searching for some jsonify example or tutorial

2009-12-17 Thread Mariano Mara
Excerpts from Krishnakant's message of Thu Dec 17 09:18:29 -0300 2009:
 Hello all,
 I have been searching for some good json example for pylons application.
 
 My case is that i have a list of accounts in a book keeping software and
 when the user chooses one account, the opening balance has to be
 displayed in a text field.
 
 So i plan to right an onclick event for the list of accounts.  I want to
 make an ajax call to some python action which can send back json
 response.
 
 Can any one suggest some tutorial or any example?
 
Did you check the pylons book example?
http://pylonsbook.com/en/1.1/css-javascript-and-ajax.html#json

--

You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-disc...@googlegroups.com.
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en.




Re: searching for some jsonify example or tutorial

2009-12-17 Thread Mario Romero
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA224

import simplejson
json_obj = {'foo', 'bar'}
return simplejson.dumps(json_obj)
etc...

On Dec 17, 2009, at 6:18 AM, Krishnakant wrote:

 Hello all,
 I have been searching for some good json example for pylons  
 application.

 My case is that i have a list of accounts in a book keeping software  
 and
 when the user chooses one account, the opening balance has to be
 displayed in a text field.

 So i plan to right an onclick event for the list of accounts.  I  
 want to
 make an ajax call to some python action which can send back json
 response.

 Can any one suggest some tutorial or any example?


 Happy hacking.
 Krishnakant.


 --

 You received this message because you are subscribed to the Google  
 Groups pylons-discuss group.
 To post to this group, send email to pylons-disc...@googlegroups.com.
 To unsubscribe from this group, send email to 
 pylons-discuss+unsubscr...@googlegroups.com 
 .
 For more options, visit this group at 
 http://groups.google.com/group/pylons-discuss?hl=en 
 .



-BEGIN PGP SIGNATURE-
Version: GnuPG/MacGPG2 v2.0.12 (Darwin)

iFYEARELAAYFAksqLY8ACgkQFXxYxga0LLmBagDeNm8ipcN5+NTWxxe3yv9h7jyX
/qfN8irP2ryOyQDdFLoUEkdQjQaBkXjNXoqhNCzpk5IjfEo9Wj5TVQ==
=1EM4
-END PGP SIGNATURE-

--

You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-disc...@googlegroups.com.
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en.




Re: searching for some jsonify example or tutorial

2009-12-17 Thread Jens Hoffrichter
 import simplejson
 json_obj = {'foo', 'bar'}
 return simplejson.dumps(json_obj)
 etc...

Or even simpler (at least in 0.9.6.2 - not sure if this still stands
with newer versions)

from pylons.decoraters import jsonify

class TestController(BaseController):
  @jsonify
  def testaction(self):
return {'foo','bar':4711}

Regards,
Jens

--

You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-disc...@googlegroups.com.
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en.




Re: searching for some jsonify example or tutorial

2009-12-17 Thread Graham Higgins
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1


On 17 Dec 2009, at 12:18, Krishnakant wrote:

 Hello all,
 I have been searching for some good json example for pylons  
 application.


Mariano's tightly-focused pointer should have landed you in the right  
place in that chapter of the Pylons book.

Watch out for datetime objects, they can't be directly serialised by  
simplejson's dumps().

See these various approaches:

1. Datetime-specific:

http://stackoverflow.com/questions/455580/json-datetime-between-python-and-javascript

and

http://code.activestate.com/recipes/200839/

2. Serialising arbitrary Python objects to JSON using __dict__

http://www.marcstober.com/blog/2007/07/07/serializing-arbitrary-python-objects-to-json-using-__dict__/

HTH

Cheers,

Graham

http://www.linkedin.com/in/ghiggins




-BEGIN PGP SIGNATURE-

iEYEARECAAYFAksqcQMACgkQOsmLt1Nhivz83QCffD2BBEHw3wVQcyXNjIwCtJyP
BOEAn38dYXvLCy9bwIIRO8w+bt1zKaitiQCVAgUBSypxA1nrWVZ7aXD1AQKELQQA
1HNodv1eWKZTZ8f9Nsx7BwYWHlvdAb436uv2cznJ877RMOqsYMEJRJlPRIu+QMQf
QTi0lqXXRwQdlc6VWTrLPDVsCx87z67F+K26Jtk1p1ojLYBlNa+ZS1AKX/SO5zVH
deolsGX4Cx/9HSQikUYZOwTTTtNkNgwvFlye1xssJkc=
=pzq8
-END PGP SIGNATURE-

--

You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-disc...@googlegroups.com.
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en.




Re: searching for some jsonify example or tutorial

2009-12-17 Thread Brian O'Connor
On Thu, Dec 17, 2009 at 12:57 PM, Graham Higgins gjhigg...@gmail.comwrote:

 -BEGIN PGP SIGNED MESSAGE-
 Hash: SHA1


 On 17 Dec 2009, at 12:18, Krishnakant wrote:

  Hello all,
  I have been searching for some good json example for pylons
  application.


 Mariano's tightly-focused pointer should have landed you in the right
 place in that chapter of the Pylons book.

 Watch out for datetime objects, they can't be directly serialised by
 simplejson's dumps().

 See these various approaches:

 1. Datetime-specific:


 http://stackoverflow.com/questions/455580/json-datetime-between-python-and-javascript

 and

 http://code.activestate.com/recipes/200839/

 2. Serialising arbitrary Python objects to JSON using __dict__


 http://www.marcstober.com/blog/2007/07/07/serializing-arbitrary-python-objects-to-json-using-__dict__/

 HTH

 Cheers,

 Graham

 http://www.linkedin.com/in/ghiggins




 -BEGIN PGP SIGNATURE-

 iEYEARECAAYFAksqcQMACgkQOsmLt1Nhivz83QCffD2BBEHw3wVQcyXNjIwCtJyP
 BOEAn38dYXvLCy9bwIIRO8w+bt1zKaitiQCVAgUBSypxA1nrWVZ7aXD1AQKELQQA
 1HNodv1eWKZTZ8f9Nsx7BwYWHlvdAb436uv2cznJ877RMOqsYMEJRJlPRIu+QMQf
 QTi0lqXXRwQdlc6VWTrLPDVsCx87z67F+K26Jtk1p1ojLYBlNa+ZS1AKX/SO5zVH
 deolsGX4Cx/9HSQikUYZOwTTTtNkNgwvFlye1xssJkc=
 =pzq8
 -END PGP SIGNATURE-

 --

 You received this message because you are subscribed to the Google Groups
 pylons-discuss group.
 To post to this group, send email to pylons-disc...@googlegroups.com.
 To unsubscribe from this group, send email to
 pylons-discuss+unsubscr...@googlegroups.compylons-discuss%2bunsubscr...@googlegroups.com
 .
 For more options, visit this group at
 http://groups.google.com/group/pylons-discuss?hl=en.




On that note - I was looking at this the other day and jsonpickle seems to
do an even more advanced version of jsonifying arbitrary objects
while retaining information

http://code.google.com/p/jsonpickle/
-- 
Brian O'Connor

--

You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-disc...@googlegroups.com.
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en.




Re: searching for some jsonify example or tutorial

2009-12-17 Thread Marius Gedminas
On Thu, Dec 17, 2009 at 05:57:23PM +, Graham Higgins wrote:
 Watch out for datetime objects, they can't be directly serialised by  
 simplejson's dumps().

I recall some fun times being had by all when the json dumper generated

  {title: something irrelevant, date: 2004-01-17}

which the browser nicely and silently evaluated to

  {title: something irrelevant, date: 1986}

Marius Gedminas
-- 
If the code and the comments disagree, then both are probably wrong.
-- Norm Schryer


signature.asc
Description: Digital signature


Re: searching for some jsonify example or tutorial

2009-12-17 Thread Graham Higgins
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1


On 17 Dec 2009, at 21:20, Marius Gedminas wrote:

 I recall some fun times being had by all when the json dumper  
 generated

  {title: something irrelevant, date: 2004-01-17}

 which the browser nicely and silently evaluated to

  {title: something irrelevant, date: 1986}



'Tis true, computers are even more pitilessly literal than children.

Cheers,

Graham

http://www.linkedin.com/in/ghiggins




-BEGIN PGP SIGNATURE-

iEYEARECAAYFAksqru4ACgkQOsmLt1Nhivx3PQCffs5SrNxkHHucH+EHzN0ei2tW
5PUAoNLja8uMGkSzwqohV2MU+FG0EzwniQCVAgUBSyqu7lnrWVZ7aXD1AQJP0gP+
Ivbr8YTw0CpO5rkQmywBWM3IALEMUPQzTcYbCy4ehNBZPbwQO+EOib1nEK3SU6bJ
OSSGp+jfrATgDmdPe/8ixf4ookvMWNCdSFS/y7UQULbnXKC/FIlSsUR9cgavdpEK
zmHREbpPLd+jOxoGhmDmwT337tCHVzthqTSTLb4iWCo=
=u//x
-END PGP SIGNATURE-

--

You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-disc...@googlegroups.com.
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en.




Re: searching for some jsonify example or tutorial

2009-12-17 Thread Krishnakant
On Thu, 2009-12-17 at 18:10 +0100, Jens Hoffrichter wrote:
  import simplejson
  json_obj = {'foo', 'bar'}
  return simplejson.dumps(json_obj)
  etc...
 
 Or even simpler (at least in 0.9.6.2 - not sure if this still stands
 with newer versions)
 
 from pylons.decoraters import jsonify
 
 class TestController(BaseController):
   @jsonify
   def testaction(self):
 return {'foo','bar':4711}

Do we need to  build the dict ourselves?

Or is there a method where in a certain return value is wrapped in a
javascript object and rendered?

happy hacking.
Krishnakant.


--

You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-disc...@googlegroups.com.
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en.




Re: jsonify validator

2009-09-24 Thread Wyatt Baldwin

On Sep 24, 10:09 am, Jonathan Vanasco jonat...@findmeon.com wrote:
  Jsonify is only ten lines or so.  You can copy it and add this
  feature.  It's too specific for Pylons though.  (What would the config
  variable be, 'jsonify_content_type'?)

 I disagree that its too specific.  It's a change that would make it
 easier for developers to test jsonify content in their browser,
 without having to use firefox with a special plugin -- which is what
 people currently have to do.  I think making things easier for a
 general audience of Pylons developers to code  test is good.

 I don't need this personally.  I use a library function to create
 structured dicts that are turned into JSON , and put this
 functionality in there.  But I do think it is of benefit to others.

 And yes, I was thinking of a change like this :

 -    pylons.response.headers['Content-Type'] = 'application/json'

 +    if 'pylons.jsonify_content_type' in pylons.config:
 +        pylons.response.headers['Content-Type'] = pylons.config
 ['pylons.jsonify_content_type']
 +    else:
 +        pylons.response.headers['Content-Type'] = 'application/json'

I'm -0 on this idea, but if it goes in, I'd prefer this
implementation:

 -pylons.response.headers['Content-Type'] = 'application/json'
 +   pylons.response.content_type = config.get('json_content_type',
'application/json')

I don't think the JSONView Firefox add-on qualifies as particularly
special, and the formatting  colorization is very nice. When I've
viewed JSON as text in the browser, it's been nearly unreadable
because it was all squished together  didn't wrap.
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-discuss@googlegroups.com
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en
-~--~~~~--~~--~--~---



Re: jsonify validator

2009-09-24 Thread Wyatt Baldwin

On Sep 24, 12:04 pm, Mike Orr sluggos...@gmail.com wrote:
 On Thu, Sep 24, 2009 at 11:38 AM, Wyatt Baldwin



 wyatt.lee.bald...@gmail.com wrote:

  On Sep 24, 10:09 am, Jonathan Vanasco jonat...@findmeon.com wrote:
   Jsonify is only ten lines or so.  You can copy it and add this
   feature.  It's too specific for Pylons though.  (What would the config
   variable be, 'jsonify_content_type'?)

  I disagree that its too specific.  It's a change that would make it
  easier for developers to test jsonify content in their browser,
  without having to use firefox with a special plugin -- which is what
  people currently have to do.  I think making things easier for a
  general audience of Pylons developers to code  test is good.

  I don't need this personally.  I use a library function to create
  structured dicts that are turned into JSON , and put this
  functionality in there.  But I do think it is of benefit to others.

  And yes, I was thinking of a change like this :

  -    pylons.response.headers['Content-Type'] = 'application/json'

  +    if 'pylons.jsonify_content_type' in pylons.config:
  +        pylons.response.headers['Content-Type'] = pylons.config
  ['pylons.jsonify_content_type']
  +    else:
  +        pylons.response.headers['Content-Type'] = 'application/json'

  I'm -0 on this idea, but if it goes in, I'd prefer this
  implementation:

   -    pylons.response.headers['Content-Type'] = 'application/json'
   +   pylons.response.content_type = config.get('json_content_type',
  'application/json')

  I don't think the JSONView Firefox add-on qualifies as particularly
  special, and the formatting  colorization is very nice. When I've
  viewed JSON as text in the browser, it's been nearly unreadable
  because it was all squished together  didn't wrap.

 response.content_type is translated to
 response.headers['content-type'] so they're the same (except that I
 forget the property exist).

Yes, it was a bikeshed-esque comment on my part. ;)

 I don't see how either way addresses
 wrapping, although I think simplejson has an argument to pretty-format
 which we could enable.

With pretty formatting, I'd be more like +0 on this.

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-discuss@googlegroups.com
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en
-~--~~~~--~~--~--~---



Re: jsonify validator

2009-09-23 Thread Hans Lellelid

Hi -

On Sep 23, 2009, at 1:36, Qiangning Hong hon...@gmail.com wrote:


 On Wed, Sep 23, 2009 at 1:17 PM, Mike Orr sluggos...@gmail.com  
 wrote:

 On Tue, Sep 22, 2009 at 8:06 PM, Jonathan Vanasco jonat...@findmeon.com 
  wrote:

 by default it sets response.content_type to application/json

 is there a way to override this?
 if not , could I request this in a future version of pylons ?

 though testing, i discovered that a lot of browsers will 'download'
 application/json files if you hit them directly -- ie, they won't
 render in the browser, they'll just save to disk.

 the same browsers will render text/javascript files fine.

 i've got some custom code that lets me dev stuff, but something  
 built
 into pylons would probably be useful for others.

 I don't quite grok decorators, but it looks like it would have to  
 be a
 separate function.  The signature is jsonify(func, *args, **kw), so
 there's no place to add a content-type argument.

 I'd like to make jsonify more smart:  use pylons.config['debug'] to
 decide to serve as application/json or text/javascript.  i.e.
 text/javascript only under debug environment for easier debugging,
 otherwise the more standard application/json.

 Also, is it proper to send JSON as text/javascript? Would this be
 widely enough used? What is the purpose, to display it in the  
 browser?

 As what http://www.iana.org/assignments/media-types/text/ describes,
 text/javascript is obsolete, use application/javascript instead for
 .js files.  And application/json is the standard media type for JSON
 data ( ref: http://www.ietf.org/rfc/rfc4627.txt )

Actually, for some browsers, json-rpc reqs simply will not work unless  
the content type is something more texty.  In these cases, it is not  
a question of making it easier to debug (if anything, I think you'd  
want it to be wrong for production).  We even found one case (ie6?)  
that required content type of text/html or it would puke. Sorry that I  
don't remember the offenders offhand; I'm sure IE6 is on that list,  
but I think maybe older FF and maybe older Safari too?

Hans

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-discuss@googlegroups.com
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en
-~--~~~~--~~--~--~---



Re: jsonify validator

2009-09-23 Thread Shailesh Kochhar

Mike Orr wrote:
 On Tue, Sep 22, 2009 at 8:06 PM, Jonathan Vanasco jonat...@findmeon.com 
 wrote:
 by default it sets response.content_type to application/json

 is there a way to override this?
 if not , could I request this in a future version of pylons ?

 though testing, i discovered that a lot of browsers will 'download'
 application/json files if you hit them directly -- ie, they won't
 render in the browser, they'll just save to disk.

 the same browsers will render text/javascript files fine.

 i've got some custom code that lets me dev stuff, but something built
 into pylons would probably be useful for others.
 
 I don't quite grok decorators, but it looks like it would have to be a
 separate function.  The signature is jsonify(func, *args, **kw), so
 there's no place to add a content-type argument.

You could use a method which binds the content type into the scope of the 
jsonfiy decorator. You effectively have a closure,


def jsonify(content_type='application/json'):
 def jsonify_decorator(fn, *args, **kwars):
 response.headers['content_type'] = content_type
 # implementation of jsonify goes in here
return simplejson.dumps(result)

 return jsonify_decorator

This could also be used to pass in the encoding function into jsonify, so users 
can specify an alternate to simplejson.

When using the decorator you'd specify

@jsonify(content_type='text/plain')
def foo_method():
   pass

or

@jsonfiy
def bar_method():
 pass


   - Shailesh

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-discuss@googlegroups.com
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en
-~--~~~~--~~--~--~---



Re: jsonify validator

2009-09-23 Thread Shailesh Kochhar

Qiangning Hong wrote:
 On Wed, Sep 23, 2009 at 1:17 PM, Mike Orr sluggos...@gmail.com wrote:
 On Tue, Sep 22, 2009 at 8:06 PM, Jonathan Vanasco jonat...@findmeon.com 
 wrote:
 by default it sets response.content_type to application/json

 is there a way to override this?
 if not , could I request this in a future version of pylons ?

 though testing, i discovered that a lot of browsers will 'download'
 application/json files if you hit them directly -- ie, they won't
 render in the browser, they'll just save to disk.

 the same browsers will render text/javascript files fine.

 i've got some custom code that lets me dev stuff, but something built
 into pylons would probably be useful for others.
 I don't quite grok decorators, but it looks like it would have to be a
 separate function.  The signature is jsonify(func, *args, **kw), so
 there's no place to add a content-type argument.
 
 I'd like to make jsonify more smart:  use pylons.config['debug'] to
 decide to serve as application/json or text/javascript.  i.e.
 text/javascript only under debug environment for easier debugging,
 otherwise the more standard application/json.

If you're debugging a url and want to see the response in a browser, firefox 
has 
a plugin called JSONView which renders JSON data nicely.

https://addons.mozilla.org/en-US/firefox/addon/10869/



--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-discuss@googlegroups.com
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en
-~--~~~~--~~--~--~---



Re: jsonify validator

2009-09-23 Thread Mike Orr

On Tue, Sep 22, 2009 at 10:36 PM, Qiangning Hong hon...@gmail.com wrote:

 On Wed, Sep 23, 2009 at 1:17 PM, Mike Orr sluggos...@gmail.com wrote:

 On Tue, Sep 22, 2009 at 8:06 PM, Jonathan Vanasco jonat...@findmeon.com 
 wrote:

 by default it sets response.content_type to application/json

 is there a way to override this?
 if not , could I request this in a future version of pylons ?

 though testing, i discovered that a lot of browsers will 'download'
 application/json files if you hit them directly -- ie, they won't
 render in the browser, they'll just save to disk.

 the same browsers will render text/javascript files fine.

 i've got some custom code that lets me dev stuff, but something built
 into pylons would probably be useful for others.

 I don't quite grok decorators, but it looks like it would have to be a
 separate function.  The signature is jsonify(func, *args, **kw), so
 there's no place to add a content-type argument.

 I'd like to make jsonify more smart:  use pylons.config['debug'] to
 decide to serve as application/json or text/javascript.  i.e.
 text/javascript only under debug environment for easier debugging,
 otherwise the more standard application/json.

This sounds too magical.  While we want to be flexible for debugging,
we don't want to make too many differences between the development and
production behavior.

It sounds like the current implementation is fine, and users can
override the content-type in their action.

Another possibility would be a magic keyword arg 'content_type',
although that doesn't seem necessary.  But I get confused between the
decorator's arguments and the wrapped function's arguments.  You'd
really want that to be a decorator argument, but I'm not sure if you
can do that with the 'decorator' decorator.  But at the same time,
only the action itself has the proper context to decide which
content-type is appropriate for the situation.  So that would argue
for the present practice of overriding the content-type in the action.

-- 
Mike Orr sluggos...@gmail.com

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-discuss@googlegroups.com
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en
-~--~~~~--~~--~--~---



Re: jsonify validator

2009-09-23 Thread Wyatt Baldwin

On Sep 23, 9:47 am, Shailesh Kochhar kochhar...@gmail.com wrote:

 [snip]

 If you're debugging a url and want to see the response in a browser, firefox 
 has
 a plugin called JSONView which renders JSON data nicely.

 https://addons.mozilla.org/en-US/firefox/addon/10869/

Nice (pro)tip. Thank you. I have a text editor (gedit) set as my
default JSON viewer, which works OK, but this is *much* nicer.
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-discuss@googlegroups.com
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en
-~--~~~~--~~--~--~---



Re: jsonify validator

2009-09-23 Thread Jonathan Vanasco

Thanks for the suggestions folks.

A lot of those things are magical too.

I'm really thinking/hoping along the lines of something like
OPTIONALLY putting a line in dev.ini that can be used to set the
content-type.

All the plugins, etc are neat... but honestly I don't want to install
plugins.  I just want the jason in my browser window so that I can hit
the JSON url's directly and make sure that they're returning correct
data , so i can thereafter blame my front-end team for anything not
working perfect.
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-discuss@googlegroups.com
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en
-~--~~~~--~~--~--~---



Re: jsonify validator

2009-09-23 Thread Mike Orr

On Wed, Sep 23, 2009 at 5:27 PM, Jonathan Vanasco jonat...@findmeon.com wrote:

 Thanks for the suggestions folks.

 A lot of those things are magical too.

 I'm really thinking/hoping along the lines of something like
 OPTIONALLY putting a line in dev.ini that can be used to set the
 content-type.

Jsonify is only ten lines or so.  You can copy it and add this
feature.  It's too specific for Pylons though.  (What would the config
variable be, 'jsonify_content_type'?)

-- 
Mike Orr sluggos...@gmail.com

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-discuss@googlegroups.com
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en
-~--~~~~--~~--~--~---



jsonify validator

2009-09-22 Thread Jonathan Vanasco

by default it sets response.content_type to application/json

is there a way to override this?
if not , could I request this in a future version of pylons ?

though testing, i discovered that a lot of browsers will 'download'
application/json files if you hit them directly -- ie, they won't
render in the browser, they'll just save to disk.

the same browsers will render text/javascript files fine.

i've got some custom code that lets me dev stuff, but something built
into pylons would probably be useful for others.
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-discuss@googlegroups.com
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en
-~--~~~~--~~--~--~---



Re: jsonify validator

2009-09-22 Thread Mike Orr

On Tue, Sep 22, 2009 at 8:06 PM, Jonathan Vanasco jonat...@findmeon.com wrote:

 by default it sets response.content_type to application/json

 is there a way to override this?
 if not , could I request this in a future version of pylons ?

 though testing, i discovered that a lot of browsers will 'download'
 application/json files if you hit them directly -- ie, they won't
 render in the browser, they'll just save to disk.

 the same browsers will render text/javascript files fine.

 i've got some custom code that lets me dev stuff, but something built
 into pylons would probably be useful for others.

I don't quite grok decorators, but it looks like it would have to be a
separate function.  The signature is jsonify(func, *args, **kw), so
there's no place to add a content-type argument.

Also, is it proper to send JSON as text/javascript? Would this be
widely enough used? What is the purpose, to display it in the browser?

-- 
Mike Orr sluggos...@gmail.com

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-discuss@googlegroups.com
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en
-~--~~~~--~~--~--~---



Re: jsonify validator

2009-09-22 Thread Qiangning Hong

On Wed, Sep 23, 2009 at 1:17 PM, Mike Orr sluggos...@gmail.com wrote:

 On Tue, Sep 22, 2009 at 8:06 PM, Jonathan Vanasco jonat...@findmeon.com 
 wrote:

 by default it sets response.content_type to application/json

 is there a way to override this?
 if not , could I request this in a future version of pylons ?

 though testing, i discovered that a lot of browsers will 'download'
 application/json files if you hit them directly -- ie, they won't
 render in the browser, they'll just save to disk.

 the same browsers will render text/javascript files fine.

 i've got some custom code that lets me dev stuff, but something built
 into pylons would probably be useful for others.

 I don't quite grok decorators, but it looks like it would have to be a
 separate function.  The signature is jsonify(func, *args, **kw), so
 there's no place to add a content-type argument.

I'd like to make jsonify more smart:  use pylons.config['debug'] to
decide to serve as application/json or text/javascript.  i.e.
text/javascript only under debug environment for easier debugging,
otherwise the more standard application/json.

 Also, is it proper to send JSON as text/javascript? Would this be
 widely enough used? What is the purpose, to display it in the browser?

As what http://www.iana.org/assignments/media-types/text/ describes,
text/javascript is obsolete, use application/javascript instead for
.js files.  And application/json is the standard media type for JSON
data ( ref: http://www.ietf.org/rfc/rfc4627.txt )

-- 
Qiangning Hong

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-discuss@googlegroups.com
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en
-~--~~~~--~~--~--~---



Re: jsonify validator

2009-09-22 Thread Wyatt Baldwin

On Sep 22, 8:06 pm, Jonathan Vanasco jonat...@findmeon.com wrote:
 by default it sets response.content_type to application/json

 is there a way to override this?

Looking at the way the decorator is written, you can just set
`response.content_type` in your controller action. This works because
the the decorator sets the (thread/request-local) response's content
type and *then* calls your controller action, so whatever you do to
the response in your action will override the decorator.

def my_action(self):
# ...
response.content_type = 'text/javascript'  # -- @jsonify already
set the content type header, so this will override it
return my_data_structure


 if not , could I request this in a future version of pylons ?

 though testing, i discovered that a lot of browsers will 'download'
 application/json files if you hit them directly -- ie, they won't
 render in the browser, they'll just save to disk.

 the same browsers will render text/javascript files fine.

 i've got some custom code that lets me dev stuff, but something built
 into pylons would probably be useful for others.
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-discuss@googlegroups.com
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en
-~--~~~~--~~--~--~---



Re: pylons jsonify and elixir

2009-05-08 Thread Isaac Csandl



On May 7, 5:09 pm, wesb5c w...@flbelt.com wrote:
 I ended up hacking pylons/decorators/__init__.py to modify jsonify to
 accept an optional parameter.  Now I can put @jsonify
 (model.encode_elixir_entry) in my controller.  I realize this will
 break compatibility with @jsonify being used today, so may not be
 appropriate for pylons, but it gets me moving forward for now...
 better suggestions still appreciated, as I said im learning.

 On May 7, 3:47 pm, wesb5c w...@flbelt.com wrote:



  First off I am brand new to python, pylons, elixir, sqlalchemy, etc so
  please go easy on me.  I am looking to turn some data from an Elixir
  model into json.  If I pull the data with:

  data = model.Item.query.all()

  and attempt to jsonify:

  simplejson.dumps(data)

  I get the TypeError: Item is not JSON serializable

  which I can work around with:

  def encode_elixir_entity(obj):
       if isinstance(obj, elixir.entity.Entity):
           return obj.to_dict()
       raise TypeError(repr(o) +  is not JSON serializable)

  then:

  simplejson.dumps(data,default=encode_elixir_entity)

  works as expected.  So, now with my limited python/pylons knowledge, I
  am ultimately trying to make use of the above in a pylons controller.

  Since the @jsonify decorator takes no arguments im assuming there is
  no way for me to specify the default=encode_elixir_entity option, is
  that correct?

  I think I can I hack the pylons.decorator code to meet my purposes,
  but I am trying to do things the right way.  Is there another
  alternative someone can suggest or point me in the right direction?

  Thanks in advance.

Hi,

The simplest thing is to return a list of dicts with only the
attributes you actually need to send over the network, otherwise
you're sending a lot of extra junk that your JavaScript has to
process. Here is a very simple example... (not that you'd want to
query.all() with a lot of items):

class MyController(BaseController):

@jsonify
def something(self, id=None):
items = Item.query.all()
result = []
for item in items:
result.append(dict(id=item.id, name=item.name,
whatever=item.whatever))
return result


HTH.
--Isaac

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-discuss@googlegroups.com
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en
-~--~~~~--~~--~--~---



pylons jsonify and elixir

2009-05-07 Thread wesb5c

First off I am brand new to python, pylons, elixir, sqlalchemy, etc so
please go easy on me.  I am looking to turn some data from an Elixir
model into json.  If I pull the data with:

data = model.Item.query.all()

and attempt to jsonify:

simplejson.dumps(data)

I get the TypeError: Item is not JSON serializable

which I can work around with:

def encode_elixir_entity(obj):
 if isinstance(obj, elixir.entity.Entity):
 return obj.to_dict()
 raise TypeError(repr(o) +  is not JSON serializable)

then:

simplejson.dumps(data,default=encode_elixir_entity)

works as expected.  So, now with my limited python/pylons knowledge, I
am ultimately trying to make use of the above in a pylons controller.

Since the @jsonify decorator takes no arguments im assuming there is
no way for me to specify the default=encode_elixir_entity option, is
that correct?

I think I can I hack the pylons.decorator code to meet my purposes,
but I am trying to do things the right way.  Is there another
alternative someone can suggest or point me in the right direction?

Thanks in advance.

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-discuss@googlegroups.com
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en
-~--~~~~--~~--~--~---



Re: pylons jsonify and elixir

2009-05-07 Thread wesb5c

I ended up hacking pylons/decorators/__init__.py to modify jsonify to
accept an optional parameter.  Now I can put @jsonify
(model.encode_elixir_entry) in my controller.  I realize this will
break compatibility with @jsonify being used today, so may not be
appropriate for pylons, but it gets me moving forward for now...
better suggestions still appreciated, as I said im learning.

On May 7, 3:47 pm, wesb5c w...@flbelt.com wrote:
 First off I am brand new to python, pylons, elixir, sqlalchemy, etc so
 please go easy on me.  I am looking to turn some data from an Elixir
 model into json.  If I pull the data with:

 data = model.Item.query.all()

 and attempt to jsonify:

 simplejson.dumps(data)

 I get the TypeError: Item is not JSON serializable

 which I can work around with:

 def encode_elixir_entity(obj):
      if isinstance(obj, elixir.entity.Entity):
          return obj.to_dict()
      raise TypeError(repr(o) +  is not JSON serializable)

 then:

 simplejson.dumps(data,default=encode_elixir_entity)

 works as expected.  So, now with my limited python/pylons knowledge, I
 am ultimately trying to make use of the above in a pylons controller.

 Since the @jsonify decorator takes no arguments im assuming there is
 no way for me to specify the default=encode_elixir_entity option, is
 that correct?

 I think I can I hack the pylons.decorator code to meet my purposes,
 but I am trying to do things the right way.  Is there another
 alternative someone can suggest or point me in the right direction?

 Thanks in advance.
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-discuss@googlegroups.com
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en
-~--~~~~--~~--~--~---



Re: jsonify Decimals and datetime.date

2009-05-01 Thread Marius Gedminas
On Thu, Apr 30, 2009 at 03:27:10PM -0700, Philip Jenvey wrote:
 Unfortunately our @jsonify just sucks in that you can't specify args  
 to dumps. Otherwise this would be even slightly easier than Domhnall's  
 example:
 
 # Don't even need a subclass
 def myenc(d):
  if if isinstance(d, decimal.Decimal):
  return float(str(d)
  # etc
  raise TypeError()
 
 simplejson.dumps(data, default=myenc)
 
 We need to fix jsonify -- what's a little problematic is it's built to  
 take no arguments, which is significantly different from a decorator  
 that's built to take arguments. We may be able to make the decorator  
 work both ways for 0.10 but it'd tricky/annoying.

It's tricky, but not too tricky, if you only accept keyword arguments in
to @jsonify():

def jsonify(fn=None, arg1=value1, arg2=value2):
if fn is None:
# this is @jsonify(arg1=...), so return a decorator
return functools.partial(jsonify, arg1=arg1, arg2=arg2)
@functools.wraps
def wrapped(*a, **kw):
# do stuff
retval = fn(*a, **kw)
return simplejson.dumps(retval, arg1=arg1, arg2=arg2)
return wrapped

Use it as

@jsonify
def fn(...):

@jsonify()
def fn(...):

@jsonify(arg1=42)
def fn(...):

but don't try

@jsonify(42)
def fn(...):

 Pylons 1.0 could definitely break it, however: @jsonify - @jsonify()

Marius Gedminas
-- 
There is nothing more practical than a good theory.
-- James Clerk Maxwell


signature.asc
Description: Digital signature


Re: jsonify Decimals and datetime.date

2009-05-01 Thread Uwe Feldtmann
I ended up moving the issue out of the jsonified method as Domhnall 
suggested which is working nicely and may have some extra benefits.

Many thanks to all.

Domhnall Walsh wrote:
 Well, maybe you should consider processing the tuple you plan to 
 return somehow to change the datetimes and Decimals to something more 
 palatable to @jsonify before returning it (via the decorator). If your 
 controller action is only returning JSON, then this shouldn't be a 
 problem?

 Domhnall.

 2009/4/30 Uwe Feldtmann u...@microshare.com.au 
 mailto:u...@microshare.com.au

 Thanks Domhnall.

 Not sure if it will help as I'm using the jsonify decorator on a
 method in the controller and it is what is failing when attempting
 to wrap the result set. 

 I managed to get the dates to work out by simply checking for data
 type and then assigning in the controller.

 Decimals on the other hand are not working for me. There doesn't
 appear to be a way to extract the value of a Decimal into another
 variable without copying the entire object. 

 Any suggestions or pointers greatly appreciated.

 Domhnall Walsh wrote:
 HI:

 This might give you a start:

 import simplejson

 class FancyEncoder(simplejson.JSONEncoder):
 
 Handle datetime objects.
 

 def default(self, obj):
 if isinstance(obj, datetime.datetime):
 return obj.isoformat()

 # Add more type-specific handlers here, for example for
 Decimals

 return simplejson.JSONEncoder.default(self, obj)

 json = simplejson.dumps(data_to_encode, cls=FancyEncoder)

 As you can see it replaces the datetimes with their ISO format
 representations as strings.

 Hope this helps,
 Domhnall.



 2009/4/30 Uwe Feldtmann u...@microshare.com.au
 mailto:u...@microshare.com.au

 Hi all.

 I've been struggling with a controller that gets a result set
 from a database and should simply return that result set as
 json data and I keep getting this traceback

 ||TypeError: Decimal(0.00) is not JSON serializable

 the data returned from the db is:
 (1492, 'BAKER', 'MR. AND MRS BAKER', Decimal(843.50),
 Decimal(5000.00), Decimal(0.00), datetime.date(1998, 8,
 24), datetime.date(1998, 8, 31))

 Is this an issue with @jsonify or am I missing something?


 I am using simplejson-2.0.8 and py2.5

 Thanks in advance.





 -- 
 Quidquid latine dictum sit, altum sonatur.
 (Whatever is said in Latin sounds profound)







 -- 
 Quidquid latine dictum sit, altum sonatur.
 (Whatever is said in Latin sounds profound)

 

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-discuss@googlegroups.com
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en
-~--~~~~--~~--~--~---



Re: jsonify Decimals and datetime.date

2009-05-01 Thread Philip Jenvey


On May 1, 2009, at 12:45 AM, Marius Gedminas wrote:

 It's tricky, but not too tricky, if you only accept keyword  
 arguments in
 to @jsonify():

Yep, but I definitely don't want to keep it working both ways going  
forward (1.0). It'd be a good stopgap.


def jsonify(fn=None, arg1=value1, arg2=value2):
if fn is None:
# this is @jsonify(arg1=...), so return a decorator
return functools.partial(jsonify, arg1=arg1, arg2=arg2)
@functools.wraps
def wrapped(*a, **kw):
# do stuff
retval = fn(*a, **kw)
return simplejson.dumps(retval, arg1=arg1, arg2=arg2)
return wrapped


functools.wraps here isn't enough because it doesn't maintain the  
method argspec -- we need the decorator module magic. Pylons needs the  
argspec maintained to know what routing args to pass along.

--
Philip Jenvey


--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-discuss@googlegroups.com
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en
-~--~~~~--~~--~--~---



Re: jsonify Decimals and datetime.date

2009-05-01 Thread Uwe (Peter) Feldtmann

I ended up moving the issue out of the jsonified method, as Domhnall
suggested, which is working nicely and may have some extra benefits.

Needless to say I'll be looking closely at jsonify as we move closer
to 1.0.

Many thanks to all.


On May 2, 9:10 am, Philip Jenvey pjen...@underboss.org wrote:
 On May 1, 2009, at 12:45 AM, Marius Gedminas wrote:



  It's tricky, but not too tricky, if you only accept keyword  
  arguments in
  to @jsonify():

 Yep, but I definitely don't want to keep it working both ways going  
 forward (1.0). It'd be a good stopgap.



     def jsonify(fn=None, arg1=value1, arg2=value2):
         if fn is None:
             # this is @jsonify(arg1=...), so return a decorator
             return functools.partial(jsonify, arg1=arg1, arg2=arg2)
        �...@functools.wraps
         def wrapped(*a, **kw):
             # do stuff
             retval = fn(*a, **kw)
             return simplejson.dumps(retval, arg1=arg1, arg2=arg2)
         return wrapped

 functools.wraps here isn't enough because it doesn't maintain the  
 method argspec -- we need the decorator module magic. Pylons needs the  
 argspec maintained to know what routing args to pass along.

 --
 Philip Jenvey
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-discuss@googlegroups.com
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en
-~--~~~~--~~--~--~---



Re: jsonify Decimals and datetime.date

2009-04-30 Thread Domhnall Walsh
HI:

This might give you a start:

import simplejson

class FancyEncoder(simplejson.JSONEncoder):

Handle datetime objects.


def default(self, obj):
if isinstance(obj, datetime.datetime):
return obj.isoformat()

# Add more type-specific handlers here, for example for Decimals

return simplejson.JSONEncoder.default(self, obj)

json = simplejson.dumps(data_to_encode, cls=FancyEncoder)

As you can see it replaces the datetimes with their ISO format
representations as strings.

Hope this helps,
Domhnall.



2009/4/30 Uwe Feldtmann u...@microshare.com.au

  Hi all.

 I've been struggling with a controller that gets a result set from a
 database and should simply return that result set as json data and I keep
 getting this traceback

 TypeError: Decimal(0.00) is not JSON serializable

 the data returned from the db is:
 (1492, 'BAKER', 'MR. AND MRS BAKER', Decimal(843.50), Decimal(5000.00),
 Decimal(0.00), datetime.date(1998, 8, 24), datetime.date(1998, 8, 31))

 Is this an issue with @jsonify or am I missing something?


 I am using simplejson-2.0.8 and py2.5

 Thanks in advance.

 



-- 
Quidquid latine dictum sit, altum sonatur.
(Whatever is said in Latin sounds profound)

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-discuss@googlegroups.com
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en
-~--~~~~--~~--~--~---



jsonify Decimals and datetime.date

2009-04-30 Thread Uwe Feldtmann
Hi all.

I've been struggling with a controller that gets a result set from a 
database and should simply return that result set as json data and I 
keep getting this traceback

||TypeError: Decimal(0.00) is not JSON serializable

the data returned from the db is:
(1492, 'BAKER', 'MR. AND MRS BAKER', Decimal(843.50), 
Decimal(5000.00), Decimal(0.00), datetime.date(1998, 8, 24), 
datetime.date(1998, 8, 31))

Is this an issue with @jsonify or am I missing something?


I am using simplejson-2.0.8 and py2.5

Thanks in advance.

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-discuss@googlegroups.com
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en
-~--~~~~--~~--~--~---



Re: jsonify Decimals and datetime.date

2009-04-30 Thread Uwe Feldtmann
Thanks Domhnall.

Not sure if it will help as I'm using the jsonify decorator on a method 
in the controller and it is what is failing when attempting to wrap the 
result set. 

I managed to get the dates to work out by simply checking for data type 
and then assigning in the controller.

Decimals on the other hand are not working for me. There doesn't appear 
to be a way to extract the value of a Decimal into another variable 
without copying the entire object. 

Any suggestions or pointers greatly appreciated.

Domhnall Walsh wrote:
 HI:

 This might give you a start:

 import simplejson

 class FancyEncoder(simplejson.JSONEncoder):
 
 Handle datetime objects.
 

 def default(self, obj):
 if isinstance(obj, datetime.datetime):
 return obj.isoformat()

 # Add more type-specific handlers here, for example for Decimals

 return simplejson.JSONEncoder.default(self, obj)

 json = simplejson.dumps(data_to_encode, cls=FancyEncoder)

 As you can see it replaces the datetimes with their ISO format 
 representations as strings.

 Hope this helps,
 Domhnall.



 2009/4/30 Uwe Feldtmann u...@microshare.com.au 
 mailto:u...@microshare.com.au

 Hi all.

 I've been struggling with a controller that gets a result set from
 a database and should simply return that result set as json data
 and I keep getting this traceback

 ||TypeError: Decimal(0.00) is not JSON serializable

 the data returned from the db is:
 (1492, 'BAKER', 'MR. AND MRS BAKER', Decimal(843.50),
 Decimal(5000.00), Decimal(0.00), datetime.date(1998, 8, 24),
 datetime.date(1998, 8, 31))

 Is this an issue with @jsonify or am I missing something?


 I am using simplejson-2.0.8 and py2.5

 Thanks in advance.





 -- 
 Quidquid latine dictum sit, altum sonatur.
 (Whatever is said in Latin sounds profound)

 

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-discuss@googlegroups.com
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en
-~--~~~~--~~--~--~---



Re: jsonify Decimals and datetime.date

2009-04-30 Thread Domhnall Walsh
Well, maybe you should consider processing the tuple you plan to return
somehow to change the datetimes and Decimals to something more palatable to
@jsonify before returning it (via the decorator). If your controller action
is only returning JSON, then this shouldn't be a problem?

Domhnall.

2009/4/30 Uwe Feldtmann u...@microshare.com.au

  Thanks Domhnall.

 Not sure if it will help as I'm using the jsonify decorator on a method in
 the controller and it is what is failing when attempting to wrap the result
 set.

 I managed to get the dates to work out by simply checking for data type and
 then assigning in the controller.

 Decimals on the other hand are not working for me. There doesn't appear to
 be a way to extract the value of a Decimal into another variable without
 copying the entire object.

 Any suggestions or pointers greatly appreciated.

 Domhnall Walsh wrote:

 HI:

 This might give you a start:

 import simplejson

 class FancyEncoder(simplejson.JSONEncoder):
 
 Handle datetime objects.
 

 def default(self, obj):
 if isinstance(obj, datetime.datetime):
 return obj.isoformat()

 # Add more type-specific handlers here, for example for Decimals

 return simplejson.JSONEncoder.default(self, obj)

 json = simplejson.dumps(data_to_encode, cls=FancyEncoder)

 As you can see it replaces the datetimes with their ISO format
 representations as strings.

 Hope this helps,
 Domhnall.



 2009/4/30 Uwe Feldtmann u...@microshare.com.au

 Hi all.

 I've been struggling with a controller that gets a result set from a
 database and should simply return that result set as json data and I keep
 getting this traceback

 TypeError: Decimal(0.00) is not JSON serializable

 the data returned from the db is:
 (1492, 'BAKER', 'MR. AND MRS BAKER', Decimal(843.50),
 Decimal(5000.00), Decimal(0.00), datetime.date(1998, 8, 24),
 datetime.date(1998, 8, 31))

 Is this an issue with @jsonify or am I missing something?


 I am using simplejson-2.0.8 and py2.5

 Thanks in advance.





 --
 Quidquid latine dictum sit, altum sonatur.
 (Whatever is said in Latin sounds profound)



 



-- 
Quidquid latine dictum sit, altum sonatur.
(Whatever is said in Latin sounds profound)

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-discuss@googlegroups.com
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en
-~--~~~~--~~--~--~---



Re: jsonify Decimals and datetime.date

2009-04-30 Thread Philip Jenvey


On Apr 30, 2009, at 5:13 AM, Uwe Feldtmann wrote:

 Thanks Domhnall.

 Not sure if it will help as I'm using the jsonify decorator on a  
 method in the controller and it is what is failing when attempting  
 to wrap the result set.


Unfortunately our @jsonify just sucks in that you can't specify args  
to dumps. Otherwise this would be even slightly easier than Domhnall's  
example:

# Don't even need a subclass
def myenc(d):
 if if isinstance(d, decimal.Decimal):
 return float(str(d)
 # etc
 raise TypeError()

simplejson.dumps(data, default=myenc)

We need to fix jsonify -- what's a little problematic is it's built to  
take no arguments, which is significantly different from a decorator  
that's built to take arguments. We may be able to make the decorator  
work both ways for 0.10 but it'd tricky/annoying.

Pylons 1.0 could definitely break it, however: @jsonify - @jsonify()

--
Philip Jenvey

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-discuss@googlegroups.com
To unsubscribe from this group, send email to 
pylons-discuss+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en
-~--~~~~--~~--~--~---



Re: How to filter the @jsonify warning

2008-10-18 Thread Christoph Haas
On Samstag, 18. Oktober 2008, Philip Jenvey wrote:
 On Oct 17, 2008, at 2:01 PM, Christoph Haas wrote:
  I tried to use:
 
  import warnings
  warnings.filterwarnings('ignore', 'JSON responses with Array
  envelopes')
 
  in several places like lib/base.py or config/environment.py but the
  warning
  always still appeared. Where would I put that code to be successful? I
  know it's close to trivial to just copy the @jsonify decorator
  function
  and removing that line. I'm more interested in how to suppress the
  warnings.

 I'd recommend environment.py for the most appropriate place for this.

 It's not working because the message argument should be an RE match,

 whereas you're assuming it's an RE search. Try:
  warnings.filterwarnings('ignore', '.*JSON responses with Array
  envelopes.*')

Thanks for the hint. Unfortunately the warnings still appears at every 
request.

 Christoph
-- 
A guess is just a guess until you turn it into a pie chart.
Then it's an analysis. (Scott Adams)


signature.asc
Description: This is a digitally signed message part.


Re: How to filter the @jsonify warning

2008-10-18 Thread Ben Bangert

On Oct 17, 2008, at 2:01 PM, Christoph Haas wrote:


Unfortunately I wasn't very lucky. I tried to use:

import warnings
	warnings.filterwarnings('ignore', 'JSON responses with Array  
envelopes')


You need to specify the warning itself that is being thrown, rather  
than the message of it. Ie:

warnings.filterwarnings('ignore', module='pylons.decorators')

As the entire message itself is a bit long.

Or if since it compiles them to be regexp, maybe:
warnings.filterwarnings('ignore', 'JSON responses with.*')

would do the trick.

Cheers,
Ben

smime.p7s
Description: S/MIME cryptographic signature


How to filter the @jsonify warning

2008-10-17 Thread Christoph Haas
Fellow earthicans,

I'm trying the ExtJS Javascript framework in a workflow-style Pylons 
project. And that means passing a lot of JSON data around. There is a 
certain cross-site vulnerability problem when sending JSON arrays (versus 
JSON dictionaries or scalars). But without working around it on the ExtJS 
side I will have to use arrays. So I tried to be smart and ignore the 
warning from the @jsonify decorator (which is flooding my logs):

22:53:51,387 WARNI [pylons.decorators] JSON responses with Array 
envelopes
are susceptible to cross-site data leak attacks, see
http://pylonshq.com/warnings/JSONArray

Unfortunately I wasn't very lucky. I tried to use:

import warnings
warnings.filterwarnings('ignore', 'JSON responses with Array envelopes')

in several places like lib/base.py or config/environment.py but the warning 
always still appeared. Where would I put that code to be successful? I 
know it's close to trivial to just copy the @jsonify decorator function 
and removing that line. I'm more interested in how to suppress the 
warnings.

Any ideas?

Cheers
 Christoph
-- 
A guess is just a guess until you turn it into a pie chart.
Then it's an analysis. (Scott Adams)


signature.asc
Description: This is a digitally signed message part.


Jsonify like TG

2007-10-02 Thread Philip Cooper

OK,
I wrote up this page http://www.openvest.com/trac/wiki/PylonsJsonify
becuase in moving code from Turbogears to Pylons, I really wanted some 
ready made json functionality.

Just thru ti together and haven't given it a through road test yet.

In short: check the link.  It only takes a half dozen lines of code and 
any pylons controller method can be jsonified, and just by adding a  
json='OK') kwarg to render_response ... no decorator required.

After the fact, I saw Kendall Clarks posting about NOT using the query 
string to invoke it.  Sorry, practicality overcame me.

Any other red flags out there as to why this won't work.  Seems too good 
to pass up.  To be honest, that feature in Turbogears is the only thing 
that has kept it of interest to me.  Now it Pylons all the way!

Write once, use twice.  I love it.  Anyway, Kendalls remarks were about 
using something like #json -- using things after the  ? throws it into 
the query string and off of uri.  Anyway the code changes 
render_response matching Ben Banget's comments on the thread 
http://groups.google.com/group/pylons-discuss/browse_thread/thread/61d9e672032f9156/403f8d380d1beb8d?lnk=gstq=jsonrnum=1#403f8d380d1beb8d
and can look at headers to decide what to do.

Any other thoughts?

--
Phil Cooper

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-discuss@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en
-~--~~~~--~~--~--~---



Re: Jsonify like TG

2007-10-02 Thread Christoph Haas

On Tue, Oct 02, 2007 at 01:08:34AM -0600, Philip Cooper wrote:
 I wrote up this page http://www.openvest.com/trac/wiki/PylonsJsonify

Quoting:

* The reason is that the return from a controller method is a call to
* render_response.

This isn't quite true. You could send a Response() object containing
plain text. And with the current Pylons version 0.9.6 you are free to
return just a string object anyway. Perhaps that makes jsonification
simpler? Or do I get your complaint wrong?

Cheers
 Christoph


--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-discuss@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en
-~--~~~~--~~--~--~---



Re: @jsonify - 'str' object has no attribute 'request'

2007-01-21 Thread Chris Leonello

Hi Alagu,

I'm *very* new to Pylons, but it appears they have greatly simplified
JSON.  Just use like so:

@jsonify
def jsontest(self):
person = {}
person['name'] = Bob
person['address'] = 123 Elm St
return person


Alagu Madhu wrote:
 Hi All,


 I'm using

 windows 200
 python 2.5
 pylons-0.9.4.1
 simplejson-1.5



 The code is here


 from kk.lib.base import *
 from pylons.decorators import jsonify

 @jsonify
 def index(self):
 c.name = Bob
 c.house = 123 Elm St
 return c._local.request




 Error Traceback

 clear this
 clear this
 Module ?:2 in index
 Module pylons.decorators:18 in jsonify
   response = pylons.Response()
 response.headers['Content-Type'] = 'text/javascript'
 response.content.append(json.dumps(func(*args, **kwargs)))
 return response
 jsonify = decorator(jsonify)
 response.content.append(json.dumps(func(*args, **kwargs)))
 Module kk.controllers.rio:70 in index1
   c.name = Bob
 c.house = 123 Elm St
 return c._local.request  return c._local.request
 type 'exceptions.AttributeError': 'str' object has no attribute
 'request'


 File 'string', line 2 in index
 File
 'c:\\python25\\lib\\site-packages\\pylons-0.9.4.1-py2.5.egg\\pylons\\decorators\\__init__.py',
 line 18 in jsonify
   response.content.append(json.dumps(func(*args, **kwargs)))
 File 'G:\\pylons\\kk\\kk\\controllers\\rio.py', line 70 in index1
   return c._local.request
 AttributeError: 'str' object has no attribute 'request'
 
 
 
 
 Thanks
 
 
 Madhu Alagu


--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-discuss@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en
-~--~~~~--~~--~--~---



Re: @jsonify - 'str' object has no attribute 'request'

2007-01-21 Thread Alagu Madhu


Thanks you,It's working fine..


--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-discuss@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en
-~--~~~~--~~--~--~---



@jsonify - 'str' object has no attribute 'request'

2007-01-20 Thread Alagu Madhu

Hi All,


I'm using

windows 200
python 2.5
pylons-0.9.4.1
simplejson-1.5



The code is here


from kk.lib.base import *
from pylons.decorators import jsonify

@jsonify
def index(self):
c.name = Bob
c.house = 123 Elm St
return c._local.request




Error Traceback

clear this
clear this
Module ?:2 in index
Module pylons.decorators:18 in jsonify
  response = pylons.Response()
response.headers['Content-Type'] = 'text/javascript'
response.content.append(json.dumps(func(*args, **kwargs)))
return response
jsonify = decorator(jsonify)
response.content.append(json.dumps(func(*args, **kwargs)))
Module kk.controllers.rio:70 in index1
  c.name = Bob
c.house = 123 Elm St
return c._local.request  return c._local.request
type 'exceptions.AttributeError': 'str' object has no attribute
'request'


File 'string', line 2 in index
File
'c:\\python25\\lib\\site-packages\\pylons-0.9.4.1-py2.5.egg\\pylons\\decorators\\__init__.py',
line 18 in jsonify
  response.content.append(json.dumps(func(*args, **kwargs)))
File 'G:\\pylons\\kk\\kk\\controllers\\rio.py', line 70 in index1
  return c._local.request
AttributeError: 'str' object has no attribute 'request'




Thanks


Madhu Alagu


--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-discuss@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en
-~--~~~~--~~--~--~---



Re: Paramatizing @jsonify

2006-12-15 Thread Philip Jenvey


On Dec 14, 2006, at 3:25 PM, ram wrote:


 Sorry, the bottom of the message was somehow cut off.

 The decorator doesn't work -- in fact using it on a controller method
 makes the controller dispatch unable to see the action, and attempts
 to reference a URL that should call that controller give
 UnImplemented errors, but both the module where this decorator is
 defined and the controller module itself seem to import fine.

 Can anybody see where I've gone astray?


This kind of decorator must be invoked:

@jsonify(something) will work
@jsonify() would work too
@jsonify isn't what you want

When you specify a param you're actually calling jsonify(), which  
returns the decorator that wraps your function

Without it, your jsonify wraps your function directly. The serializer  
argument ends up being your function and havoc ensues. I'm not sure  
why exactly that causes a 404 but it's not too surprising.

This wasn't at all apparent to me at first either. How evil


 Thanks much,
 Rick

 On Dec 14, 5:59 pm, ram [EMAIL PROTECTED] wrote:
 I'd like to modify the @jsonify decorator to be able to:

a) override the default simplejson serializer with a replacement
 JSONencoder subclass that I'll set as a module-level variable.

b) provide the decorator with an argument for one-time overrides

 so I'm trying this:

 jsonify_serializer = None# this is the module-level variable

 def jsonify(serializer=None):
 def wrapper(func, *args, **kwargs):
 response = pylons.Response()
 response.headers['Content-Type'] = 'text/javascript'
 if serializer or jsonify_serializer:
 response.content.append(json.dumps(func(*args, **kwargs),
 cls=serializer or jsonify_serializer))
 else:
 response.content.append(json.dumps(func(*args,  
 **kwargs)))
 return response
 return decorator(wrapper)


--
Philip Jenvey


--~--~-~--~~~---~--~~
 You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-discuss@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en
-~--~~~~--~~--~--~---



Re: Paramatizing @jsonify

2006-12-14 Thread ram

Sorry, the bottom of the message was somehow cut off.

The decorator doesn't work -- in fact using it on a controller method
makes the controller dispatch unable to see the action, and attempts
to reference a URL that should call that controller give
UnImplemented errors, but both the module where this decorator is
defined and the controller module itself seem to import fine.

Can anybody see where I've gone astray?

Thanks much,
Rick

On Dec 14, 5:59 pm, ram [EMAIL PROTECTED] wrote:
 I'd like to modify the @jsonify decorator to be able to:

a) override the default simplejson serializer with a replacement
 JSONencoder subclass that I'll set as a module-level variable.

b) provide the decorator with an argument for one-time overrides

 so I'm trying this:

 jsonify_serializer = None# this is the module-level variable

 def jsonify(serializer=None):
 def wrapper(func, *args, **kwargs):
 response = pylons.Response()
 response.headers['Content-Type'] = 'text/javascript'
 if serializer or jsonify_serializer:
 response.content.append(json.dumps(func(*args, **kwargs),
 cls=serializer or jsonify_serializer))
 else:
 response.content.append(json.dumps(func(*args, **kwargs)))
 return response
 return decorator(wrapper)


--~--~-~--~~~---~--~~
 You received this message because you are subscribed to the Google Groups 
pylons-discuss group.
To post to this group, send email to pylons-discuss@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en
-~--~~~~--~~--~--~---