Coder Social home page Coder Social logo

django-tastypie-mongoengine's Introduction

django-tastypie-mongoengine's People

Contributors

aljana avatar aparajita avatar climax777 avatar danstovall avatar jeffersonheard avatar leo-naeka avatar matevzmihalic avatar mitar avatar yunmanger1 avatar zupan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-tastypie-mongoengine's Issues

Problem using PATCH

There is a problem when using PATCH if there is related field that has full=True parameter.

change licence to BSD

I'm no software licencing expert however I noticed that this project uses the AGPLv3 licence.

This summary of the AGPLv3 licence says you can't

  • Write BSD or closed source software on top of it: AGPLv3 is designed to keep the code always free, so you can't use nor import AGPLv3 code into a closed source project.

In layman's terms that means that people can't use django-tastypie-mongoengine if they don't share the source of their Django project. I can't use this project due to that restriction, if that's what you intended that's fine (say so and close this issue), if you didn't intend that please change the licence to a BSD or similar (such as Django itself uses) so that restriction is lifted.

Exact synatx of Datetime field in POST

I am trying to send date_time from jQuery post to our server we are using mongoDB as backend and using django_tastypie_mongoengine for posting so far i have tried putting date="2010-11-10T03:07:43" and also date="2013-05-21T02:17:55.544000" in my jQuery but it is failing everytime.

I want to know the exact syntax of sending date

Problem with PUT and _id

Hello,

I don't know if the issue is related to mongoengine or tastypie, but I have a problem with a PUT.

I use angularjs and RESTangular to create this PUT, but I reproduced by writing my PUT request manually.

