简体   繁体   中英

Manipulate Request data of TastyPie and Django API

I'm writing an application with django-tastypie and following are my models.py and resource.py files.

Models.py:

import uuid

from django.db import models


class User(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=50, null=False)
    email = models.EmailField(max_length=254, null=False)
    password = models.CharField(max_length=100, null=False)
    role = models.CharField(max_length=16, default='basic', null=False)

    def __unicode__(self):
        return self.name, self.email

Resources.py:

from tastypie.resources import ModelResource
from tastypie.authorization import Authorization

from api.models import User


class UserResource(ModelResource):
    class Meta:
        queryset = User.objects.all()
        resource_name = 'user'
        authorization = Authorization()
        excludes = ['password']
        #allowed_methods = ['get']

Now the thing is that whenever I hit an API end point from postman, the user is created directly. Now what I don't understand is that whether the request data goes into resources and then into database or directly into the database? Actually, the thing is that I need to apply some changes to the data before it is stored in the database, like hashing the password and then storing the object in the database. I'm new to django, so how can I achieve that? Like in Flask, we can do something like:

@user.route('/users', methods=['POST'])
def create_user(user_id):

    data = request.get_json(force=True)

    # do all the changes we want

    user = User(data)
    db.session.add(user)
    db.session.commit()

Now if any request comes at '/users' endpoint, we can get it's data in the 'data' variable and then whatever changes we want before storing in the database. But how to do that in django with tastypie.

Any help would be appreciated

If you have to massage data before entering into database then Tastypie has the notion of hydrate and dehydrate methods.

Check that. Here is reference hydrate and dehydrate

In every web framework the data that sent with the request passed to the api endpoint through some mechanism and the same thing happens in Tastypie (you can read about it in Tastypie documentation under Flow Through The Request/Response Cycle ).

If you want to change the data that you sending/receiving read about Hydrate/Dehydrate , in your case you want to use dehydrate on user password but I recommend you to save the effort and instead use custom user model by inheriting from AbstractUser , that way you can get hashed password by default when User object is saved to your DB.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM