标签: tastypie

在视图中使用tastypie资源

我的第一个问题:

所以我正在使用tastypie来为我的应用程序提供api.

我希望能够使用tastypie渲染json,然后将其包含在django视图中,以便我可以引导我的应用程序的数据.

这里有django tastypie食谱中的一个例子:http://django-tastypie.readthedocs.org/en/latest/cookbook.html#using-your-resource-in-regular-views

问题是我无法使用它,我尝试了从简单到更复杂的变体,我只是无法得到它,这里是我的模型的一些代码:

class ChatMessage(models.Model):
     content = models.TextField()
     added = models.DateTimeField(auto_now_add=True)

     author = models.ForeignKey(ChatUser, related_name="messages")
     chat_session = models.ForeignKey(ChatSession, related_name="messages")
     answer_to = models.ForeignKey('self', blank=True, null=True)

     flagged = models.BooleanField(blank=True,default=False)
     mododeleted = models.BooleanField(blank=True,default=False)
     mododeleted_by = models.ForeignKey(ChatUser,blank=True,null=True,default=None)
     mododeleted_at = models.DateTimeField(blank=True,null=True,default=None)
     [...]

class ChatSession (models.Model):
    title = models.CharField(max_length=200)
    link_title = models.CharField(max_length=200)
    description = tinymce_models.HTMLField()
    date = models.DateTimeField()
    online = models.BooleanField(default=False)
    next_session = models.BooleanField(default=False)
    meps = models.ManyToManyField(ChatMep)
    uid_newsupdate = models.CharField(max_length=200,blank=True,null=True,default="")
    [...]
Run Code Online (Sandbox Code Playgroud)

和我的资源:

class ChatMessageResource(MyModelResource):
    chat_session = fields.ForeignKey(ChatSessionResource, 'chat_session')

    def renderOne(self,request,pkval):
       data …
Run Code Online (Sandbox Code Playgroud)

python django rest tastypie

6
推荐指数
1
解决办法
7444
查看次数

tastypie发布和完整的例子

是否有完整的tastypie django示例站点和设置可供下载?我一直在挣扎着整天缠着它.我有以下代码.基本上,我有一个用ajax处理的POST表单.当我在表单上单击"提交"并运行ajax请求时,调用将返回"POST http://192.168.1.110:8000/api/private/client_basic_info/ 404(未找到)"我已将URL配置为正常,我认为.我可以访问http://192.168.1.110:8000/api/private/client_basic_info/?format=json就好了.我错过了一些设置或在我的方法中出现了一些基本错误吗?我的意图是每个用户可以填写/修改一个且仅修改一个"客户端基本信息"表单/模型.

页面:

{% extends "layout-column-100.html" %}
{% load uni_form_tags sekizai_tags %}

{% block title %}Basic Information{% endblock %}

