Python client for a DjangoRestFramework based web site
Project description
Django Rest Framework Python API Package
A python library for interacting with any Django web server base on django-rest-framework
Package is based on https://github.com/samgiles/slumber, but enhanced to support tokens and other features.
Features
-
Support for tokens. Both
- django-rest-framework's own tokens:
rest_framework.authentication.TokenAuthentication
- JWT tokens:
rest_framework_jwt.authentication.JSONWebTokenAuthentication
- django-rest-framework's own tokens:
-
Support for arguments (e.g.
?name1=val1&name2=val2
) -
Support for custom methods (e.g. ``/ap1/v1/object/custom/`)
Requirements
restframeworkclient requires the following modules.
* Python 3.7+
* requests
Installation
python3 -m venv ~/.virtualenv/drf_client
source ~/.virtualenv/drf_client/bin/activate
pip install django-rest-framework-client
Usage Guide
Example
from drf_client.connection import Api as RestApi
options = {
'DOMAIN': 'http://127.0.0.1:8000',
'API_PREFIX': 'api/v1',
'TOKEN_TYPE': 'jwt',
'TOKEN_FORMAT': 'JWT {token}',
'USERNAME_KEY': 'username',
'LOGIN': 'auth/login/',
'LOGOUT': 'auth/logout/',
}
c = RestApi(options)
ok = c.login(username=username, password=password)
if ok:
# GET some data
my_object = c.myresourcename.get()
for obj in my_object['results']:
pprint(obj)
logger.info('------------------------------')
payload = {
'data1': 'val1',
'data2': 'val2',
}
resp = c.myresourcename.post(data=payload)
# If the URL includes "-", add under parenthesis:
# GET: /api/v1/someresource/some-path/
my_object = c.someresource('some-path').get()
Django Setup
Client assumes by default that all urls should end with a slash (tested with the default
router: routers.DefaultRouter()
)
Apart from the regular Django and Rest Framework setup, this package currently relies on the following custom login and logout API functions:
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'email', 'username')
class APILogoutViewSet(APIView):
permission_classes = (permissions.IsAuthenticated,)
def post(self, request, format=None):
logout(request)
return Response({}, status=status.HTTP_204_NO_CONTENT)
urlpatterns = [
url(r'^auth/logout/$', APILogoutViewSet.as_view(), name='api-logout'),
Helpers
BaseMain Helper
This class helps write a script with a flexible template that helps avoid having to duplicate boiler plate code from script to script.
The class assumes that most scripts include the basic folliwing flow:
# Parse arguments
# Setup LOG configuration
# Login
# Do something after logging in
The opinionated class will execute the basic main flow:
# Initialize arguments and LOG in the init function
# Add additional arguments by implemenenting self.add_extra_args()
self.domain = self.get_domain()
self.api = Api(self.domain)
self.before_login()
ok = self.login()
if ok:
self.after_login()
Any of the above functions can be overwritten by derving from this class.
Here is a sample script:
from drf_client.helper.base_main import BaseMain
class MyScript(BaseMain):
def add_extra_args(self):
# Add extra positional argument (as example)
self.parser.add_argument('foo', metavar='foo', type=str, help='RTFM')
def before_login(self):
logger.info('-----------')
def after_login(self):
# Main function to OVERWITE and do real work
do_some_real_work(self.api, self.args)
if __name__ == '__main__':
work = MyScript()
work.main()
Given the above script, you will run it with
python myscript.py -u <USERNAME> --foo bar
Development
To test, run python setup.py test or to run coverage analysis:
python3 -m venv .virtualenv/drf_client
source .virtualenv/drf_client/bin/activate
pip install -r requirements-test.txt
pip install -e .
coverage run --source=iotile_cloud setup.py test
coverage report -m
You can also use py.test:
py.test
Deployment
pip install -r requirements-build.txt
python setup.py sdist bdist_wheel
twine check dist/*
# Publish
twine upload dist/*
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for django-rest-framework-client-0.4.1.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | 372c9ed384777689d5e53657aeac4ac7f66df4bbf8fefae4f636d29aaf39645f |
|
MD5 | eba039b33826b3b3f60bf2c98f6ce351 |
|
BLAKE2b-256 | b2343a5d09f22defde90256d15d64408502e378c8bf44820fc1fc7bdaf0d1974 |
Hashes for django_rest_framework_client-0.4.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 208205f4f3c770d8c8b0009afa0f63d156bd67aa32f29bc2ff09f82c1aaa5e7c |
|
MD5 | 6cc6873b6f37033826347667d7252888 |
|
BLAKE2b-256 | 803e1ffa29da5b4eb1d23f2bb94010e5fb14ccea26c095311a377188b4735bb2 |