started apidoc

This commit is contained in:
seba 2011-10-04 19:36:16 +02:00
parent 793162c060
commit b2438f2981
6 changed files with 247 additions and 15 deletions

View File

@ -6,27 +6,22 @@ from django.contrib.auth.decorators import user_passes_test
from django.contrib.auth.models import Group from django.contrib.auth.models import Group
from decorators import * from decorators import *
from decimal import Decimal, InvalidOperation from decimal import Decimal, InvalidOperation
from helper import *
import datetime import datetime
def getInt(d, key, default):
try:
return int(d.get(key, default))
except ValueError:
return default
def getDecimal(d, key, default):
try:
return Decimal(d.get(key, default))
except InvalidOperation:
return default
class BuyableItemHandler(BaseHandler): class BuyableItemHandler(BaseHandler):
"""Handler responsible for getting and buying items."""
allowed_methods = ('GET', 'POST') allowed_methods = ('GET', 'POST')
#fields = ('id', 'description') #fields = ('id', 'description')
model = Buyable model = Buyable
exclude = ('_*',) exclude = ('_*',)
def read(self, request, itemId=None): def read(self, request, itemId=None):
"""Get one or multiple items.
- type: Only get items belonging to this type
"""
if itemId == None: if itemId == None:
if request.GET.has_key('type'): if request.GET.has_key('type'):
obj = Buyable.objects.filter(buyableType__name=request.GET['type']) obj = Buyable.objects.filter(buyableType__name=request.GET['type'])
@ -42,6 +37,12 @@ class BuyableItemHandler(BaseHandler):
@manglePluginPerms @manglePluginPerms
def create(self, request, itemId=None): def create(self, request, itemId=None):
"""Buy a :class:`Buyable <buyable.models.Buyable>` item.
- deposit Set to > 0 if you want to buy the item with deposit (default 0)
- amount amount of items to buy (default 1)
"""
if not request.content_type: if not request.content_type:
request.data = request.POST request.data = request.POST
if not itemId: if not itemId:
@ -75,15 +76,26 @@ class BuyableItemHandler(BaseHandler):
return rc.CREATED return rc.CREATED
class BuyableTypeHandler(BaseHandler): class BuyableTypeHandler(BaseHandler):
"""Handler for listing all :class:`BuyableType <buyable.models.BuyableType>`.
This class only supports read requests which won't accept
any arguments. It will give you a list of buyable-types.
Nothing more, nothing less.
"""
allowed_methods = ('GET',) allowed_methods = ('GET',)
model = BuyableType model = BuyableType
class HistoryHandler(BaseHandler): class HistoryHandler(BaseHandler):
"""Handler providing access to the users history """
allowed_methods = ('GET',) allowed_methods = ('GET',)
fields = ('id', 'price', 'dateTime', ('purchase_set', (('buyable', ('id', )), 'price', 'name'))) fields = ('id', 'price', 'dateTime', ('purchase_set', (('buyable', ('id', )), 'price', 'name')))
@manglePluginPerms @manglePluginPerms
def read(self, request): def read(self, request):
"""Get the users history
- num: Number of entries to return
"""
num = getInt(request.GET, 'num', 0) num = getInt(request.GET, 'num', 0)
qset = Order.objects.filter(user=request.user) qset = Order.objects.filter(user=request.user)
if num > 0: if num > 0:
@ -92,12 +104,22 @@ class HistoryHandler(BaseHandler):
class TransactionTransactHandler(BaseHandler): class TransactionTransactHandler(BaseHandler):
"""Handler for transaction.
This hanlder takes care of adding money to accounts and returning
previous moneytransfers
"""
allowed_methods = ('GET', 'POST') allowed_methods = ('GET', 'POST')
model = Transaction model = Transaction
fields = ('amount', 'dateTime', 'checked', ('transactionType', ('id', 'name'))) fields = ('amount', 'dateTime', 'checked', ('transactionType', ('id', 'name')))
@manglePluginPerms @manglePluginPerms
def read(self, request): def read(self, request):
"""Return the users last transactions
- num: Number of entries to return
"""
num = getInt(request.GET, 'num', 0) num = getInt(request.GET, 'num', 0)
if num < 0: if num < 0:
return rc.BAD_REQUEST return rc.BAD_REQUEST
@ -109,6 +131,11 @@ class TransactionTransactHandler(BaseHandler):
@manglePluginPerms @manglePluginPerms
def create(self, request): def create(self, request):
"""Transact money to an account
- amount: [req] Amount to add to the users account
- type: [req]Type of transaction (id)
"""
amount = getDecimal(request.POST, 'amount', Decimal(0)) amount = getDecimal(request.POST, 'amount', Decimal(0))
tTypeId = getInt(request.POST, 'type', -1) tTypeId = getInt(request.POST, 'type', -1)
@ -133,23 +160,41 @@ class TransactionTransactHandler(BaseHandler):
return rc.ALL_OK return rc.ALL_OK
class TransactionTypeHandler(BaseHandler): class TransactionTypeHandler(BaseHandler):
"""Handler for :class:`Transaction Types <transaction.models.TransactionType>`
Supplies a list of Transaction Types
"""
allowed_methods = ('GET',) allowed_methods = ('GET',)
model = TransactionType model = TransactionType
class AccountBalanceHandler(BaseHandler): class AccountBalanceHandler(BaseHandler):
"""Handler for the users account balance"""
allowed_methods = ('GET',) allowed_methods = ('GET',)
@manglePluginPerms @manglePluginPerms
def read(self, request): def read(self, request):
"""Returns the users current account balance"""
balance = request.user.get_profile().balance balance = request.user.get_profile().balance
return {'balance': balance} return {'balance': balance}
class AuthBlobHandler(BaseHandler): class AuthBlobHandler(BaseHandler):
"""Handler to read and write an users authblob
Currently these functions are only available for a plugin user.
Other users will get a rc.FORBIDDEN. Keep in mind that, to use
these functions a plugin needs the permissions to do this in its
configuration.
"""
allowed_methods = ('GET', 'POST') allowed_methods = ('GET', 'POST')
@requirePlugin @requirePlugin
@manglePluginPerms @manglePluginPerms
def read(self, request): def read(self, request):
"""Read the users authblob
To use this function the plugin needs
:attr:`main.models.Plugin.pluginCanReadAuthblob` to be true.
"""
if not request.plugin.pluginCanReadAuthblob: if not request.plugin.pluginCanReadAuthblob:
ret = rc.FORBIDDEN ret = rc.FORBIDDEN
ret.write("\nThis plugin is not allowed to read the users authblob\n") ret.write("\nThis plugin is not allowed to read the users authblob\n")
@ -159,6 +204,16 @@ class AuthBlobHandler(BaseHandler):
@requirePlugin @requirePlugin
@manglePluginPerms @manglePluginPerms
def create(self, request): def create(self, request):
"""Write the users authblob.
To use this function the plugin needs
:attr:`main.models.Plugin.pluginCanWriteAuthblob` to be true.
.. Note:: In fact this method *should* be an update method, but for
compability reasons (wget usage) it was decided to make
this accessible as a create (POST) hook.
"""
if not request.plugin.pluginCanWriteAuthblob: if not request.plugin.pluginCanWriteAuthblob:
ret = rc.FORBIDDEN ret = rc.FORBIDDEN
ret.write("\nThis plugin is not allowed to write the users authblob\n") ret.write("\nThis plugin is not allowed to write the users authblob\n")
@ -172,11 +227,22 @@ class AuthBlobHandler(BaseHandler):
return rc.ALL_OK return rc.ALL_OK
class AuthUserHandler(BaseHandler): class AuthUserHandler(BaseHandler):
""" Handler for mapping an authblob to a user
This handler is only available to plugins and only if
:attr:`unique authblob <main.models.Plugin.uniqueAuthblob>`
is set for this plugin. Then it will provide a mapping from
an authblob to a specifig user.
"""
allowed_methods = ('GET') allowed_methods = ('GET')
fields = ('id', 'username') fields = ('id', 'username')
@requirePlugin @requirePlugin
def read(self, request): def read(self, request):
"""Returns an user if one can be found, else rc.GONE
- authblob: [required] Authblob to search
"""
if not request.plugin.uniqueAuthblob: if not request.plugin.uniqueAuthblob:
ret = rc.BAD_REQUEST ret = rc.BAD_REQUEST
ret.write("\nThis plugin does not support unique auth blobs, therefore we can't identify an user uniquely by its authblob\n") ret.write("\nThis plugin does not support unique auth blobs, therefore we can't identify an user uniquely by its authblob\n")
@ -192,10 +258,19 @@ class AuthUserHandler(BaseHandler):
return rc.NOT_FOUND return rc.NOT_FOUND
class ConfigHandler(BaseHandler): class ConfigHandler(BaseHandler):
""" Handler for API configuration values
This handler provides some API related configuration values"""
allowed_methods = ('GET',) allowed_methods = ('GET',)
def read(self, request): def read(self, request):
"""Get API configuration values
Currently returns the API version and mediaurl (where to
find images etc.)
"""
return { return {
'version': '0.1', 'version': '0.1',
'mediaurl': 'http://devcat.someserver.de:13805/media', 'mediaurl': 'http://devcat.someserver.de:13805/media',
} }

