utils.py
1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import json
from django.contrib.auth import get_user_model
from rest_framework.test import APIClient
from .fixtures import create_user
JSON_CONTENT_TYPE = "application/json"
JSON_API_CONTENT_TYPE = "application/vnd.api+json"
JSON_API_ACCEPT_HEADER = "application/vnd.api+json"
def get_authenticated_client(user=None):
client = APIClient()
if user is not None:
client.force_authenticate(user=user)
return client
def get(url, params=None, headers=None, user_logged=None):
url += "?{}".format(params) if params else ''
client = get_authenticated_client(user_logged)
if headers is None:
headers = {'HTTP_ACCEPT': JSON_API_ACCEPT_HEADER}
response = client.get(url, **headers)
return response
def post(url, data=None, content_type=JSON_API_CONTENT_TYPE, headers=None, user_logged=None):
url = url + '/' if not url.endswith('/') else url
client = get_authenticated_client(user_logged)
if headers is None:
headers = {'HTTP_ACCEPT': JSON_API_ACCEPT_HEADER}
response = client.post(url, data=json.dumps(data), content_type=content_type, **headers)
return response
def patch(url, data=None, content_type=JSON_API_CONTENT_TYPE, headers=None, user_logged=None):
url = url + '/' if not url.endswith('/') else url
client = get_authenticated_client(user_logged)
if headers is None:
headers = {'HTTP_ACCEPT': JSON_API_ACCEPT_HEADER}
response = client.patch(url, data=json.dumps(data), content_type=content_type, **headers)
return response
def delete(url, data=None, content_type=JSON_API_CONTENT_TYPE, headers=None, user_logged=None):
url = url + '/' if not url.endswith('/') else url
client = get_authenticated_client(user_logged)
if headers is None:
headers = {'HTTP_ACCEPT': JSON_API_ACCEPT_HEADER}
response = client.delete(url, data=json.dumps(data), content_type=content_type, **headers)
return response