fixed linter issues and store credentials cookie in the session object (#1526)

* fixed issues

* fixed issues and stored credentials cookies inside the session

* fixed tests
main
Andrey Zhavoronkov 6 years ago committed by GitHub
parent 214eeada7d
commit 3caae98b5b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -36,9 +36,13 @@ def _get_kwargs():
parser.add_argument('--show-image-delay', default=0, type=int, help='Displays the images for a set duration in milliseconds, default is until a key is pressed') parser.add_argument('--show-image-delay', default=0, type=int, help='Displays the images for a set duration in milliseconds, default is until a key is pressed')
parser.add_argument('--serialize', default=False, action='store_true', help='Try to serialize the result') parser.add_argument('--serialize', default=False, action='store_true', help='Try to serialize the result')
parser.add_argument('--show-labels', action='store_true', help='Show the labels on the window') parser.add_argument('--show-labels', action='store_true', help='Show the labels on the window')
return vars(parser.parse_args()) return vars(parser.parse_args())
def _init_django(settings):
import django
os.environ['DJANGO_SETTINGS_MODULE'] = settings
django.setup()
def random_color(): def random_color():
rgbl=[255,0,0] rgbl=[255,0,0]
@ -63,10 +67,7 @@ def find_min_y(array):
return array[index] return array[index]
def _get_docker_files(model_name: str, task_id: int): def _get_docker_files(model_name: str, task_id: int):
os.environ['DJANGO_SETTINGS_MODULE'] = 'cvat.settings.development' _init_django('cvat.settings.development')
import django
django.setup()
from cvat.apps.auto_annotation.models import AnnotationModel from cvat.apps.auto_annotation.models import AnnotationModel
from cvat.apps.engine.models import Task as TaskModel from cvat.apps.engine.models import Task as TaskModel
@ -74,7 +75,7 @@ def _get_docker_files(model_name: str, task_id: int):
task = TaskModel(pk=task_id) task = TaskModel(pk=task_id)
model = AnnotationModel.objects.get(name=model_name) model = AnnotationModel.objects.get(name=model_name)
images_dir = task.get_data_dirname() images_dir = task.data.get_data_dirname()
py_file = model.interpretation_file.name py_file = model.interpretation_file.name
mapping_file = model.labelmap_file.name mapping_file = model.labelmap_file.name
@ -82,6 +83,7 @@ def _get_docker_files(model_name: str, task_id: int):
bin_file = model.weights_file.name bin_file = model.weights_file.name
image_files = [] image_files = []
images_dir = os.path.abspath(images_dir)
for root, _, filenames in os.walk(images_dir): for root, _, filenames in os.walk(images_dir):
for filename in fnmatch.filter(filenames, '*.jpg'): for filename in fnmatch.filter(filenames, '*.jpg'):
image_files.append(os.path.join(root, filename)) image_files.append(os.path.join(root, filename))
@ -94,7 +96,7 @@ def main():
py_file = kwargs.get('py') py_file = kwargs.get('py')
bin_file = kwargs.get('bin') bin_file = kwargs.get('bin')
mapping_file = kwargs.get('json') mapping_file = os.path.abspath(kwargs.get('json'))
xml_file = kwargs.get('xml') xml_file = kwargs.get('xml')
model_name = kwargs.get('model_name') model_name = kwargs.get('model_name')
@ -233,9 +235,7 @@ def main():
cv2.destroyWindow(str(index)) cv2.destroyWindow(str(index))
if kwargs['serialize']: if kwargs['serialize']:
os.environ['DJANGO_SETTINGS_MODULE'] = 'cvat.settings.production' _init_django('cvat.settings.production')
import django
django.setup()
from cvat.apps.engine.serializers import LabeledDataSerializer from cvat.apps.engine.serializers import LabeledDataSerializer

@ -28,9 +28,8 @@ def main():
args = parser.parse_args() args = parser.parse_args()
config_log(args.loglevel) config_log(args.loglevel)
with requests.Session() as session: with requests.Session() as session:
session.auth = args.auth
api = CVAT_API_V1('%s:%s' % (args.server_host, args.server_port)) api = CVAT_API_V1('%s:%s' % (args.server_host, args.server_port))
cli = CLI(session, api) cli = CLI(session, api, args.auth)
try: try:
actions[args.action](cli, **args.__dict__) actions[args.action](cli, **args.__dict__)
except (requests.exceptions.HTTPError, except (requests.exceptions.HTTPError,

@ -17,9 +17,10 @@ log = logging.getLogger(__name__)
class CLI(): class CLI():
def __init__(self, session, api): def __init__(self, session, api, credentials):
self.api = api self.api = api
self.session = session self.session = session
self.login(credentials)
def tasks_data(self, task_id, resource_type, resources): def tasks_data(self, task_id, resource_type, resources):
""" Add local, remote, or shared files to an existing task. """ """ Add local, remote, or shared files to an existing task. """
@ -144,6 +145,14 @@ class CLI():
"with annotation file {} finished".format(filename) "with annotation file {} finished".format(filename)
log.info(logger_string) log.info(logger_string)
def login(self, credentials):
url = self.api.login
auth = {'username': credentials[0], 'password': credentials[1]}
response = self.session.post(url, auth)
response.raise_for_status()
if 'csrftoken' in response.cookies:
self.session.headers['X-CSRFToken'] = response.cookies['csrftoken']
class CVAT_API_V1(): class CVAT_API_V1():
""" Build parameterized API URLs """ """ Build parameterized API URLs """
@ -174,3 +183,7 @@ class CVAT_API_V1():
def tasks_id_annotations_filename(self, task_id, name, fileformat): def tasks_id_annotations_filename(self, task_id, name, fileformat):
return self.tasks_id(task_id) + '/annotations?format={}&filename={}' \ return self.tasks_id(task_id) + '/annotations?format={}&filename={}' \
.format(fileformat, name) .format(fileformat, name)
@property
def login(self):
return self.base + 'auth/login'

@ -10,7 +10,6 @@ import unittest
from django.conf import settings from django.conf import settings
from PIL import Image from PIL import Image
from requests.auth import HTTPBasicAuth
from rest_framework.test import APITestCase, RequestsClient from rest_framework.test import APITestCase, RequestsClient
from cvat.apps.engine.tests._test_rest_api import (create_db_users, from cvat.apps.engine.tests._test_rest_api import (create_db_users,
@ -22,9 +21,9 @@ class TestCLI(APITestCase):
@unittest.mock.patch('sys.stdout', new_callable=io.StringIO) @unittest.mock.patch('sys.stdout', new_callable=io.StringIO)
def setUp(self, mock_stdout): def setUp(self, mock_stdout):
self.client = RequestsClient() self.client = RequestsClient()
self.client.auth = HTTPBasicAuth('admin', 'admin') self.credentials = ('admin', 'admin')
self.api = CVAT_API_V1('testserver') self.api = CVAT_API_V1('testserver')
self.cli = CLI(self.client, self.api) self.cli = CLI(self.client, self.api, self.credentials)
self.taskname = 'test_task' self.taskname = 'test_task'
self.cli.tasks_create(self.taskname, self.cli.tasks_create(self.taskname,
[{'name' : 'car'}, {'name': 'person'}], [{'name' : 'car'}, {'name': 'person'}],

Loading…
Cancel
Save