13
k4ever/api2/helper.py Normal file
View File

@ -0,0 +1,13 @@
from decimal import Decimal, InvalidOperation
def getInt(d, key, default):
try:
return int(d.get(key, default))
except ValueError:
return default
def getDecimal(d, key, default):
try:
return Decimal(d.get(key, default))
except InvalidOperation:
return default

1
k4ever/docs/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
_build/*

View File

@ -16,7 +16,13 @@ import sys, os
# If extensions (or modules to document with autodoc) are in another directory, # If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the # add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here. # documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.append(os.path.abspath('.')) sys.path.append(os.path.abspath('..'))
sys.path.append(os.path.abspath('../..'))
# django specific configuration
from django.conf import settings
settings.configure()
# -- General configuration ----------------------------------------------------- # -- General configuration -----------------------------------------------------
@ -38,7 +44,7 @@ master_doc = 'index'
# General information about the project. # General information about the project.
project = u'k4ever' project = u'k4ever'
copyright = u'2011, TrollWare, FarbDev, others' copyright = u'2011, TrollWare, FarbDev and others'
# The version info for the project you're documenting, acts as replacement for # The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the # |version| and |release|, also used in various other places throughout the
@ -173,7 +179,7 @@ htmlhelp_basename = 'k4everdoc'
# (source start file, target name, title, author, documentclass [howto/manual]). # (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [ latex_documents = [
('index', 'k4ever.tex', u'k4ever Documentation', ('index', 'k4ever.tex', u'k4ever Documentation',
u'TrollWare, FarbDev, others', 'manual'), u'TrollWare, FarbDev and others', 'manual'),
] ]
# The name of an image file (relative to this directory) to place at the top of # The name of an image file (relative to this directory) to place at the top of
@ -196,3 +202,4 @@ latex_documents = [
# Example configuration for intersphinx: refer to the Python standard library. # Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'http://docs.python.org/': None} intersphinx_mapping = {'http://docs.python.org/': None}

134
k4ever/docs/django/api.rst Normal file
View File

@ -0,0 +1,134 @@
API
===
- explain a bit how piston/REST works
- how to access the read/write/put/create functions
- what this api does and what not
Authentication
--------------
- how does authentication work
- what is the plugin authentication
- when does a plugin need an user?
- how to change user names
URLs
----
For more information about a specific method you can click on the url/method to get
to the handler or the responsible method for more documentation or code.
**buyable/**
:class:`item/[itemId]/ <api2.handlers.BuyableItemHandler>`
:func:`GET <api2.handlers.BuyableItemHandler.read>`
Get a specific item or a full/type item list.
========= =======================
Parameter Description
========= =======================
type item belonging to type-group
========= =======================
:func:`POST <api2.handlers.BuyableItemHandler.create>`
Buy a :class:`Buyable <buyable.models.Buyable>` (requires an ItemId)
========= =======================================================
Parameter Description
========= =======================================================
deposit Set to > 0 if you want to buy with deposit (default 0)
amount amount of items to buy (default 1)
========= =======================================================
:class:`types/ <api2.handlers.BuyableTypeHandler>`
:func:`GET <api2.handlers.BuyableTypeHandler.read>`
List all types which an item can belong to
:class:`history/ <api2.handlers.HistoryHandler>`
:func:`GET <api2.handlers.HistoryHandler.read>`
List the users last orders
========= =================
Parameter Description
========= =================
num Number of entries
========= =================
**account/**
**transactions/** or **transfers/**
:class:`transact/ or transfer/ <api2.handlers.TransactionTransactHandler>`
:func:`GET <api2.handlers.TransactionTransactHandler.read>`
List the users last transactions
========= =================
Parameter Description
========= =================
num Number of entries
========= =================
:func:`POST <api2.handlers.TransactionTransactHandler.create>`
Transact money to an account
========= =================
Parameter Description
========= =================
amount [required] Amount to add to the users account
type [required] Type of transaction (id)
========= =================
:class:`types/ <api2.handlers.TransactionTypeHandler>`
:func:`GET <api2.handlers.TransactionTypeHandler.read>`
List all available :class:`Transaction Types <buyable.models.TransactionType>`
:class:`balance/ <api2.handlers.AccountBalanceHandler>`
:func:`GET <api2.handlers.AccountBalanceHandler.read>`
Get users account balance
**auth/**
:class:`blob/ <api2.handlers.AuthBlobHandler>`
:func:`GET <api2.handlers.AuthBlobHandler.read>`
Return authblob if allowed or auth if str given
(currentyl only allowed for Plugin users)
========= =================
Parameter Description
========= =================
blob blob to get user from / auth user with, returns User or NULL
========= =================
:func:`POST <api2.handlers.AuthBlobHandler.create>`
Set authblob if allowed
:class:`user/ <api2.handlers.AuthUserHandler>`
:func:`GET <api2.handlers.AuthUserHandler.read>`
get user by authblob string - this function works only when plugin
has the :attr:`unique authblob <main.models.Plugin.uniqueAuthblob>` flag set
========= =================
Parameter Description
========= =================
authblob [required] authblob to sear
========= =================
:class:`config/ <api2.handlers.ConfigHandler>`
:func:`GET <api2.handlers.ConfigHandler.read>`
Display API configuration variables
Handler
-------
.. automodule:: api2.handlers
:members:
Examples
--------
- how to use the api
- examples with... wget.. python-rest?
As normal user
^^^^^^^^^^^^^^
.. note:: there will be cat content
wget
""""
wget part
As a plugin
^^^^^^^^^^^

View File

@ -11,6 +11,8 @@ Contents:
.. toctree:: .. toctree::
:maxdepth: 2 :maxdepth: 2
django/api
Indices and tables Indices and tables
================== ==================