{% block main_content %}

    {% addtoblock "js" %}
        <script language="JavaScript">

        $(document).ready( function() {

            $('#client_basic_info_form').submit(function (e) {

                form = $(this)

                form.find('span.error-message, span.success-message').remove()
                form.find('.invalid').removeClass('invalid')
                form.find('input[type="submit"]').attr('disabled', 'disabled')

                e.preventDefault();
                var values = {}

                $.each($(this).serializeArray(), function(i, field) {
                    values[field.name] = field.value;
                })


                $.ajax({
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(values),
                    dataType: 'json',
                    processData: false,
                    url: '/api/private/client_basic_info/',
                    success: function(data, status, jqXHR) {
                        form.find('input[type="submit"]')
                            .after('<span …
Run Code Online (Sandbox Code Playgroud)

api django tastypie

6
推荐指数
1
解决办法
1万
查看次数

如果资源已经存在,我如何才能使Django-Tastypie覆盖资源?

我正在使用一些简单的django-tastypie资源,存在以下问题:

想象一下,我正在构建一个简单的评级系统.我有一个资源,称之为Ratinga User和a Comment.每个用户每个评论最多有一个评级.

我想制作一个带有元组的通用资源('user', 'comment').然后,每当我使用新的POST进行POST时Rating,我都希望检查usercomment字段以查看是否已经存在与这两个字段匹配的评级.如果是,则覆盖现有资源,否则创建新资源(这样任何API调用都将始终传递Django的unique_together).

我正在努力obj_get作为一个起点,但很难理解如何正确地覆盖它以获得这种行为.

python django tastypie

6
推荐指数
1
解决办法
1754
查看次数

Tastypie foreignkey设置为null

我正在创建UserResource和UserProfileResource.当我创建一个新用户时,我看到我的userprofile数据库表也在被更新.这很好.但当我获取用户时,我得到一个错误说:

The model '' has an empty attribute 'profile' and doesn't allow a null value.
Run Code Online (Sandbox Code Playgroud)

我的代码:

resources.py

class UserProfileResource(ModelResource):
    home_address = fields.CharField(attribute='home_address')
    user = fields.ToManyField('resources.UserResource', attribute='user', related_name='profile')
    class Meta:
        queryset = UserProfile.objects.all()
        resource_name = 'profile'
        allowed_methods = ['get', 'post', 'delete', 'put']
        fields = ['home_address']
        authorization = Authorization()
        include_resource_uri = False
        include_absolute_url = False

class UserResource(ModelResource):
    profile = fields.ToOneField('resources.UserProfileResource', attribute = 'profile', related_name='user', full=True)
    class Meta:
        queryset = User.objects.all()
        resource_name = 'user'
        allowed_methods = ['get', 'post', 'delete', 'put']
        fields = ['username'] …
Run Code Online (Sandbox Code Playgroud)

django tastypie

6
推荐指数
1
解决办法
4454
查看次数

为多表继承Django模型填充tastypie资源

鉴于以下代码,我想知道如何填充RecordsResource每个真实的记录数据:

models.py

class Record(models.Model):
    content_type = models.ForeignKey(ContentType, editable=False, null=True)
    user = models.ForeignKey(User, related_name='records')
    issued = models.DateTimeField(auto_now_add=True)
    date = models.DateField()

    def save(self, *args, **kwargs):
        if not self.content_type:
            self.content_type = ContentType.objects.get_for_model(self.__class__)
        super(Record, self).save(*args, **kwargs)

    def as_leaf_class(self):
        model = self.content_type.model_class()
        if model == self.__class__:
            return self
        return model.objects.get(pk=self.id)


class Record1(Record):
    # some fields

# ...

class RecordN(Record):
    # some fields
Run Code Online (Sandbox Code Playgroud)

api.py

class BaseModelResource(ModelResource):
    class Meta(object):
        authentication = ApiKeyPlusWebAuthentication()
        authorization= Authorization()
        cache = SimpleCache()
        throttle = CacheDBThrottle(
            throttle_at=350,
            # 1 day
            expiration=86400 …
Run Code Online (Sandbox Code Playgroud)

django django-models tastypie

6
推荐指数
1
解决办法
1642
查看次数

Tastypie - 允许未经身份验证的用户使用只读权限,同时授予授权的写入权限

我正在使用Tastypie 0.9.11并且我希望允许未经身份验证的用户获得对API的只读权限,同时,如果用户使用API​​密钥身份验证进行身份验证,则该用户可以执行添加/更改/删除操作那些相同的模型.

使用API​​密钥身份验证+ Django授权不满足要求1(未经身份验证的用户根本无法访问API).使用无身份验证不允许用户使用API​​密钥进行身份验证(不满足要求2).

我打赌有一种简单的方法来实现这种行为,请帮助.

非常感谢,Yuval Cohen

django django-authentication tastypie

6
推荐指数
1
解决办法
1551
查看次数

Tastypie与application/x-www-form-urlencoded

我在确定下一步应该是什么时遇到了一些困难.我正在使用tastypie为我的Web应用程序创建API.

从另一个应用程序,特别是ifbyphone.com,我收到一个没有标题的POST,看起来像这样:

post data:http://myapp.com/api/
callerid=1&someid=2&number=3&result=Answered&phoneid=4
Run Code Online (Sandbox Code Playgroud)

现在,我在我的服务器日志中看到这是在击中我的服务器.但是tastypie抱怨POST的格式.

{"error_message":"指示'application/x-www-form-urlencoded'的格式没有可用的反序列化方法.请检查你的formatscontent_types你的Serializer.","traceback":"Traceback(最近的呼叫最后一次):\n \n File \"/ usr/local/lib/python2.7/dist-packages/tastypie/resources.py \"

当我尝试使用curl发布原始数据时,我也收到相同的消息,我"相信"与ifbyphone的POST方法使用的基本过程相同:

curl -X POST --data 'callerid=1&someid=2&number=3&duration=4&phoneid=5' http://myapp.com/api/
Run Code Online (Sandbox Code Playgroud)

因此,假设我的问题实际上是错误消息中指定的内容,并且没有反序列化方法,我将如何编写一个?

####更新######

在这个提交的帮助下(https://github.com/toastdriven/django-tastypie/commit/7c5ea699ff6a5e8ba0788f23446fa3ac31f1b8bf)我一直在编写自己的序列化程序,从文档中复制基本框架(https:// django -tastypie.readthedocs.org/en/latest/serialization.html#implementing-your-own-serializer)

import urlparse
from tastypie.serializers import Serializer

class urlencodeSerializer(Serializer):
    formats = ['json', 'jsonp', 'xml', 'yaml', 'html', 'plist', 'urlencode']
    content_types = {
        'json': 'application/json',
        'jsonp': 'text/javascript',
        'xml': 'application/xml',
        'yaml': 'text/yaml',
        'html': 'text/html',
        'plist': 'application/x-plist',
        'urlencode': 'application/x-www-form-urlencoded',
        }
    def from_urlencode(self, data,options=None):
        """ handles basic formencoded url posts """
        qs = dict((k, …
Run Code Online (Sandbox Code Playgroud)

python django tastypie

6
推荐指数
1
解决办法
3687
查看次数

基于Django-Tastypie构建的Self Documenting API

我使用django-tastypie,我很高兴.但我真的想从Django Rest Framework获得自我记录的api功能.

有哪些解决方案(或有人建立)来获得这种自动生成的Django Rest Framework文档,但是来自基于TastyPie的API?

api django documentation tastypie

6
推荐指数
1
解决办法
1290
查看次数

什么是django休息框架的控制流程

我正在为webapp开发api.我最初使用tastypie并切换到django-rest-framework (drf).Drf对我来说似乎很容易.我打算做的是创建嵌套的用户配置文件对象.我的模型如下

from django.db import models
from django.contrib.auth.models import User

class nestedmodel(models.Model):
    info = models.CharField(null=True, blank=True, max_length=100)


class UserProfile(models.Model):
    add_info = models.CharField(null=True, blank=True, max_length=100)
    user = models.OneToOneField(User)
    nst = models.ForeignKey(nestedmodel)
Run Code Online (Sandbox Code Playgroud)

我有其他具有Foreignkey Relation的模型.我的序列化器如下

from django.contrib.auth.models import User, Group
from rest_framework import serializers
from quickstart.models import UserProfile, nestedmodel


class NestedSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = nestedmodel
        fields = ('info', )

class UserSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'groups')


class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group
        fields …
Run Code Online (Sandbox Code Playgroud)

django control-flow tastypie django-rest-framework

6
推荐指数
1
解决办法
3937
查看次数

通过客户端使用两个API作为IOS应用程序(Swift)的喜欢功能实现

我们正在尝试为我们的IOS应用程序构建一个简单的关注功能.我们有两个API,我们Brand API的对象数组包含每个对象中我们品牌的独特品牌ID.我们Firebase API在哪里存储用户.在Firebase API它内部有一个名为unique brand ids from ourfollowBrands的键,其中的对象数组由Brand API` 组成,键为值为true.一旦用户按照品牌喜欢我们的应用程序上的品牌,就会创建对象.

当应用程序加载时,我们会检查Firebase API品牌ID 是否与品牌ID相匹配,Brand API然后显示一个星标,表示用户已经关注该品牌.

我们的问题是Brand API通过分页(即抵消)来实现,那么如果不是所有独特的品牌ID都可以与我们进行比较,我们将如何验证他们所关注的所有品牌Firebase API

我们在IOS方面使用swift.并Brand API使用django-tastypie构建

Firebase API

"user_id" : {
  "currentFollowingCount" : 0,
  "displayName" : "",
  "email" : "",
  "followingBrands" : {
    "unique_brand_id" : true
  },
  "provider" : "Facebook",
  "userID" : "user_id"
}
Run Code Online (Sandbox Code Playgroud)

品牌API

{
  "labels": [
    {
      "id": "unique_brand_id"
    }
  ],
  "meta": {
    "limit": 10,
    "next": "/api/?limit=10&offset=10", …
Run Code Online (Sandbox Code Playgroud)

ios tastypie swift

6
推荐指数
1
解决办法
145
查看次数