(. Ho dovuto modificare i link più evidenti)
+1 per piston
- (link sopra). In passato avevo usato apibuilder
(fonte aperta di Washington Times), ma l'Piston per me è più semplice. La cosa più difficile per me è capire le mie strutture URL per l'API e aiutare con le espressioni regolari. Ho anche usato surlex che rende questo compito molto più facile.
esempio, utilizzando questo modello per Group
(da un sistema di calendario a cui stiamo lavorando):
class Group(models.Model):
"""
Tree-like structure that holds groups that may have other groups as leaves.
For example ``st01gp01`` is part of ``stage1``.
This allows subgroups to work. The name is ``parents``, i.e.::
>>> stage1group01 = Group.objects.get(unique_name = 'St 1 Gp01')
>>> stage1group01
>>> <Group: St 1 Gp01>
# get the parents...
>>> stage1group01.parents.all()
>>> [<Group: Stage 1>]
``symmetrical`` on ``subgroup`` is needed to allow the 'parents' attribute to be 'visible'.
"""
subgroup = models.ManyToManyField("Group", related_name = "parents", symmetrical= False, blank=True)
unique_name = models.CharField(max_length=255)
name = models.CharField(max_length=255)
academic_year = models.CharField(max_length=255)
dept_id = models.CharField(max_length=255)
class Meta:
db_table = u'timetable_group'
def __unicode__(self):
return "%s" % self.name
E questo frammento urls.py (si noti che surlex permette macro espressioni regolari da istituire facilmente) :
from surlex.dj import surl
from surlex import register_macro
from piston.resource import Resource
from api.handlers import GroupHandler
group_handler = Resource(GroupHandler)
# add another macro to our 'surl' function
# this picks up our module definitions
register_macro('t', r'[\w\W ,-]+')
urlpatterns = patterns('',
# group handler
# all groups
url(r'^groups/$', group_handler),
surl(r'^group/<id:#>/$', group_handler),
surl(r'^group/<name:t>/$', group_handler),)
Poi questo gestore si prenderà cura di uscita JSON (per impostazione predefinita) e possono anche fare XML e YAML.
class GroupHandler(BaseHandler):
"""
Entry point for Group model
"""
allowed_methods = ('GET',)
model = Group
fields = ('id', 'unique_name', 'name', 'dept_id', 'academic_year', 'subgroup')
def read(self, request, id=None, name=None):
base = Group.objects
if id:
print self.__class__, 'ID'
try:
return base.get(id=id)
except ObjectDoesNotExist:
return rc.NOT_FOUND
except MultipleObjectsReturned: # Should never happen, since we're using a primary key.
return rc.BAD_REQUEST
else:
if name:
print self.__class__, 'Name'
return base.filter(unique_name = name).all()
else:
print self.__class__, 'NO ID'
return base.all()
Come potete vedere, la maggior parte del codice di gestione è a capire quali parametri vengono passati in urlpatterns
.
Alcuni URL di esempio sono api/groups/
, api/group/3301/
e api/group/st1gp01/
- che emetteranno tutti JSON.
Che ne dici di ottenere JSON? – marcc
Creare un decoratore 'json_view', che è simile:' restituisci HttpResponse (json.dumps (result), mimetype = "application/json") ' –
(Installa' simplejson' o usa il modulo 'json' incorporato in Python 2.6 e versioni successive.) –