When I try to save my user (https://github.com/Seraf/LISA/blob/angularjs/lisa/server/web/weblisa/api/accounts.py#L22), it throw me a :

{"error_message": "Could not save document (Mod on _id not allowed)", "traceback": "Traceback (most recent call last):
File \"/home/seraf/.virtualenvs/LISA/local/lib/python2.7/site-packages/tastypie/resources.py\", line 201, in wrapper
response = callback(request, *args, **kwargs)

File \"/home/seraf/.virtualenvs/LISA/local/lib/python2.7/site-packages/tastypie/resources.py\", line 441, in dispatch_detail
return self.dispatch('detail', request, **kwargs)

File \"/home/seraf/.virtualenvs/LISA/local/lib/python2.7/site-packages/tastypie_mongoengine/resources.py\", line 390, in dispatch
return self._wrap_request(request, lambda: super(MongoEngineResource, self).dispatch(request_type, request, **kwargs))

File \"/home/seraf/.virtualenvs/LISA/local/lib/python2.7/site-packages/tastypie_mongoengine/resources.py\", line 360, in _wrap_request
return fun()

File \"/home/seraf/.virtualenvs/LISA/local/lib/python2.7/site-packages/tastypie_mongoengine/resources.py\", line 390, in <lambda>
return self._wrap_request(request, lambda: super(MongoEngineResource, self).dispatch(request_type, request, **kwargs))

File \"/home/seraf/.virtualenvs/LISA/local/lib/python2.7/site-packages/tastypie/resources.py\", line 464, in dispatch\n    response = method(request, **kwargs)\n\n  File \"/home/seraf/.virtualenvs/LISA/local/lib/python2.7/site-packages/tastypie/resources.py\", line 1431, in put_detail\n    updated_bundle = self.obj_update(bundle=bundle, **self.remove_api_resource_names(kwargs))

File \"/home/seraf/.virtualenvs/LISA/local/lib/python2.7/site-packages/tastypie_mongoengine/resources.py\", line 565, in obj_update
return self.save(bundle, skip_errors=skip_errors)

File \"/home/seraf/.virtualenvs/LISA/local/lib/python2.7/site-packages/tastypie_mongoengine/resources.py\", line 582, in save
return super(MongoEngineResource, self).save(bundle, skip_errors)

File \"/home/seraf/.virtualenvs/LISA/local/lib/python2.7/site-packages/tastypie/resources.py\", line 2253, in save\n    bundle.obj.save()

File \"/home/seraf/Sandbox/LISA/lisa/server/web/interface/models.py\", line 29, in save
return super(LisaUser, self).save(*args, **kwargs)

File \"/home/seraf/.virtualenvs/LISA/local/lib/python2.7/site-packages/mongoengine/document.py\", line 296, in save
raise OperationError(message % unicode(err))

OperationError: Could not save document (Mod on _id not allowed)\n"}

My user is a custom class : https://github.com/Seraf/LISA/blob/angularjs/lisa/server/web/interface/models.py#L15

So, digging a little bit to understand why it doesn't work, I tried with my plugin resource :
https://github.com/Seraf/LISA/blob/angularjs/lisa/server/web/manageplugins/api.py#L14

And it worked.

So I tried to see why it detected an _id field as changed on my user resource, and not my plugin.

By adding some debug in :
Mongoengine/document.py (line 242)

object_id = doc['_id']
updates, removals = self._delta()
print "====UPDATES/REMOVALS===="
print updates
print removals
# Need to add shard key to query, or you get an error
select_dict = {'_id': object_id}

Here is the ouput with a PUT of my user
User :

2014-08-21 09:51:50+0200 [HTTPChannel,52,127.0.0.1] ====UPDATES/REMOVALS====
2014-08-21 09:51:50+0200 [HTTPChannel,52,127.0.0.1] {'api_key_created': datetime.datetime(2014, 8, 18, 9, 31, 43, 944000, tzinfo=<DstTzInfo 'Europe/Paris' CEST+2:00:00 DST>), '_id': ObjectId('53f1abdfa9a7bf5358f3d046'), 'last_login': datetime.datetime(2014, 8, 21, 7, 35, 30, 736000, tzinfo=<DstTzInfo 'Europe/Paris' CEST+2:00:00 DST>), 'date_joined': datetime.datetime(2014, 8, 18, 7, 31, 43, 898000, tzinfo=<DstTzInfo 'Europe/Paris' CEST+2:00:00 DST>)}
2014-08-21 09:51:50+0200 [HTTPChannel,52,127.0.0.1] {}
2014-08-21 09:51:50+0200 [-] "127.0.0.1" - - [21/Aug/2014:07:51:50 +0000] "PUT /backend/api/v1/user/53f1abdfa9a7bf5358f3d046/?format=json HTTP/1.1" 500 2467 "http://lisa:8000/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/36.0.1985.125 Chrome/36.0.1985.125 Safari/537.36

Here is a put with my plugin :
Plugin :

2014-08-21 11:03:38+0200 [HTTPChannel,83,127.0.0.1] ====UPDATES/REMOVALS====
2014-08-21 11:03:38+0200 [HTTPChannel,83,127.0.0.1] {'description.0.description': u'Ce plugin est celui par d\xe9faut int\xe9grant les interactions basiques avec LISA', 'description.1.lang': u'en', 'description.0.lang': u'fr', 'description.1.description': u'This plugin is shipped by default, managing all basic interactions with LISA'}
2014-08-21 11:03:38+0200 [HTTPChannel,83,127.0.0.1] {'id': 1}
2014-08-21 11:03:38+0200 [-] "127.0.0.1" - - [21/Aug/2014:09:03:38 +0000] "PUT /backend/api/v1/plugin/53dba55aa9a7bf3c9da33373/?format=json HTTP/1.1" 204 - "http://lisa:8000/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/36.0.1985.125 Chrome/36.0.1985.125 Safari/537.36"

Both sent the id field the same way, and I received the request.body.id identical ...
So I don't understand the difference between them ... It appears there's a problem with the hydrate (or dehydrate) functions, but don't know why ...

If you have an idea ...

Thanks a lot !

Problem in django_tastypie-0.9.15-py2.7

I have the following versions installed:
django_tastypie-0.9.15-py2.7
mongoengine-0.8.0RC4-py2.7
pymongo-2.5.1-py2.7
python 2.7.4
Red Hat 4.4.6-4

When I any HTTP GET, I get the following error message:
{"error_message": "'QuerySet' object has no attribute '_reset_already_indexed'", "traceback": "Traceback (most recent call last):\n\n File "/usr/local/lib/python2.7/site-packages/tastypie/resources.py", line 217, in wrapper\n response = callback(request, _args, *_kwargs)\n\n File "/usr/local/lib/python2.7/site-packages/tastypie/resources.py", line 459, in dispatch_list\n return self.dispatch('list', request, **kwargs)\n\n File "/usr/local/lib/python2.7/site-packages/tastypie_mongoengine/resources.py", line 373, in dispatch\n return super(MongoEngineResource, self).dispatch(request_type, request, *_kwargs)\n\n File "/usr/local/lib/python2.7/site-packages/tastypie/resources.py", line 491, in dispatch\n response = method(request, *_kwargs)\n\n File "/usr/local/lib/python2.7/site-packages/tastypie/resources.py", line 1299, in get_list\n objects = self.obj_get_list(bundle=base_bundle, **self.remove_api_resource_names(kwargs))\n\n File "/usr/local/lib/python2.7/site-packages/tastypie/resources.py", line 2112, in obj_get_list\n objects = self.apply_filters(bundle.request, applicable_filters)\n\n File "/usr/local/lib/python2.7/site-packages/tastypie/resources.py", line 2084, in apply_filters\n return self.get_object_list(request).filter(**applicable_filters)\n\n File "/usr/local/lib/python2.7/site-packages/tastypie_mongoengine/resources.py", line 309, in get_object_list\n self._reset_collection()\n\n File "/usr/local/lib/python2.7/site-packages/tastypie_mongoengine/resources.py", line 301, in _reset_collection\n self._meta.queryset._reset_already_indexed()\n\nAttributeError: 'QuerySet' object has no attribute '_reset_already_indexed'\n"}

One thing I noticed is that, in windows, the using mongoengine if I save collections, I get the following structure, for example.
{"_types" : [ "Test" ], "f1" : "Ranjith", "_cls" : "Test" }

But with the above mentioned configuration, I'm just getting:
{"f1": "Ranjith"}

Any help is highly appreciated as it's the project demo day..
Thanks

Raise BadRequest rather than AssertionError in MongoEngineResource.dispatch()

If an API client sends an invalid request to the API server, the server should return a 4xx response rather than a 5xx response.

The dispatch() method on MongoEngineResource raises AssertionError when testing the request method. If dispatch() was to raise tastypie_exceptions.BadRequest rather than AssertionError, then tastypie will return an HTTP 400 to the client rather than an HTTP 500.

In the 0.4.2 version of tastypie_mongoengine, the AssertionError exceptions are raised in the following places:
tastypie_mongoengine/resources.py:373
tastypie_mongoengine/resources.py:376

MongoEngineListResource does not check authorization

MongoEngineListResource objects do not check authorization for any changes (create, update, delete) prior to performing them. In obj_update for example https://github.com/wlanslovenija/django-tastypie-mongoengine/blob/master/tastypie_mongoengine/resources.py#L854 the change is made and saved without ever checking in for authorization to make the change. The only permissions enforced here are read_* checks when getting the parent/containing Document.

Failing on nested list of embedded documents

Hi,
First of all, thanks thanks to every contributor on this project, it is very useful when playing with tastypie !

I am encountering a little problem with nested list of embedded documents.
This is a little diff on the test project to reproduce the issue :

--- a/tests/test_project/test_app/documents.py
+++ b/tests/test_project/test_app/documents.py
@@ -14,6 +14,7 @@ class StrangePerson(Person):
 class EmbeddedPerson(mongoengine.EmbeddedDocument):
     name = mongoengine.StringField(max_length=200, required=True)
     optional = mongoengine.StringField(max_length=200, required=False)
+    coworkers = mongoengine.ListField(mongoengine.EmbeddedDocumentField("EmbeddedPerson"))

 class EmbeddedStrangePerson(EmbeddedPerson):
     strange = mongoengine.StringField(max_length=100, required=True)

--- a/tests/test_project/test_app/api/resources.py
+++ b/tests/test_project/test_app/api/resources.py
@@ -38,6 +38,8 @@ class EmbeddedStrangePersonResource(resources.MongoEngineResource):
         object_class = documents.EmbeddedStrangePerson

 class EmbeddedPersonResource(resources.MongoEngineResource):
+    coworkers = fields.EmbeddedListField(of='test_project.test_app.api.resources.EmbeddedPersonResource',     attribute='coworkers', full=True, null=True
+    
     class Meta:
         object_class = documents.EmbeddedPerson
         allowed_methods = ('get', 'post', 'put', 'patch', 'delete')

After populating the database :

$ ./manage.py shell
Python 2.7.3 (default, Apr 20 2012, 22:39:59) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from test_project.test_app.documents import *
>>> leo = EmbeddedPerson(name = 'leo')
>>> tom = EmbeddedPerson(name = 'tom')
>>> max = EmbeddedPerson(name = 'max')
>>> leo.coworkers = [tom,max]
>>> tom.coworkers = [max]
>>> liste = EmbeddedListFieldTest(embeddedlist = [leo,tom,max])
>>> liste.save()
<EmbeddedListFieldTest: EmbeddedListFieldTest object>

And when accessing to /api/v1/embeddedlistfieldtest/, we get an error : "init() takes at least 3 arguments (2 given)" :

Traceback (most recent call last):

  File "/home/leo/Coding/django-tastypie-mongoengine/tests/local/lib/python2.7/site-packages/tastypie/resources.py", line 192, in wrapper
    response = callback(request, *args, **kwargs)

  File "/home/leo/Coding/django-tastypie-mongoengine/tests/local/lib/python2.7/site-packages/tastypie/resources.py", line 397, in dispatch_list
    return self.dispatch('list', request, **kwargs)

  File "/home/leo/Coding/django-tastypie-mongoengine/tests/tastypie_mongoengine/resources.py", line 251, in dispatch
    return super(MongoEngineResource, self).dispatch(request_type, request, **kwargs)

  File "/home/leo/Coding/django-tastypie-mongoengine/tests/local/lib/python2.7/site-packages/tastypie/resources.py", line 427, in dispatch
    response = method(request, **kwargs)

  File "/home/leo/Coding/django-tastypie-mongoengine/tests/local/lib/python2.7/site-packages/tastypie/resources.py", line 1037, in get_list
    to_be_serialized['objects'] = [self.full_dehydrate(bundle) for bundle in bundles]

  File "/home/leo/Coding/django-tastypie-mongoengine/tests/tastypie_mongoengine/resources.py", line 292, in full_dehydrate
    return super(MongoEngineResource, self).full_dehydrate(bundle)

  File "/home/leo/Coding/django-tastypie-mongoengine/tests/local/lib/python2.7/site-packages/tastypie/resources.py", line 654, in full_dehydrate
    bundle.data[field_name] = field_object.dehydrate(bundle)

  File "/home/leo/Coding/django-tastypie-mongoengine/tests/tastypie_mongoengine/fields.py", line 173, in dehydrate
    m2m_dehydrated.append(self.dehydrate_related(m2m_bundle, m2m_resource))

  File "/home/leo/Coding/django-tastypie-mongoengine/tests/local/lib/python2.7/site-packages/tastypie/fields.py", line 514, in dehydrate_related
    return related_resource.full_dehydrate(bundle)

  File "/home/leo/Coding/django-tastypie-mongoengine/tests/tastypie_mongoengine/resources.py", line 296, in full_dehydrate
    return super(MongoEngineResource, self).full_dehydrate(bundle)

  File "/home/leo/Coding/django-tastypie-mongoengine/tests/local/lib/python2.7/site-packages/tastypie/resources.py", line 654, in full_dehydrate
    bundle.data[field_name] = field_object.dehydrate(bundle)

  File "/home/leo/Coding/django-tastypie-mongoengine/tests/tastypie_mongoengine/fields.py", line 170, in dehydrate
    m2m_resource = self.get_related_resource(m2m)

  File "/home/leo/Coding/django-tastypie-mongoengine/tests/local/lib/python2.7/site-packages/tastypie/fields.py", line 462, in get_related_resource
    related_resource = self.to_class()

  File "/home/leo/Coding/django-tastypie-mongoengine/tests/tastypie_mongoengine/fields.py", line 188, in <lambda>
    self._to_class_with_listresource = lambda api_name=None: base_with_listresource(self._resource, self.instance_name, api_name)

  File "/home/leo/Coding/django-tastypie-mongoengine/tests/tastypie_mongoengine/resources.py", line 554, in __init__
    self.parent = parent(api_name)

TypeError: __init__() takes at least 3 arguments (2 given)

And then, to be honest, I don't know what's happening : as far as I know, parent should be a MongoEngineResource, inherited from tastypie.ModelResource, inherited from tastypie.Resource, which only takes the api_name as parameter...

Thanks in advance for spending your time on this.
Leo.

How can I implement token based authentication and authorization.

Hi,

I am implementing the RESTfull server where I have to serve rest services to different type of clients so in order to keep it as stateless service I want to use token based authentication where I will return a bearer token on login and then I wanna use this token in Authorization Header to authorize other rest services.

I tried to googling it but could not found any prefect solution.

Thanks,
AbdulWahid

Exact synatx of Datetime field in POST

I am trying to send date_time from jQuery post to our server we are using mongoDB as backend and using django_tastypie_mongoengine for posting so far i have tried putting date="2010-11-10T03:07:43" and also date="2013-05-21T02:17:55.544000" in my jQuery but it is failing everytime.

I want to know the exact syntax of sending date

Question about accessing a referencefield from tastypie

Hello,

First here is the code :
API resources : https://github.com/Seraf/LISA/blob/6cf8d2ea7928c91231a30ef0734da81ac8d8fdbe/LISA-Engine/web/interface/api.py
Models used :

These models have a referencefield to a user (as a user have a Workspace)
I'm trying to create a Workspace resource by post method with Tastypie (using the swagger ui).
It shouldn't be too complicated as I have only a simple model with a : user = ReferenceField(User, required=True)

The problem is I can't pass this reference from tastypie :

Using the id of my user object : 
{
  "user": "51cade8246e1fa47c14ddfcc",
  "name": "Dashboard"
}

Result in :
{
  "error": [
    "ValidationError (Workspace:None) (A ReferenceField only accepts DBRef or documents: ['user'])"
  ]
}

When I use the resource_uri : 
{
  "user": "/api/v1/user/51cade8246e1fa47c14ddfcc/",
  "name": "Dashboard"
}

Same problem : 
{
  "error": [
    "ValidationError (Workspace:None) (A ReferenceField only accepts DBRef or documents: ['user'])"
  ]
}

I don't know if it's related to mongoengine, tastypie, or the both .. So sorry, I post my issue here. Hope you will have some free time to help me.
Thanks a lot for tastypie-mongoengine !

Getting the schema for a DynamicEmbeddedDocument via a top level endpoint

With django-tastypie-mongoengine 0.4 and django-tastypie 0.9.14, I am trying to expose the schema for a resource created from a DynamicEmbeddedDocument. This used to work in 0.3+0.9.11 but now throws an AttributeError: 'ListQuerySet' object has no attribute '_document' error, presumably because the resource returns a ListQuerySet object that doesn't get converted to a MongoEngineListResource by the EmbeddedListField.

For example, if I have the resources:

class EmbeddedFooResource(MongoEngineResource):
    ...
    class Meta:
        object_class = Foo #this is a DynamicEmbeddedDocument
        resource_name = 'foo'

class BarResource(MongoEngineResource):
    foo = EmbeddedListField('EmbeddedFooResource')
    ...
    class Meta:
        queryset = Bar.objects.all()
        resource_name = 'bar'

How would I get the schema for EmbeddedFooResource? api/v1/foo/schema/ isn't working for me and api/v1/bar/<_id>/1/foo/schema/ isn't possible. Thanks!

Help me please. Embedded polymorphic

Hello, I'm brazilian sorry if you have written something wrong.

I have a probmea a long time, how to make a MongoEngineResource Embedded field with a polymorphic

Eeste the error is reported in POST:

"{" error_message ":" <class'pessoa.models.Pessoa'> "," traceback ":" Traceback (most recent call last): \ n \ n File \ "/ home / isaiah / Projects / cedenti / venv/lib/python2.7/site-packages/tastypie/resources.py \ ", line 201, in wrapper \ n response = callback (request, * args, ** kwargs) \ n \ n File " / home / isaias/Projetos/cedenti/venv/lib/python2.7/site-packages/tastypie/resources.py \ ", line 432, in dispatch_list \ n return self.dispatch ('list', request, ** kwargs) \ n \ n File "/home/isaias/Projetos/cedenti/venv/lib/python2.7/site-packages/tastypie_mongoengine/resources.py", line 390, in dispatch \ n return self._wrap_request (request, lambda:. super (MongoEngineResource, self) dispatch (request_type, request, ** kwargs)) \ n \ n File "/home/isaias/Projetos/cedenti/venv/lib/python2.7/site-packages/tastypie_mongoengine/resources.py", line 360, in _wrap_request \ n return func () \ n \ n File "/home/isaias/Projetos/cedenti/venv/lib/python2.7/site-packages/tastypie_mongoengine/resources.py", line 390, in \ n return self._wrap_request (request, lambda: super (MongoEngineResource, self) dispatch (request_type, request, ** kwargs).) \ n \ n File \ "/ home / isaiah / Projects / cedenti/venv/lib/python2.7/site-packages/tastypie/resources.py \ ", line 464, in dispatch \ n response = method (request, ** kwargs) \ n \ n File " / home / isaias / Projetos/cedenti/venv/lib/python2.7/site-packages/tastypie/resources.py \ ", line 1348, in post_list \ n = updated_bundle self.full_dehydrate (updated_bundle) \ n \ n File "/home/isaias/Projetos/cedenti/venv/lib/python2.7/site-packages/tastypie_mongoengine/resources.py", line 428, in full_dehydrate \ n return super (MongoEngineResource, self). full_dehydrate (bundle, for_list) \ n \ n File \ "/ home/isaias/Projetos/cedenti/venv/lib/python2.7/site-packages/tastypie / resources.py \ ", line 854, in full_dehydrate \ n bundle.data [field_name] = field_object.dehydrate (bundle, for_list for_list =) \ n \ n File " / home / isaiah / Projects / cedenti / venv / lib / python2.7/site-packages/tastypie/fields.py \ ", line 732, in dehydrate \ n return self.dehydrate_related (fk_bundle, self.fk_resource, for_list for_list =) \ n \ n File " / home / isaias / Projetos/cedenti/venv/lib/python2.7/site-packages/tastypie/fields.py \ ", line 570, in dehydrate_related \ n return related_resource.full_dehydrate (bundle) \ n \ n File "/home/isaias/Projetos/cedenti/venv/lib/python2.7/site-packages/tastypie_mongoengine/resources.py", line 432, in full_dehydrate \ n return super (MongoEngineResource, self). full_dehydrate (bundle, for_list) \ n \ n File \ "/ home/isaias/Projetos/cedenti/venv/lib/python2.7/site-packages/tastypie / resources.py \ ", line 860, in full_dehydrate \ n bundle.data [field_name] = method (bundle) \ n \ n File "/home/isaias/Projetos/cedenti/venv/lib/python2.7/site-packages/tastypie_mongoengine/resources.py", line 423, in dehydrate_resource_type \ n return self._get_type_from_class (type_map, bundle.obj.class) \ n \ n File "/home/isaias/Projetos/cedenti/venv/lib/python2.7/site-packages/tastypie_mongoengine/resources.py", line 416, in _get_type_from_class \ n raise KeyError (cls) \ n \ nKeyError: <class'pessoa.models.Pessoa'> \ n "}"

Help me please.

Authentication doesn't work for EmbeddedListField

I'm trying to setup a resource with EmbeddedListField, and it fails to Authenticate user to access the individual items.

Here is my example:

class FieldDefinitionResource(MongoEngineResource):
    class Meta:
        object_class = documents.FieldDefinition
        authentication = ApiKeyAuthentication()
        authorization = StaffAuthorization()

class SectionResource(MongoEngineResource):
    fields = EmbeddedListField(attribute='fields',
        of='myproj.api.resources.FieldDefinitionResource',
        full=True, null=True)
    class Meta:
        object_class = documents.Section
        authentication = ApiKeyAuthentication()
        authorization = StaffAuthorization()

StaffAuthorization() allows performing all actions (read, update, create, delete on both list and detail) to active users, who are is_staff or is_superuser

This request

/api/v1/section/52adcdbc02c8f1078ea68f63/?format=json&username=beta&api_key=b924d14ff71d27509a25f0d779ec45db83158199

works perfectly fine, displaying the list of fields and their resource_uri's

But this one:

/api/v1/section/52adcdbc02c8f1078ea68f63/fields/0/?format=json&username=beta&api_key=b924d14ff71d27509a25f0d779ec45db83158199

fails with 401

This happens with any of the requests: GET, PATCH, POST, etc.

After switching authorization off (i.e. authorization = Authorization()), everything works fine in both cases: /section/ and /section/section_pk/fields/field_index. Also, all the requests work fine for SectionResource with authorization on, so it's not the problem with custom StaffAuthorization.

Debugging showed that in the method read_detail of StaffAuthorization the bundle.request.user is AnonymousUser - so, it skips Authentication entirely.

Unable to get resources containing an embedded document with a ReferencedListField

With the following documents:

from mongoengine import *

class Referred(Document):
    something = StringField()

class Embedded(EmbeddedDocument):
    refs = ListField(ReferenceField(Referred))

class TopLevel(Document):
    embedded = EmbeddedDocumentField(Embedded)

class TopLevelList(Document):
    embedded = ListField(EmbeddedDocumentField(Embedded))

and the following resources:

from tastypie_mongoengine.resources import MongoEngineResource, fields

class ReferredResource(MongoEngineResource):
    class Meta:
        list_allowed_methods = ('get',)
        detail_allowed_methods = ('get',)
        object_class = Referred

class EmbeddedResource(MongoEngineResource):
    refs = fields.ReferencedListField(ReferredResource, 'refs')

    class Meta:
        list_allowed_methods = ('get',)
        detail_allowed_methods = ('get',)
        object_class = Embedded

class TopLevelResource(MongoEngineResource):
    embedded = fields.EmbeddedDocumentField(EmbeddedResource, 'embedded')

    class Meta:
        list_allowed_methods = ('get',)
        detail_allowed_methods = ('get',)
        object_class = TopLevel


class TopLevelListResource(MongoEngineResource):
    embedded = fields.EmbeddedListField(EmbeddedResource, 'embedded', full=True)

    class Meta:
        list_allowed_methods = ('get',)
        detail_allowed_methods = ('get',)
        object_class = TopLevelList

getting a list of TopLevelResources throws this exception:

  File "/.../site-packages/django/core/handlers/base.py", line 115, in get_response
    response = callback(request, *callback_args, **callback_kwargs)
  File "/.../site-packages/django/views/decorators/csrf.py", line 77, in wrapped_view
    return view_func(*args, **kwargs)
  File "/.../site-packages/tastypie/resources.py", line 217, in wrapper
    response = callback(request, *args, **kwargs)
  File "/.../site-packages/tastypie/resources.py", line 459, in dispatch_list
    return self.dispatch('list', request, **kwargs)
  File "/.../site-packages/tastypie_mongoengine/resources.py", line 374, in dispatch
    return super(MongoEngineResource, self).dispatch(request_type, request, **kwargs)
  File "/.../site-packages/tastypie/resources.py", line 491, in dispatch
    response = method(request, **kwargs)
  File "/.../site-packages/tastypie/resources.py", line 1310, in get_list
    bundles.append(self.full_dehydrate(bundle, for_list=True))
  File "/.../site-packages/tastypie_mongoengine/resources.py", line 415, in full_dehydrate
    return super(MongoEngineResource, self).full_dehydrate(bundle, for_list)
  File "/.../site-packages/tastypie/resources.py", line 865, in full_dehydrate
    bundle.data[field_name] = field_object.dehydrate(bundle, for_list=for_list)
  File "/.../site-packages/tastypie/fields.py", line 729, in dehydrate
    return self.dehydrate_related(fk_bundle, self.fk_resource, for_list=for_list)
  File "/.../site-packages/tastypie/fields.py", line 565, in dehydrate_related
    return related_resource.full_dehydrate(bundle)
  File "/.../site-packages/tastypie_mongoengine/resources.py", line 415, in full_dehydrate
    return super(MongoEngineResource, self).full_dehydrate(bundle, for_list)
  File "/.../site-packages/tastypie/resources.py", line 865, in full_dehydrate
    bundle.data[field_name] = field_object.dehydrate(bundle, for_list=for_list)
  File "/.../site-packages/tastypie_mongoengine/fields.py", line 255, in dehydrate
    if not bundle.obj or not bundle.obj.pk:
AttributeError: 'Embedded' object has no attribute 'pk'

and getting a list of TopLevelListResources returns a 400, throwing this exception: https://github.com/mitar/django-tastypie-mongoengine/blob/master/tastypie_mongoengine/fields.py#L261 because bundle.obj.pk is 0.

I'm not sure why the check (https://github.com/mitar/django-tastypie-mongoengine/blob/master/tastypie_mongoengine/fields.py#L259) checks for bundle.obj.pk, but in the case of an embedded document it's clearly not correct. If I remove it, and only check for bundle.obj everything appears to work, but I'm worried it will mess up some case that I'm not testing...

How to update DictField ?

Hi;

I am trying to update a resoure. My data is:
{
"tokens" : {
"first_token": "xasdadjasdh22939123"
}
}

I am doing a PUT request and getting 204. But nothing happens.

Any example how people do that?

Suggestion: Implement ApiAuthentication

We should add support for the ApiAuthentication by adding a mongoengine model that overrides this (from tastypie/models.py):

class ApiKey(models.Model):
        user = models.OneToOneField(User, related_name='api_key')
        key = models.CharField(max_length=256, blank=True, default='')
        created = models.DateTimeField(default=datetime.datetime.now)

        def __unicode__(self):
            return u"%s for %s" % (self.key, self.user)

        def save(self, *args, **kwargs):
            if not self.key:
                self.key = self.generate_key()

            return super(ApiKey, self).save(*args, **kwargs)

        def generate_key(self):
            # Get a random UUID.
            new_uuid = uuid.uuid4()
            # Hmac that beast.
            return hmac.new(str(new_uuid), digestmod=sha1).hexdigest() 

Then it will be possible to use a specialized version of the following hook to authenticate against a mongoengine.django.auth.User object :

def create_api_key(sender, **kwargs):
        """
        A signal for hooking up automatic ``ApiKey`` creation.
        """
        if kwargs.get('created') is True:
            ApiKey.objects.create(user=kwargs.get('instance')) 

Questions about versions and an obj_create error

Hi,

I'm running into an issue with obj_create in resources.py throwing an exception. It happens after an upgrade while posting to the simplest model I can create. I really expect this is a versioning problem and before doing a pull request, wondered if you know something right off that might be the answer.

I have been successfully running the following:
python 2.7
django-tastypie==0.9.11
django-tastypie-mongoengine==0.2.1
mongoengine==0.6.16

My app has one document model which I have been POSTing and GETing from with no problem. Today I tried adding PUT and PATCH for the model, and received "not implemented" messages in the return data. I thought that (and I could be wrong) that tastypie did not implement put and/or patch in 0.9.11. So, I upgraded my packages to:

django-tastypie==0.9.12
django-tastypie-mongoengine==0.3
mongoengine==0.6.16

After this point, doing a post on my original model resulted in:
updated_bundle = self.obj_create(bundle, *_self.remove_api_resource_names(kwargs)) File "/Users/guerry/Envs/adfreeq/lib/python2.7/site-packages/tastypie_mongoengine/resources.py", line 504, in obj_create\n return super(MongoEngineResource, self).obj_create(bundle, request, *_kwargs)\n\nTypeError: obj_create() takes exactly 2 arguments (3 given)

I created a very simple model and resource (below) and got the same result.

class TestRecord(Document):
my_text = StringField(max_length='10')

class TestRecordResource(resources.MongoEngineResource):
class Meta:
queryset = TestRecord.objects.all()
resource_name = 'record'
allowed_methods = ('post', 'get')

curl "http://localhost:8000/api/v1/record/" --dump-header - -H "Content-Type: application/json" -X POST --data '{ "my_text": "cool text" }'

Any thoughts?

Polymorphic schemas

When my resource class is polymorphic, the /schema url fails, something like this:

class OtherArticle(MongoEngineResource):
    class Meta:
        queryset = models.OtherArticle.objects.all()

     publication = fields.ReferenceField(to='datahub.api.PublicationResource',
                                    attribute='publication', full=True, null=True)

class Article(MongoEngineResource):
    class Meta:
        queryset = models.Article.objects.all()
        polymorphic = {
            'article': 'self',
            'other': OtherArticle,
        }
     publication = fields.ReferenceField(to='datahub.api.PublicationResource',
                                    attribute='publication', full=True, null=True)    

The schema for the article resource returns:

Reverse for 'api_get_schema' with arguments '()' and keyword arguments '{'api_name': None, 'resource_name': 'publications'}' not found

When I remove the polymorphic attribute, it works as expected.

Python3 support?

Example from docs:

from tastypie import authorization
from tastypie_mongoengine import resources
from test_app import documents

class PersonResource(resources.MongoEngineResource):
    class Meta:
        queryset = documents.Person.objects.all()
        allowed_methods = ('get', 'post', 'put', 'delete')
        authorization = authorization.Authorization()

doesn't work with python3:

    def __new__(cls, name, bases, attrs):
        meta = attrs.get('Meta')

        if meta and hasattr(meta, 'queryset'):
>           setattr(meta, 'object_class', meta.queryset.model)
E           AttributeError: 'QuerySet' object has no attribute 'model'

objects.all() doesn't have model attribute that is required here:
https://github.com/toastdriven/django-tastypie/blob/master/tastypie/resources.py#L1691

Cannot find User by pk

    class UserResource(resources.MongoEngineResource):
        class Meta:
            queryset = models.User.objects.all()
            allowed_methods = ('get', 'post', 'put', 'delete')
            authorization = authorization.Authorization()
            resource_name = "user"

Here is the "/api/v1/user/" response:

{
  "meta": {
    "limit": 20,
    "next": null,
    "offset": 0,
    "previous": null,
    "total_count": 1
  },
  "objects": [
    {
      "bio": "I'm a computer engineer",
      "contact": {
        "twitter": "xsadasda"
      },
      "email": "[email protected]",
      "first_name": "Burak",
      "gender": "M",
      "home_city": null,
      "id": "50796e9da5e97c571445d8be",
      "last_name": "Kılıç",
      "outh_tokens": {},
      "photo": null,
      "resource_uri": "/api/v1/user/50796e9da5e97c571445d8be"
    }
  ]
}

When I make "/api/v1/user/50796e9da5e97c571445d8be" , it gives 404 not found. Is something wrong?

Installing with pip fails

OS: OS X 10.7.3

$ pip install django-tastypie-mongoengine
Downloading/unpacking django-tastypie-mongoengine
  Downloading django-tastypie-mongoengine-0.1.tar.gz
  Running setup.py egg_info for package django-tastypie-mongoengine
    Traceback (most recent call last):
      File "<string>", line 14, in <module>
      File "user/env_piplmesh/build/django-tastypie-mongoengine/setup.py", line 12, in <module>
        long_description = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read(),
    IOError: [Errno 2] No such file or directory: user/env_piplmesh/build/django-tastypie-mongoengine/README.rst'
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):

  File "<string>", line 14, in <module>

  File "user/env_piplmesh/build/django-tastypie-mongoengine/setup.py", line 12, in <module>

    long_description = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read(),

IOError: [Errno 2] No such file or directory: 'user/env_piplmesh/build/django-tastypie-mongoengine/README.rst'

----------------------------------------
Command python setup.py egg_info failed with error code 1 in user/env_piplmesh/build/django-tastypie-mongoengine
Storing complete log in user/.pip/pip.log

Problem updating resource containing EmbeddedListField of Resource containing ReferenceField (and other fields)

Hi !

I've got this schema :

class PipeResource(resources.MongoEngineResource):
    exporters = EmbeddedListField(of='api.resources.EmbeddedExporterListResource',
                          attribute='exporters', full=True, null=True)

class EmbeddedExporterListResource(resources.MongoEngineResource):
    exporter = ReferenceField(to='api.resources.ExporterResource',
                        attribute='exporter', full=True)

And when trying to update a PipeResource, I've got this error :

File "/lib/python2.7/site-packages/mongoengine/queryset.py", line 639, in _lookup_field % field_name)
InvalidQueryError: Cannot resolve field "resource_uri"

So am I doing things right or do I miss something ? Because it seems that Tastypie hands the resource_uri field to MongoEngine, and it shouldn't...
I precise that the EmbeddedExporterListResource is not only a ReferenceField, but contains other fields

Thansks for your help, I post this on stackoverflow too : http://stackoverflow.com/questions/13287098

references to dynamic documents

Let's say I have an article document with a list of references to image documents (which are dynamic).

class Image(DynamicDocument):
   something = StringField(required=True)

class Article(Document):
    images = ListField(ReferenceField(Image))

class ArticleMongoResource(MongoEngineResource):
    images = fields.ReferencedListField(of='app.api.ImageResource',
                                    attribute='images', full=True, null=True)

class ImageResource(MongoEngineResource):
   ...   

Now when I POST and add a number of arbitrary fields to images they don't seem to picked up, it seems to behave like a regular document (not dynamic), i.e.:

{ "images": [{"something": "abc", "dynamic": "def" }]

Here the "dynamic" field isn't picked up and saved, it is stripped somewhere.
Is there anything wrong with above code? What could be the case here?

Tests fail with MongoEngine 0.6.11+

Since this fix in MongoEngine (0.6.11+) tests fail with:

ValidationError(You can only reference documents once they have been saved to the database: ['person'])

at:

.../django-tastypie-mongoengine/tests/test_project/test_app/tests/test_basic.py", line 146, in test_basic
    self.assertEqual(response.status_code, 201)
AssertionError: 400 != 201

Bump supported mongoengine version to 0.8.4

Currently django-tastypie-mongoengine depends on mongoengine>=0.8.1,<0.8.2, can you bump that to 0.8.4? It seems to be working just fine with it. Are there any know issues with 0.8.4?

Creating resources containing an embedded document with a ReferencedListField doesn't work properly

This is closely related to #57. Using the same documents and resources described in that ticket, POSTing a TopLevelResource or TopLevelListResource with nonempty lists of references to ReferredResources succeeds, but the references are not actually created -- embedded.refs ends up empty.

I haven't figured out a fix for this issue, but I have a rough idea of why it's happening. It comes down to how tastypie handles m2m resources. They are not hydrated during the full_hydrate() pass, but there is a separate call to hydrate_m2m() and save_m2m() in Resource.save(). ReferencedListFields are m2m, so they follow this pattern.

The problem comes when the ReferencedListField is a member of an embedded document, because there is no logic built into the save() method to save m2m fields on embedded documents. The closest analog that tastypie supports would be a ToOneField pointing to a resource with a ToManyField. This works in tastypie because Resource.save() calls Resource.save_related(), which calls save() on the related resource that the ToOneField points to, and save() in turn calls hydrate_m2m() and save_m2m(). However, this doesn't work in our case because embedded documents aren't their own resource -- we don't call save() on them, so there is no opportunity to call hydrate_m2m() and save_m2m().

That's the nub of the problem -- the embedded documents are kind of acting like related resources, but we don't call save on them, so we don't save their m2m fields. My best idea for a fix for this is to add an is_embedded attribute to EmbeddedDocumentField and EmbeddedListField (analogous to the is_m2m attribute). Then, in MongoEngineResource.save(), notice any is_embedded fields and call their hydrate_m2m() and save_m2m() methods. Except this won't exactly work, because I think hydrate_m2m and/or save_m2m have some code that assumes they are being called in the context of a top-level resource whose object has a functioning save() method and a pk and everything, which won't be the case here.

Not compatible with QuerySetNoCache()

If you are inheriting from MongoEngine's QuerySetNoCache() instead of QuerySet() for a custom QuerySet, the you will get the following error:

File \"/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/tastypie/resources.py\", line 1930, in build_filters

    query_terms = self._meta.queryset.query.query_terms

AttributeError: 'CustomQuerySet' object has no attribute 'query'

If you lift the code from lines 32-41 of resources.py and add it to your custom QuerySet class, things will work. Seems like that code is very specific to using the cached QuerySet and not supporting the non-cached version?

Add support for filtering on EmbeddedDocumentField

Currently it's not possible to filter by values stored in EmbeddedDocumentField.

When attempting to search by any of the embedded document fields - the error is thrown in "tastypie/resources.py", line 1584, in check_filtering function: raise InvalidFilterError("The '%s' field does not support relations." % field_name)

It is possible to force django-tastypie-mongoengine to allow search by that field (by wrapping the field resource in a class that overrides the is_related value), however it does mean breaking the create/edit actions via the API.

Upload file image

How to use django-tastypie-mongoengine to upload file image via api?

Exact syntax of sending date in Datetime field in POST

I am trying to send date_time from jQuery post to our server we are using mongoDB as backend and using django_tastypie_mongoengine for posting so far i have tried putting date="2010-11-10T03:07:43" and also date="2013-05-21T02:17:55.544000" in my jQuery but it is failing everytime.
I want to know the exact syntax of sending date

Improve atomicity of operations

Current implementation is really badly implemented as it is based on code which assumes transactions. For MongoEngine (and MongoDB) this is of course not true, so some improvements to operations should be done to implement them through atomic operations. And not through current fetch-update-save cycle.

Even worse is for subresources (lists), especially because we use indexes so things could move around and something would not be anymore on its place. You want to delete n-th element, but that element could be already something else at the time it is processed. Maybe we should introduce some dummy UUID/PKs to make sure we know what we are operating on. Operations on subresources should be really implemented through MongoEngine/MongoDB atomic operations on list and not changing list in the code.

Document validation on full_hydrate

Hi,

Since c9bedc3, Mongoengine's validate() method is called before returning the bundle.
I understand that is used to handle validation errors and to return the proper error message, but this awkward when doing auto-allocation on required fields in document's save() method for example.

Won't the validation reporting be in a better place in obj_create() and obj_update() methods ?
If you're agree, just say it and I'll make a pull request ;)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.