jsocol / django-jsonview Goto Github PK
View Code? Open in Web Editor NEWReturn Python objects, always get JSON.
License: Other
Return Python objects, always get JSON.
License: Other
Flask is full of good ideas.
Is there any way we could get a stacktrack in there if DEBUG=True ? I really like the fact it handles it as expected, but sometimes the single line is ambiguous as to what actually caused the error.
Thanks
In the Exception
handler, send Django's got_request_exception
signal. For the sender
argument, I guess just use django.core.handlers.base.BaseHandler
.
got_request_exception.send(sender=BaseHandler, request=request)
This is along with logging, not instead.
We use a lot of management commands in cronjobs and such, some of which run quite often. So as a rule we don't log unless it is actually valuable information, or else our logs get swamped.
But this module prints a "Using json JSON module." line on every initialization ๐
I'm not quite sure why printing this line is necessary; not many modules we've used repeat back their settings on every app invocation.
If you must have this visible then maybe it should be put behind the DEBUG flag?
I forked and added a small patch, aptwebapps@447f240 , to enable custom encoders. I'd send a pull request, but it needs polishing (tests, Readme updates). Before I do that, are you interested in the idea?
/Users/peterbe/virtualenvs/redunter/lib/python2.7/site-packages/django_jsonview-0.4.3-py2.7.egg/jsonview/decorators.py:14: RemovedInDjango19Warning: django.utils.importlib will be removed in Django 1.9.
from django.utils.importlib import import_module
Anywhere django.core.handlers.base.BaseHandler
would log a warning
, and @json_view
also handles that exception type, log the same warning.
A simple decorator that would do something like this:
# POST {"foo": "bar"}
@json_request
def my_view(request):
assert request.META['CONTENT_TYPE'] == 'application/json'
assert request.data == {'foo': 'bar'}
Not 100% sure how to handle other content-types yet. That's probably got to go into some sort of setting. Do you always want to assume JSON (e.g. try to parse it regardless of the content-type header) or respect the header? If it does respect the header, does it make sense to assign request.data = request.POST
if content-type is set to application/x-www-form-urlencoded
? What's the right error-handling if you can't parse JSON (or form-encoded)? 400
?
Can not work with django 3.0:cannot import name 'six' from 'django.utils'
django.utils.six module was removed
Using @json_view in the following function:
@json_view
@login_required
def user_verification(request):
logger.info(__name__ + ', user_verification (AJAX)')
if not request.POST.has_key('user_list'):
print (__name__ + ', user_verification, raising BadRequest.')
raise BadRequest("'user_list' not found as a POST parameter.")
return dict(user_list='user_list')
I get the following exception when returning the dict():
Traceback (most recent call last):
File "/usr/lib/python2.7/wsgiref/handlers.py", line 86, in run
self.finish_response()
File "/usr/lib/python2.7/wsgiref/handlers.py", line 127, in finish_response
self.write(data)
File "/usr/lib/python2.7/wsgiref/handlers.py", line 210, in write
DEBUG (0.000) SELECT `auth_user`.`id`, `auth_user`.`password`, `auth_user`.`last_login`, `auth_user`.`is_superuser`, `auth_user`.`username`, `auth_user`.`first_name`, `auth_user`.`last_name`, `auth_user`.`email`, `auth_user`.`is_staff`, `auth_user`.`is_active`, `auth_user`.`date_joined`, `accounts_userprofile`.`user_ptr_id`, `accounts_userprofile`.`organization`, `accounts_userprofile`.`country`, `accounts_userprofile`.`is_verified` FROM `accounts_userprofile` INNER JOIN `auth_user` ON (`accounts_userprofile`.`user_ptr_id` = `auth_user`.`id`) WHERE `accounts_userprofile`.`is_verified` = 0 ; args=(False,)
self.send_headers()
File "/usr/lib/python2.7/wsgiref/handlers.py", line 268, in send_headers
self.send_preamble()
File "/usr/lib/python2.7/wsgiref/handlers.py", line 192, in send_preamble
'Date: %s\r\n' % format_date_time(time.time())
File "/usr/lib/python2.7/socket.py", line 324, in write
DEBUG (0.000) SAVEPOINT s140402375128832_x1; args=()
self.flush()
File "/usr/lib/python2.7/socket.py", line 303, in flush
self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe
Exception happened during processing of request from ('127.0.0.1', 46714)
Traceback (most recent call last):
File "/usr/lib/python2.7/SocketServer.py", line 593, in process_request_thread
DEBUG (0.001) SELECT (1) AS `a` FROM `django_session` WHERE `django_session`.`session_key` = 'm88fndnzgwjwaqwvhwaj1umks20skgwo' LIMIT 1; args=('m88fndnzgwjwaqwvhwaj1umks20skgwo',)
self.finish_request(request, client_address)
File "/usr/lib/python2.7/SocketServer.py", line 334, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/home/rtubio/repositories/satnet-release-1/WebServices/__v_env/local/lib/python2.7/site-packages/django/core/servers/basehttp.py", line 150, in __init__
super(WSGIRequestHandler, self).__init__(*args, **kwargs)
File "/usr/lib/python2.7/SocketServer.py", line 651, in __init__
self.finish()
File "/usr/lib/python2.7/SocketServer.py", line 704, in finish
self.wfile.flush()
File "/usr/lib/python2.7/socket.py", line 303, in flush
self._sock.sendall(view[write_offset:write_offset+buffer_size])
Am I doing anything wrong?
Does the new JsonResponse basically replace django-jsonview? https://docs.djangoproject.com/en/1.7/ref/request-response/#django.http.JsonResponse
Something like
JSONVIEW = {
'serializer_options': {
'cls': None,
},
}
To get more room to grow (e.g. deserializer_options
, c.f. #28)
How can I return model instance using jsonview ?
ujson.dumps
, for example, doesn't support the cls=
serializer arguments. Given the huge speed with some of these C json libraries, the serializers have to be optional.
Given a @json_request
(c.f. #28) it makes sense to move json_view
to json_response
django.utils.six
is gone in 3.0. It's still present in 2.2 but we should remove the dependency. We can consider this along with ESRs and Python2 support
The json_view()
decorator catches all exceptions which means that with ATOMIC_REQUESTS = True
exceptions do not cause a rollback.
It's easy to work around by explicitly putting @transaction.atomic
decorator on a view below @json_view
but it's a gotcha and also easy to forget. I think that json_view()
should be doing the same thing Django does to get the rollback behavior of normal views (I'm not sure if it's just this decorator or a bit more magic). Or at least document the current behavior in the README.
Handle the case where the first argument isn't a request!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.