【问题标题】:Exposing model method with Tastypie用 Tastypie 暴露模型方法
【发布时间】:2012-12-29 20:57:44
【问题描述】:

我目前正致力于在我的 Django 项目中实现一个 API,Tastypie 似乎是最合适的。

我似乎无法解决的是如何使用 Tastypie 在我的模型中公开一个函数。

例如,我有这个模型:

class game(models.Model):
    id = models.AutoField("ID", primary_key=True, editable=False)
    ip_address = models.OneToOneField(IPAddress, verbose_name="IP Address")
    port = models.CharField("Port", max_length=5)
    name = models.CharField("Game Name", max_length=100)
    ram = models.IntegerField("RAM (mb)", max_length=10)
    node = models.ForeignKey(node)
    user = models.ForeignKey(User)
    config = models.ForeignKey(Config)
    mysqlserver = models.ForeignKey(MySQLserver)
    mysqlenabled = models.BooleanField("MySQL Created?")
    suspended = models.BooleanField("Suspended")

在这个模型中,我有这样的功能:

def start(self):
    config = Config.objects.get(pk=self.config.id)
    cmds = config.startcmds
    game = config.gametype
    parsedcmds = self.replace_variables(cmds)

    client = phPanel.jelly.jelly.zmqclient(self.ip_address.address)
    data = {'user':self.generate_username(), 'method':'start_server', 'id':self.id, 'memory':self.ram, 'ip':self.ip_address.address,
            'port':self.port, 'startcmds':parsedcmds, 'game':game}

    result = client.send(data)
    return result

我想通过 API 使用 sweetpie 来公开它。

我浏览了文档和食谱,但似乎找不到我要找的东西。

任何帮助将不胜感激:)

【问题讨论】:

标签: python django tastypie


【解决方案1】:

在您的游戏资源中,您始终可以预先添加可以公开方法的新网址。例如(根据@BigglesZX的评论编辑):

from tastypie.resources import ModelResource
from tastypie.utils import trailing_slash

class GameResource(ModelResource):
    class Meta:
         queryset = Game.objects.all()
         resource_name = 'store'

    def prepend_urls(self):
        """ Add the following array of urls to the GameResource base urls """
        return [
            url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/start%s$" %
                (self._meta.resource_name, trailing_slash()),
                self.wrap_view('start'), name="api_game_start"),
        ]

    def start(self, request, **kwargs):
         """ proxy for the game.start method """  

         # you can do a method check to avoid bad requests
         self.method_check(request, allowed=['get'])

         # create a basic bundle object for self.get_cached_obj_get.
         basic_bundle = self.build_bundle(request=request)

         # using the primary key defined in the url, obtain the game
         game = self.cached_obj_get(
             bundle=basic_bundle,
             **self.remove_api_resource_names(kwargs))

         # Return what the method output, tastypie will handle the serialization
         return self.create_response(request, game.start())

所以现在您可以使用以下 uri "/game/[pk]/start/" 调用此方法 所以“/game/1/start/”会调用pk = 1的游戏启动方法

【讨论】:

  • cached_obj_get 函数的签名已根据此答案更改:stackoverflow.com/a/15159600/258794
  • 你是对的@BigglesZX 我更新了我的答案以反映最新版本的美味。
  • 你会如何处理美味派 0.9.11 ?我在这个版本中没有找到任何 prepend_urls 函数:/
  • @aRkadeFR 在 0.9.11 中,官方的方式是使用方法“override_urls”,它已被弃用,取而代之的是“prepend_urls”。你可以在这里找到文档:django-tastypie.readthedocs.org/en/v0.9.11/…
猜你喜欢
  • 1970-01-01
  • 2014-10-27
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-04
相关资源
最近更新 更多