index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
56,002
nathananderson03/soundproof
refs/heads/master
/soundproof/instagram.py
#pylint: skip-file from __future__ import absolute_import, print_function import sys import pickle import time import datetime import re import json import urlparse import traceback from httplib import ResponseNotReady from httplib2 import ServerNotFoundError from django.conf import settings from django.core.urlresolvers import reverse from django.contrib.sites.models import Site from django.db import IntegrityError from django.db.models import Max from django.utils.timezone import now from django.core.cache import cache import requests from instagram import InstagramAPI, InstagramAPIError, InstagramClientError import pytz from .models import ( InstagramImage, InstagramTag, User, DisplayEngagementLog, DisplayFollowers, Display ) from . import util api = InstagramAPI( client_id=settings.INSTAGRAM_ID, client_secret=settings.INSTAGRAM_SECRET, ) IGNORE_ERRORS = ( 'invalid media id', 'you cannot view this resource', ) class Subscriptions(dict): def __init__(self, api): super(Subscriptions, self).__init__() self.update(api.list_subscriptions()) @property def tags(self): return set([d['object_id'] for d in self['data']]) def tag_id(self, tag): for s in self['data']: if s['object_id'] == tag: return s['id'] raise KeyError def subscriptions(): return Subscriptions(api) def add_subscription(tag): site = Site.objects.get_current() kwargs = { 'object':'tag', 'object_id':str(tag), 'aspect':'media', 'callback_url':'http://{}{}'.format(site.domain, reverse('instagram_callback')), 'verify_token':settings.INSTAGRAM_VERIFY_TOKEN, } api.create_subscription(**kwargs) def remove_subscription(id): api.delete_subscriptions(id=int(id)) def _extract_max_tag_id(url): parms = urlparse.parse_qs(urlparse.urlparse(url).query) return int(parms.get('max_tag_id')[0]) def _update_max_tag_id(tag, max_tag_id): model_tag, _ = InstagramTag.objects.get_or_create(name=tag) if max_tag_id > model_tag.max_tag_id: model_tag.max_tag_id = max_tag_id model_tag.save(update_fields=['max_tag_id']) def _iterate_tag(tag, max_tag_id): """A generator allowing iteration over new media for a tag. """ '''I've hacked this up to just fetch 10 images then quit - it seemed like it was just running back through older and older images forever - max_tag_id is confusing :( -dg''' max_tag = int(max_tag_id) if max_tag_id else None while True: images, next_url = api.tag_recent_media(tag_name=tag, min_tag_id=max_tag_id) # continue until we have no more images if not len(images): break for image in images: yield image try: if not next_url: break max_tag_id = _extract_max_tag_id(next_url) # we need to take the max tag id and make it our # new min tag id # so we go forwards # update the max id tag _update_max_tag_id(tag, max_tag_id) except (KeyboardInterrupt, SystemExit): raise except: print(traceback.format_exc()) if max_tag_id < max_tag: raise ValueError('Going backwards') max_tag = max_tag_id def _scrape_tag(tag, count): """A generator allowing iteration over historic media for a tag. """ loaded = 0 while count: images, next_url = api.tag_recent_media(tag_name=tag, count=count) loaded += len(images) count -= len(images) for image in images: yield image try: if not next_url: print("No more pages") break # max_tag_id will be max id for next page in PAST # ie max_tag_id will be decremented max_tag_id = _extract_max_tag_id(next_url) # update the max id tag _update_max_tag_id(tag, max_tag_id) except (KeyboardInterrupt, SystemExit): raise except: print(traceback.format_exc()) def _add_instagram_image(tags, im_data): try: url = im_data.images['standard_resolution'].url url = url.replace('https://','http://') print('Instagram image: {url}'.format(url=url)) cached_url = util.cache_image(url) meta = {} try: meta['user'] = im_data.user.username except: pass try: meta['caption'] = im_data.caption.text except: pass user, _ = User.objects.get_or_create(username=im_data.user.username) user.set_mug_url(im_data.user.profile_picture) print('Creating DB instagram image') im = InstagramImage.objects.create( page_url=im_data.link, url=url, cached_url=cached_url, instagram_id=im_data.id, meta=json.dumps(meta), user=user, remote_timestamp=im_data.created_time.replace(tzinfo=pytz.utc), like_count=im_data.like_count, comment_count=im_data.comment_count, ) tag_image(im, im_data) print('Done') return im except IntegrityError: pass except (KeyboardInterrupt, SystemExit): raise except: print(traceback.format_exc()) raise def tag_image(im, im_data): print('Creating DB instagram tags') # we need all of the tags for reporting if not hasattr(im_data,'tags'): return for tag_data in im_data.tags: try: print('Creating DB instagram tag {}'.format(tag_data.name)) im.tags.add(InstagramTag.objects.get_or_create(name=tag_data.name)[0]) except: pass def update_instagram_tag(tag, max_tag_id=None, limit=None): if not max_tag_id: try: # attempt to get the max tag id it = InstagramTag.objects.get(name=tag) max_tag_id = it.max_tag_id except: pass print('Updating {tag}'.format(tag=tag)) for im_data in _iterate_tag(tag, max_tag_id): try: _add_instagram_image([tag], im_data) pass except (KeyboardInterrupt, SystemExit): raise except: pass def scrape_instagram_tag(tag, count=200): print('Scraping {tag} for {count} images'.format(tag=tag, count=count)) for im_data in _scrape_tag(tag, count): try: _add_instagram_image([tag], im_data) except (KeyboardInterrupt, SystemExit): raise except: pass def instagram_url_to_instagram_id(url): query_url = "http://api.instagram.com/oembed?url={}".format(url) data = requests.get(query_url).json() id = data['media_id'] return id def iconosquare_url_to_instagram_id(url): id = iconosquare_url_to_instagram_id.re.match(url).group('id') return id "http://iconosquare.com/p/947328653831618359_1692452990" iconosquare_url_to_instagram_id.re = re.compile(r"http://iconosquare.com/p/(?P<id>[\d_]+)") def url_to_instagram_id(url): try: return instagram_url_to_instagram_id(url) except: pass try: return iconosquare_url_to_instagram_id(url) except: pass raise ValueError('Unrecognised URL') def add_instagram_image(tags, id=None, url=None): if url: id = url_to_instagram_id(url) data = api.media(id) return _add_instagram_image(tags, data) def get_report(tags, period): if True: with open('fdsa.pickle') as fp: state = pickle.load(fp) else: state = { 'posters': set(), 'followers': set(), 'follower_counts': {}, 'commenters': set(), 'likers': set(), 'comment_count': 0, 'like_count': 0, 'last_processed': 0, 'deleted_count': 0, 'img_inaccessible_count': 0, 'followers_inaccessible_count': 0, 'like_distribution':{}, 'comment_distribution':{}, 'most_commented':[], 'most_liked':[], } images = InstagramImage.objects\ .filter(tags__name__in=tags)\ .filter(created__gte=period[0])\ .filter(created__lte=period[1])\ .filter(id__gt=state['last_processed'])\ .order_by('id') def serialise(state): with open('fdsa.pickle','w') as fp: pickle.dump(state, fp) def process_image(image, state): try: data = wrap_api(api.media, (image.instagram_id,)) except InstagramAPIError as e: msg = getattr(e, 'error_message', None) if msg == 'invalid media id': state['deleted_count'] += 1 return elif msg == 'you cannot view this resource': state['img_inaccessible_count'] += 1 return else: raise except: print(image.instagram_id) raise # TODO instagram API only returns subset of likes/comments? #print(data.comments) #for comment in data.comments: # date = comment.created_at.replace(tzinfo=pytz.utc) # if date >= period[0] and date <= period[1]: # state['comment_count'] += 1 # state['commenters'].add(comment.user.id) #count = len(data.comments) #if count not in state['comment_distribution']: # state['comment_distribution'][count] = 0 #state['comment_distribution'][count] += 1 #print(data.likes) #for like in data.likes: # #likes dont have dates on them # state['like_count'] += 1 # state['likers'].add(like.id) #count = len(data.likes) #if count not in state['like_distribution']: # state['like_distribution'][count] = 0 #state['like_distribution'][count] += 1 state['comment_count'] += data.comment_count state['like_count'] += data.like_count state['most_commented'].append({ 'url':image.page_url, 'count':data.comment_count, }) state['most_liked'].append({ 'url':image.page_url, 'count':data.like_count, }) state['most_commented'].sort(key=lambda x:x['count'], reverse=True) state['most_liked'].sort(key=lambda x:x['count'], reverse=True) state['most_commented'] = state['most_commented'][0:10] state['most_liked'] = state['most_liked'][0:10] if image.user.username not in state['posters']: state['posters'].add(image.user.username) #try: # state['follower_counts'][image.user.username] =\ # count_followers2(image.user.username) #except InstagramAPIError as e: # pass state['last_processed'] = image.id processed = 0 #for image in images: # process_image(image, state) # serialise(state) # processed += 1 # if processed % 100 == 0: # sys.stdout.write(str(processed)) # else: # sys.stdout.write('.') # sys.stdout.flush() print('images',images.count()) print('commenters',len(state['commenters'])) print('comments',state['comment_count']) print('likers',len(state['likers'])) print('likes',state['like_count']) print('followers',len(state['followers'])) print('posters',len(state['posters'])) print('most commented') print('\n'.join([str(x) for x in state['most_commented']])) print('most liked') print('\n'.join([str(x) for x in state['most_liked']])) #print('\n'.join([str(x) for x in state['comment_distribution'].items()])) #print('\n'.join([str(x) for x in state['like_distribution'].items()])) if len(state['follower_counts']): print( 'average followers per poster', sum(state['follower_counts'].values())/len(state['follower_counts']) ) print( 'max followers', max(state['follower_counts'].values()) ) followers = state['follower_counts'].items() followers.sort(key=lambda x: x[1], reverse=True) for follower_id, count in followers[:10]: print(follower_id) continue user_data = wrap_api(api.user, (follower_id,)) #print(user_data. def count_followers(user, cursor=None, page_limit=None): print('count followers {}'.format(user.username)) print('got cursor {}'.format(cursor)) user_id = get_id_from_username(user.username) pages_parsed = 0 ret = set() while True: try: if cursor: followers, next_page_url = wrap_api( api.user_followed_by, (user_id,), {'cursor':cursor}, ) else: followers, next_page_url = wrap_api( api.user_followed_by, (user_id,), ) except InstagramAPIError as e: if e.error_message in ( 'you cannot view this resource',): break else: print(traceback.format_exc()) break # storing followers in db is too slow # for follower_data in followers: # follower, _ = User.objects.get_or_create( # username=follower_data.username, # ) # follower.set_mug_url(follower_data.profile_picture) # Follower.objects.create( # follower=follower, # followee=user, # ) [ret.add(f.id) for f in followers] if next_page_url: pages_parsed += 1 parms = urlparse.parse_qs(urlparse.urlparse(next_page_url).query) new_cursor = parms.get('cursor')[0] if new_cursor == cursor: cursor = None break else: cursor = new_cursor if pages_parsed == page_limit: break else: cursor = None break return cursor, ret def wrap_api(f, args, kwargs={}): while True: try: data = f(*args, **kwargs) break except (ResponseNotReady, ServerNotFoundError): print('bad response') time.sleep(1) except InstagramAPIError as e: if e.error_message == 'Your client is making too many request per second': print('limited') time.sleep(60) else: raise except InstagramClientError as e: if e.error_message == 'Unable to parse response, not valid JSON.': print('json error') time.sleep(1) else: raise return data def get_id_from_username(username): key = 'id_for_user_{}'.format(username) ret = cache.get(key) if not ret: try: for hit in wrap_api(api.user_search, (username,)): if hit.username == username: ret = hit.id cache.set(key, ret, 3600) except: pass return ret def refresh_social(img): print('refreshing like/comment counts for {}'.format(img.page_url)) try: data = wrap_api(api.media, (img.instagram_id,)) InstagramImage.objects.filter(id=img.id).update( like_count=data.like_count, comment_count=data.comment_count, last_updated=now(), ) tag_image(img, data) except InstagramAPIError as e: msg = getattr(e, 'error_message', None) if msg not in IGNORE_ERRORS: print(msg) #raise InstagramImage.objects.filter(id=img.id).update( last_updated=now(), ) followers_state = {} def refresh_users(): '''keep user follower sets up to date only process one page of one user at a time return True to indicate more work to be done''' cutoff = now() - datetime.timedelta( seconds=settings.REFRESH_INSTAGRAM_USER_FREQUENCY) morework = False for display in Display.objects.filter(active=True): users = User.objects\ .filter(image__instagramimage__tags__in=display.get_split_tags())\ .filter(last_updated__lt=cutoff)\ .order_by('last_updated')\ .distinct() if users.count(): user = users[0] next_page_cursor, new_followers = count_followers( user, page_limit=10, cursor=followers_state.get(user.id) ) key = 'display-followers-{}'.format(display.id) display_followers = cache.get(key) if display_followers is None: display_followers = unserialise_followers(display) display_followers = display_followers.union(new_followers) cache.set(key, display_followers, 86400) #one day if not next_page_cursor: print('no more pages') # no more pages # store numeric user count per user try: user_id = get_id_from_username(user.username) user_data = wrap_api(api.user, (user_id,)) user.follower_count = user_data.counts['followed_by'] print(user.follower_count) except: print(traceback.format_exc()) pass user.last_updated = now() user.save(update_fields=('last_updated','follower_count')) # delete this user's cursor from state if user.id in followers_state: del followers_state[user.id] else: print('next page is {}'.format(next_page_cursor)) followers_state[user.id] = next_page_cursor serialise_followers(display) morework = morework or users.count() > 1 return morework or len(followers_state) def unserialise_followers(display): try: return set(DisplayFollowers.objects\ .get(display=display).followers.split(',')) except: return set() def serialise_followers(display): control_key = 'serialised-followers-{}'.format(display.id) if not cache.get(control_key): print('serialising display followers to db') key = 'display-followers-{}'.format(display.id) followers = cache.get(key, set()) db_item, created = DisplayFollowers.objects.get_or_create(display=display) db_item.followers = ','.join(followers) db_item.save() cache.set(control_key, True, 60*5) #serialise every 5 mins def refresh_images(): '''keep image like/comment counts up to date''' cutoff = now() - \ datetime.timedelta(seconds=settings.REFRESH_INSTAGRAM_IMAGE_FREQUENCY) morework = False for display in Display.objects.filter(active=True): images = display.images()\ .filter(last_updated__lte=cutoff)\ .order_by('last_updated') if images.count(): refresh_social(images[0]) morework |= images.count() > 1 return morework def log_engagement(): '''save a snapshot of like/comment counts for each display every 15 minutes''' if not cache.get('logged_engagement_time'): for display in Display.objects.filter(active=True): display.log_stats() cache.set('logged_engagement_time', True, settings.LOG_ENGAGEMENT_FREQUENCY)
{"/soundproof/admin.py": ["/soundproof/models.py"], "/microsite/urls.py": ["/microsite/views.py"], "/soundproof/instagram.py": ["/soundproof/models.py"], "/soundproof/migrations/0001_initial.py": ["/soundproof/models.py"], "/soundproof/management/commands/refresh_images.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/report.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/instagram_daemon.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/urls.py": ["/soundproof/views.py"]}
56,003
nathananderson03/soundproof
refs/heads/master
/soundproof/migrations/0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import soundproof.models from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Display', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=50)), ('slug', models.SlugField()), ('tile_width', models.CharField(default=b'10vw', max_length=50, blank=True)), ('tile_margin', models.CharField(default=b'0%', max_length=50, blank=True)), ('background_color', models.CharField(max_length=50, blank=True)), ('css', models.TextField(blank=True)), ('tags', models.TextField(blank=True)), ('seed_urls', models.TextField(help_text=b'image urls (instagram / iconosquare) to be automatically downloaded and approved', blank=True)), ('moderation', models.CharField(default=b'off', max_length=50, choices=[(b'off', b'No moderation, all images are displayed'), (b'whitelist', b'Only show approved images'), (b'blacklist', b'Show all but rejected images')])), ('speed', models.PositiveIntegerField(default=5, help_text=b'minimum time between loading new images')), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='DisplayImage', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('approved', models.BooleanField(default=False)), ('timestamp', models.DateTimeField(auto_now=True)), ('display', models.ForeignKey(to='soundproof.Display')), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='Image', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('page_url', models.URLField()), ('url', models.URLField(unique=True)), ('cached_url', models.URLField(blank=True)), ('meta', models.TextField(blank=True)), ('created', models.DateTimeField(auto_now_add=True)), ('last_updated', models.DateTimeField(auto_now_add=True, db_index=True)), ('remote_timestamp', models.DateTimeField(db_index=True)), ], options={ }, bases=(soundproof.models.LoadableImage, models.Model), ), migrations.CreateModel( name='InstagramImage', fields=[ ('image_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='soundproof.Image')), ('instagram_id', models.CharField(max_length=128)), ('like_count', models.PositiveIntegerField(default=0, db_index=True)), ('comment_count', models.PositiveIntegerField(default=0, db_index=True)), ], options={ }, bases=('soundproof.image',), ), migrations.CreateModel( name='InstagramTag', fields=[ ('name', models.CharField(max_length=50, serialize=False, primary_key=True)), ('max_tag_id', models.BigIntegerField(default=0)), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='PhotoFrame', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('url', models.URLField(unique=True)), ('inset_string', models.CommaSeparatedIntegerField(max_length=64, db_column=b'inset')), ('mug_string', models.CommaSeparatedIntegerField(max_length=64, db_column=b'mug')), ('name_string', models.CharField(max_length=64, db_column=b'name')), ('name_colour_string', models.CommaSeparatedIntegerField(max_length=12, db_column=b'name_colour')), ('name_font', models.CharField(max_length=256)), ('name_font_size', models.IntegerField()), ], options={ }, bases=(soundproof.models.LoadableImage, models.Model), ), migrations.CreateModel( name='PrintedPhoto', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created', models.DateTimeField(auto_now_add=True)), ('frame', models.ForeignKey(to='soundproof.PhotoFrame')), ('image', models.ForeignKey(to='soundproof.Image')), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('username', models.CharField(unique=True, max_length=50)), ('mug_url', models.URLField()), ('last_updated', models.DateTimeField(auto_now=True)), ], options={ }, bases=(models.Model,), ), migrations.AddField( model_name='instagramimage', name='tags', field=models.ManyToManyField(to='soundproof.InstagramTag'), preserve_default=True, ), migrations.AddField( model_name='image', name='user', field=models.ForeignKey(to='soundproof.User'), preserve_default=True, ), migrations.AddField( model_name='displayimage', name='image', field=models.ForeignKey(related_name='displayimage', to='soundproof.Image'), preserve_default=True, ), migrations.AlterUniqueTogether( name='displayimage', unique_together=set([('display', 'image')]), ), migrations.AddField( model_name='display', name='admins', field=models.ManyToManyField(to=settings.AUTH_USER_MODEL), preserve_default=True, ), ]
{"/soundproof/admin.py": ["/soundproof/models.py"], "/microsite/urls.py": ["/microsite/views.py"], "/soundproof/instagram.py": ["/soundproof/models.py"], "/soundproof/migrations/0001_initial.py": ["/soundproof/models.py"], "/soundproof/management/commands/refresh_images.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/report.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/instagram_daemon.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/urls.py": ["/soundproof/views.py"]}
56,004
nathananderson03/soundproof
refs/heads/master
/soundproof/models.py
#pylint: skip-file from __future__ import absolute_import, print_function import hashlib import re import os import string import json import time import datetime from django.conf import settings from django.db import models from django.core.urlresolvers import reverse from django.template import Context, Template from django.utils.timezone import now from django.db.models.signals import pre_save, post_save from django.dispatch import receiver from django.core.cache import cache from django.contrib.auth.models import User as AuthUser from . import util MODERATION_TYPES = ( ('off','No moderation, all images are displayed'), ('whitelist','Only show approved images'), ('blacklist','Show all but rejected images'), ) try: if settings.DEFAULT_FILE_STORAGE == 'storages.backends.s3boto.S3BotoStorage': import boto.s3 s3_conn = boto.s3.connect_to_region(settings.AWS['REGION']) s3_bucket = s3_conn.get_bucket(settings.AWS_STORAGE_BUCKET_NAME) except: pass class User(models.Model): username = models.CharField(max_length=50, unique=True) mug_url = models.URLField() follower_count = models.PositiveIntegerField(default=0) # this is when the users follower set was last fetched last_updated = models.DateTimeField(blank=True) def set_mug_url(self, url): if url != self.mug_url: self.mug_url = url self.save(update_fields=['mug_url']) @property def mug(self): return MugImage(self.mug_url) def __unicode__(self): return self.username def save(self, *args, **kwargs): # prioritize fetching followers for new users if not self.last_updated: self.last_updated = now() - datetime.timedelta(weeks=10*52) super(User, self).save(*args, **kwargs) def instagram_page_url(self): return 'https://instagram.com/{}'.format(self.username) class DisplayFollowers(models.Model): display = models.ForeignKey('Display') followers = models.TextField() # comma separated list def __unicode__(self): count = len(self.followers.split(',')) return '{} {}'.format(self.display.name, count) class LoadableImage(object): def load(self): return util.load_image_url(self.get_absolute_url()) class MugImage(LoadableImage): """Convenience class, doesn't do any DB calls """ def __init__(self, url): self.url = url def get_absolute_url(self): return self.url class Image(LoadableImage, models.Model): page_url = models.URLField() url = models.URLField(unique=True) cached_url = models.URLField(blank=True) meta = models.TextField(blank=True) created = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now_add=True, db_index=True) user = models.ForeignKey(User) remote_timestamp = models.DateTimeField(db_index=True) def as_dict(self): return { 'id':self.id, 'src':self.get_image_url, 'meta':json.loads(self.meta), 'remote_ts':self.remote_unixtime, 'page_url':self.page_url, 'age': self.get_pretty_age(), 'user_mug': self.user.mug_url, } @property def get_image_url(self): return self.cached_url or self.url @property def remote_unixtime(self): return time.mktime(self.remote_timestamp.timetuple()) def get_pretty_age(self): delta = now() - self.remote_timestamp seconds = delta.total_seconds() days = round(seconds/86400) weeks = round(days/7) months = round(days/30) created = self.remote_timestamp if months > 1: compareto = created + datetime.timedelta(days=30*months) elif weeks > 1: compareto = created + datetime.timedelta(days=7*weeks) elif days > 1: compareto = created + datetime.timedelta(days=days) else: compareto = now() template = Template('{{created|timesince:compareto}} ago') context = Context({'created':created, 'compareto':compareto}) return template.render(context) def get_absolute_url(self): return self.get_image_url class InstagramImage(Image): instagram_id = models.CharField(max_length=128) tags = models.ManyToManyField('InstagramTag') like_count = models.PositiveIntegerField(default=0, db_index=True) comment_count = models.PositiveIntegerField(default=0, db_index=True) def __unicode__(self): return self.tag_str() def tag_str(self): return ', '.join(self.tags.all().values_list('name',flat=True)) class InstagramTag(models.Model): name = models.CharField(max_length=50, primary_key=True) max_tag_id = models.BigIntegerField(default=0) def get_split_tags(self): # tokenise and strip the tags return [s.lower().strip() for s in self.tags.split(',') if s.strip()] def __unicode__(self): return self.name class Display(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(db_index=True) admins = models.ManyToManyField(AuthUser) tile_width = models.CharField(max_length=50, default='10vw', blank=True) tile_margin = models.CharField(max_length=50, default='0%', blank=True) background_color = models.CharField(max_length=50, blank=True) border_color = models.CharField(max_length=50, default='white') logo = models.ImageField(upload_to='logos', blank=True, null=True) css = models.TextField(blank=True) tags = models.TextField(blank=True, help_text='comma separated list, no spaces, all on one line, no # symbol (eg funny,fail)') seed_urls = models.TextField(blank=True, help_text='image urls (instagram / iconosquare) to be automatically downloaded and approved, comma separated list') moderation = models.CharField(max_length=50, choices=MODERATION_TYPES, default='off') active = models.BooleanField(default=True) # image loading speed = models.PositiveIntegerField(default=5, help_text='Minimum time between loading new images (seconds)') minimum_flips = models.PositiveIntegerField(default=3, help_text='Always flip this many images per load, even if there are no new images') images_to_load = models.CharField(max_length=50, default='5,10', help_text='''How many images to load at a time, for example "5,10" means load 5 images, then 10, then 5, then 10, repeating''') # internal last_updated = models.DateTimeField(auto_now=True) public_analytics = models.BooleanField(default=False, help_text='Can anyone with the URL access the analytics page?') def auth_user(self, user): return user.is_superuser or user in self.admins.all() def tile_hcount(self): return int(100/float(re.sub(r'[^.\d]','',self.tile_width))) def get_absolute_url(self): return reverse('feed', args=(self.slug,)) def get_highest_ts(self): try: tags = self.get_split_tags() img = Image.objects\ .filter(instagramimage__tags__name__in=tags)\ .order_by('-remote_timestamp')[0] return img.remote_unixtime except: return 0 def get_split_tags(self): # tokenise and strip the tags return [s.lower().strip() for s in self.tags.split(',') if s.strip()] def get_split_seed_urls(self): return map(string.strip, self.seed_urls.split(',')) @classmethod def get_unique_tags(cls): tags = set() for d in Display.objects.filter(active=True): tags.update(set(d.get_split_tags())) return tags @classmethod def update_subscriptions(cls): # compare local and subscribed tags # and get the added and removed tags subscriptions = instagram.subscriptions() model_tags = Display.get_unique_tags() sub_tags = subscriptions.tags added = model_tags - sub_tags removed = sub_tags - model_tags # convert removed tags to ids removed_ids = map(subscriptions.tag_id, removed) try: map(instagram.add_subscription, added) map(instagram.remove_subscription, removed_ids) except: pass def process_seed_urls(self): tags = self.get_split_tags() for url in self.get_split_seed_urls(): print('Seed url {}'.format(url)) image = instagram.add_instagram_image(tags=tags, url=url) if image: # approve the images print('Adding approval') di, _ = DisplayImage.objects.get_or_create( display=self, image=image ) di.approved = True di.save() def __unicode__(self): return self.name def admin_links(self): return ( (reverse('grid',args=(self.slug,)),'Grid config'), (reverse('moderate',args=(self.slug,)),'Moderate'), (reverse('analytics',args=(self.slug,)),'Analytics'), (self.get_absolute_url(),'View on site'), ) def images(self, date_from=None, date_to=None): tags = self.get_split_tags() images = InstagramImage.objects\ .filter(tags__name__in=tags) if date_from: images = images.filter(remote_timestamp__gte=date_from) if date_to: images = images.filter(remote_timestamp__lte=date_to) return images.distinct() def comment_count(self, date_from=None, date_to=None): return self.images(date_from, date_to)\ .aggregate(models.Sum('comment_count'))['comment_count__sum'] def like_count(self, date_from=None, date_to=None): return self.images(date_from, date_to)\ .aggregate(models.Sum('like_count'))['like_count__sum'] def log_stats(self): args = { 'display': self, 'total_like_count': self.like_count(), 'total_comment_count': self.comment_count(), 'total_image_count': self.images().count(), } if not args['total_like_count']: args['total_like_count'] = 0 if not args['total_comment_count']: args['total_comment_count'] = 0 if not args['total_image_count']: args['total_image_count'] = 0 try: last = DisplayEngagementLog.objects\ .filter(display=self)\ .order_by('-timestamp')[0] args['interval_like_count'] = max(0, args['total_like_count'] - last.total_like_count) args['interval_comment_count'] = max(0, args['total_comment_count'] - last.total_comment_count) args['interval_image_count'] = max(0, args['total_image_count'] - last.total_image_count) except: args['interval_like_count'] = args['total_like_count'] args['interval_comment_count'] = args['total_comment_count'] args['interval_image_count'] = args['total_image_count'] DisplayEngagementLog.objects.create(**args) @receiver(pre_save, sender=Display) def display_asciify_tags(sender, instance, signal, *args, **kwargs): # ensure tags dont contain unicode instance.tags = util.asciify(instance.tags) @receiver(post_save, sender=Display) def display_update_subscriptions(sender, instance, signal, *args, **kwargs): # update our instagram subscriptions if settings.INSTAGRAM_ENABLE_SUBSCRIPTIONS: Display.update_subscriptions() @receiver(post_save, sender=Display) def display_seed_scrape(sender, instance, signal, *args, **kwargs): # seed our initial images seed = cache.get(settings.CACHE_KEY_SEED_DISPLAY, []) seed.append(instance.id) cache.set(settings.CACHE_KEY_SEED_DISPLAY, seed, settings.CACHE_TIMEOUT) @receiver(post_save, sender=Display) def display_historic_scrape(sender, instance, signal, *args, **kwargs): # perform a historic scrape #if settings.INSTAGRAM_ENABLE_HISTORIC_SCRAPE and \ # instance.images().count < settings.INSTAGRAM_HISTORIC_IMAGE_COUNT: if settings.INSTAGRAM_ENABLE_HISTORIC_SCRAPE: tags = instance.get_split_tags() # preferably this would be sent to a worker # saving too many displays could cause a number of issues #cmd = ["python", "manage.py", "instagram_historic"] + tags #Popen(cmd, shell=False, stdin=None, stdout=None, stderr=None, close_fds=True) historic = cache.get(settings.CACHE_KEY_INSTAGRAM_HISTORIC_SCRAPE,[]) historic += tags cache.set(settings.CACHE_KEY_INSTAGRAM_HISTORIC_SCRAPE, historic, settings.CACHE_TIMEOUT) class DisplayImage(models.Model): display = models.ForeignKey(Display, db_index=True) image = models.ForeignKey(Image, related_name='displayimage') approved = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now=True) class Meta: unique_together = (('display', 'image',),) class PhotoFrame(LoadableImage, models.Model): frame = models.ImageField(upload_to='frames') inset_string = models.CommaSeparatedIntegerField(max_length=64, db_column='inset') mug_string = models.CommaSeparatedIntegerField(max_length=64, db_column='mug') name_string = models.CharField(max_length=64, db_column='name') name_colour_string = models.CommaSeparatedIntegerField(max_length=12, db_column='name_colour') name_font = models.FileField(upload_to='fonts') name_font_size = models.IntegerField() class Box(object): """Parses a CommaSeparatedIntegerField. Provides convenient access to the values contained in the field. The field is stored in the format "x1,y1,x2,y2" ("left,top,right,bottom") as a string. The class provides properties to access these, and other convenient functions. """ def __init__(self, str): self._str = str @property def size(self): return (self.width, self.height) @property def box(self): return (self.left, self.top, self.right, self.bottom) @property def values(self): return map(int, self._str.split(',')) @property def left(self): return self.values[0] @property def right(self): return self.values[2] @property def top(self): return self.values[1] @property def bottom(self): return self.values[3] @property def width(self): return self.values[2] - self.values[0] @property def height(self): return self.values[3] - self.values[1] @property def top_left(self): return self.values[0], self.values[1] def __unicode__(self): return self._str def cache_font(self): # bullshit to work around PIL not being able to load fonts from # data/open file handlers (it only accepts a path, which doesnt work # with S3, so instead we make a local copy of the file and return the # path to *that*) # TODO hashing on name might not work if the user uploads a different # version of the file with the same name h = hashlib.md5(self.name_font.name).hexdigest() base, ext = os.path.splitext(os.path.basename(self.name_font.name)) fn = os.path.join(settings.BASE_DIR, 'font-cache', '{}{}'.format(h, ext)) if not os.path.exists(fn): # tried using FieldFile.open but it doesnt work, falling back to boto key = s3_bucket.get_key(self.name_font.name) with open(fn,'wb') as local_fp: local_fp.write(key.read()) return fn def frame_image(self, photo): frame = self.load() img = photo.load() # resize the photo # paste the image img = img.resize(self.inset.size) frame.paste(img, self.inset.box) # get the user mug and name user = photo.user if self.name_string: username = user.username colour = self.name_colour font = self.cache_font() font_size = self.name_font_size util.draw_text(frame, username, self.name.top_left, colour, font=font, fontsize=font_size) if self.mug_string: mug = user.mug.load() mug = mug.resize(self.mug.size) frame.paste(mug, self.mug.box) return frame def get_absolute_url(self): return self.frame.url @property def inset(self): return PhotoFrame.Box(self.inset_string) @property def mug(self): return PhotoFrame.Box(self.mug_string) @property def name(self): return PhotoFrame.Box(self.name_string) @property def name_colour(self): return map(int, self.name_colour_string.split(',')) class DisplayEngagementLog(models.Model): display = models.ForeignKey(Display) timestamp = models.DateTimeField(auto_now_add=True, db_index=True) interval_like_count = models.PositiveIntegerField() interval_comment_count = models.PositiveIntegerField() interval_image_count = models.PositiveIntegerField() total_like_count = models.PositiveIntegerField() total_comment_count = models.PositiveIntegerField() total_image_count = models.PositiveIntegerField() def __unicode__(self): return '{} {}'.format(self.display, self.timestamp) class PrintedPhoto(models.Model): image = models.ForeignKey(Image) frame = models.ForeignKey(PhotoFrame) created = models.DateTimeField(auto_now_add=True) from . import instagram
{"/soundproof/admin.py": ["/soundproof/models.py"], "/microsite/urls.py": ["/microsite/views.py"], "/soundproof/instagram.py": ["/soundproof/models.py"], "/soundproof/migrations/0001_initial.py": ["/soundproof/models.py"], "/soundproof/management/commands/refresh_images.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/report.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/instagram_daemon.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/urls.py": ["/soundproof/views.py"]}
56,005
nathananderson03/soundproof
refs/heads/master
/soundproof/migrations/0004_auto_20150507_1204.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('soundproof', '0003_auto_20150507_1200'), ] operations = [ migrations.RemoveField( model_name='follower', name='followee', ), migrations.RemoveField( model_name='follower', name='follower', ), migrations.DeleteModel( name='Follower', ), ]
{"/soundproof/admin.py": ["/soundproof/models.py"], "/microsite/urls.py": ["/microsite/views.py"], "/soundproof/instagram.py": ["/soundproof/models.py"], "/soundproof/migrations/0001_initial.py": ["/soundproof/models.py"], "/soundproof/management/commands/refresh_images.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/report.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/instagram_daemon.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/urls.py": ["/soundproof/views.py"]}
56,006
nathananderson03/soundproof
refs/heads/master
/soundproof/middleware/exception_logger.py
import logging logger = logging.getLogger(__name__) class ExceptionLogger(object): def process_exception(self, request, exception): #logger.exception(exception) print exception
{"/soundproof/admin.py": ["/soundproof/models.py"], "/microsite/urls.py": ["/microsite/views.py"], "/soundproof/instagram.py": ["/soundproof/models.py"], "/soundproof/migrations/0001_initial.py": ["/soundproof/models.py"], "/soundproof/management/commands/refresh_images.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/report.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/instagram_daemon.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/urls.py": ["/soundproof/views.py"]}
56,007
nathananderson03/soundproof
refs/heads/master
/soundproof/data_store.py
from __future__ import absolute_import from django.conf import settings import kvstore _image_store = None def image_store(): global _image_store if not _image_store: _image_store = kvstore.create(**settings.STORES['image']['kvstore']) return _image_store
{"/soundproof/admin.py": ["/soundproof/models.py"], "/microsite/urls.py": ["/microsite/views.py"], "/soundproof/instagram.py": ["/soundproof/models.py"], "/soundproof/migrations/0001_initial.py": ["/soundproof/models.py"], "/soundproof/management/commands/refresh_images.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/report.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/instagram_daemon.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/urls.py": ["/soundproof/views.py"]}
56,008
nathananderson03/soundproof
refs/heads/master
/soundproof/migrations/0009_auto_20150529_1535.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('soundproof', '0008_auto_20150514_1117'), ] operations = [ migrations.AddField( model_name='display', name='images_to_load', field=models.CharField(default=b'5,10', help_text=b'How many images to load at a time, for example "5,10" means\n load 5 images, then 10, then 5, then 10, repeating', max_length=50), preserve_default=True, ), migrations.AddField( model_name='display', name='minimum_flips', field=models.PositiveIntegerField(default=3, help_text=b'Always flip this many images per load, even if there are no new images'), preserve_default=True, ), migrations.AlterField( model_name='display', name='speed', field=models.PositiveIntegerField(default=5, help_text=b'Minimum time between loading new images'), preserve_default=True, ), ]
{"/soundproof/admin.py": ["/soundproof/models.py"], "/microsite/urls.py": ["/microsite/views.py"], "/soundproof/instagram.py": ["/soundproof/models.py"], "/soundproof/migrations/0001_initial.py": ["/soundproof/models.py"], "/soundproof/management/commands/refresh_images.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/report.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/instagram_daemon.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/urls.py": ["/soundproof/views.py"]}
56,009
nathananderson03/soundproof
refs/heads/master
/soundproof/management/commands/subscribe.py
import requests from django.core.management.base import BaseCommand, CommandError from django.conf import settings class Command(BaseCommand): def handle(self, *args, **kwargs): r = requests.post('https://api.instagram.com/v1/subscriptions/',data={ 'client_id':settings.INSTAGRAM_ID, 'client_secret':settings.INSTAGRAM_SECRET, 'verify_token':settings.INSTAGRAM_VERIFY_TOKEN, 'callback_url':'http://soundproof.alhazan.ath.cx/instagram', 'object':'tag', 'object_id':'soundproof', 'aspect':'media', }) print r.text print r.headers
{"/soundproof/admin.py": ["/soundproof/models.py"], "/microsite/urls.py": ["/microsite/views.py"], "/soundproof/instagram.py": ["/soundproof/models.py"], "/soundproof/migrations/0001_initial.py": ["/soundproof/models.py"], "/soundproof/management/commands/refresh_images.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/report.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/instagram_daemon.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/urls.py": ["/soundproof/views.py"]}
56,010
nathananderson03/soundproof
refs/heads/master
/soundproof/migrations/0007_display_public_analytics.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('soundproof', '0006_auto_20150507_1316'), ] operations = [ migrations.AddField( model_name='display', name='public_analytics', field=models.BooleanField(default=False, help_text=b'Can anyone with the URL access the analytics page?'), preserve_default=True, ), ]
{"/soundproof/admin.py": ["/soundproof/models.py"], "/microsite/urls.py": ["/microsite/views.py"], "/soundproof/instagram.py": ["/soundproof/models.py"], "/soundproof/migrations/0001_initial.py": ["/soundproof/models.py"], "/soundproof/management/commands/refresh_images.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/report.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/instagram_daemon.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/urls.py": ["/soundproof/views.py"]}
56,011
nathananderson03/soundproof
refs/heads/master
/soundproof/views.py
# pylint: skip-file from __future__ import absolute_import, print_function import traceback import json import pytz import random from StringIO import StringIO from collections import namedtuple from django.db.models import Q, Sum, Min, Max, Count from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.conf import settings from django.core.cache import cache from django.core.urlresolvers import reverse from django.shortcuts import render_to_response, get_object_or_404 from django.utils.decorators import method_decorator from django.utils.timezone import get_current_timezone from django.views.generic.base import View, TemplateResponseMixin from django.views.decorators.csrf import csrf_exempt from django.contrib.auth.decorators import login_required, user_passes_test from . import instagram from .models import * def is_superuser(user): return user.is_superuser @csrf_exempt def instagram_callback(request): if request.GET.get('hub.mode') == 'subscribe': if request.GET.get('hub.verify_token') == settings.INSTAGRAM_VERIFY_TOKEN: return HttpResponse(request.GET.get('hub.challenge')) return HttpResponse() if request.method == 'POST': data = json.loads(request.body) state = cache.get(settings.CACHE_KEY_INSTAGRAM_UPDATE,[]) for obj in data: if obj['object'] != 'tag': continue tag = obj['object_id'] print('Instagram callback for {}'.format(tag)) # treat the list as an ordered set # remove any existing instance of the tag try: state.remove(tag) except: pass # add the tag state.append(tag) cache.set(settings.CACHE_KEY_INSTAGRAM_UPDATE, state, settings.CACHE_TIMEOUT) return HttpResponse() def feed(request, slug): display = get_object_or_404(Display, slug=slug) return render_to_response('soundproof/pages/feed.html', {'display':display}) def moderate(display, images): if display.moderation == 'whitelist': images = images.filter(displayimage__approved=True, displayimage__display=display) elif display.moderation == 'blacklist': images = images.filter( Q(displayimage=None)| ( Q(displayimage__approved=True) &Q(displayimage__display=display) ) ) return images def warmup(request): display = Display.objects.get(id=request.GET.get('display_id')) tags = display.get_split_tags() images = Image.objects\ .filter(Q(instagramimage__tags__name__in=tags)|Q(displayimage__display=display))\ .order_by('-remote_timestamp')\ .distinct() images = moderate(display, images) return render_to_response('soundproof/components/image.html', {'images':images[:int(request.GET.get('count'))]}) def update(request): '''serve images/directives to a feed restrict to images that are newer that gt_ts also send maintenance directives (ie reload the page) and moderation directives (replace image x with image y)''' cutoff = datetime.datetime.fromtimestamp(float(request.POST.get('gt_ts'))) cutoff = pytz.UTC.localize(cutoff) display_id = request.POST.get('display_id') display = Display.objects.get(id=display_id) tags = display.get_split_tags() images = Image.objects.filter(Q(instagramimage__tags__name__in=tags)|Q(displayimage__display=display)) if request.POST.get('image_ids'): images = images.exclude(id__in=request.POST.get('image_ids').split(",")) if images.filter(remote_timestamp__gt=cutoff).count() == 0: images = images.order_by('?') # grab some random images if there are no new ones else: images = images.filter(remote_timestamp__gt=cutoff).distinct().order_by('-remote_timestamp') images = moderate(display, images) images = set(images[0:int(request.POST.get('count'))]) if request.POST.get('format','html') == 'json': resp = { 'images':[img.as_dict() for img in images], 'moderated':get_moderated(display), 'directives':get_directives(request), } return HttpResponse(json.dumps(resp)) else: return render_to_response('soundproof/components/image.html', {'images':images}) def get_moderated(display): '''return recently moderated images for this display and a substitution''' cutoff = now() - datetime.timedelta(hours=1) moderated = DisplayImage.objects\ .filter( display=display, approved=False, timestamp__gte=cutoff ) return [{ 'id':di.image.id, 'sub':get_sub(display).as_dict(), } for di in moderated] def get_sub(display): '''pick random substitution image for this display take from 50 most recent non-rejected images''' tags = display.get_split_tags() images = Image.objects.order_by('-remote_timestamp') images = images.filter(instagramimage__tags__name__in=tags) images = moderate(display, images) return random.choice(list(images[:50])) def json_images(request): '''serve images to microsite as JSON restrict to images older than lt_ts''' lt_ts = request.GET.get('lt_ts') if lt_ts: cutoff = datetime.datetime.fromtimestamp(float(lt_ts)) cutoff = pytz.UTC.localize(cutoff) else: cutoff = now() images = Image.objects.all() images = images.filter(remote_timestamp__lt=cutoff) display = Display.objects.get(slug=request.GET.get('display_slug')) tags = display.tags.split(',') images = images.filter(instagramimage__tags__name__in=tags) if request.GET.get('moderation') == 'whitelist': images = images.filter(displayimage__approved=True, displayimage__display=display) elif request.GET.get('moderation') == 'blacklist': images = images.filter(Q(displayimage=None)|(Q(displayimage__approved=True)&Q(displayimage__display=display))) images = images.order_by('-remote_timestamp')[0:request.GET.get('count')] resp = HttpResponse(json.dumps([img.as_dict() for img in images])) resp['Access-Control-Allow-Origin'] = '*' return resp class SubscriptionsView(View, TemplateResponseMixin): template_name = 'soundproof/pages/subs.html' @method_decorator(user_passes_test(is_superuser)) def dispatch(self, *args, **kwargs): return super(SubscriptionsView, self).dispatch(*args, **kwargs) def get(self, request): return self.render_to_response({ 'subs':instagram.subscriptions(), }) def post(self, request): # this functionality is superseded by the Display save logic # it is left in for manual over-ride # use at own risk tag_name = request.POST.get('tag_name') if tag_name: instagram.add_subscription(tag_name) delete = request.POST.get('delete') if delete: instagram.remove_subscription(int(delete)) return HttpResponseRedirect(reverse('subs')) class ModerateView(View, TemplateResponseMixin): template_name = 'soundproof/pages/moderate.html' limit = 100 @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(ModerateView, self).dispatch(*args, **kwargs) def get(self, request, slug): display = get_object_or_404(Display, slug=slug) if not display.auth_user(request.user): raise Http404 tags = display.get_split_tags() # get the N latest images images = Image.objects\ .filter(instagramimage__tags__name__in=tags)\ .distinct()\ .order_by('-remote_timestamp')[:self.limit] return self.render_to_response({ 'display':display, 'images':images, }) def post(self, request, slug): display = get_object_or_404(Display, slug=slug) if not display.auth_user(request.user): raise Http404 image = get_object_or_404(Image, id=request.POST.get('img_id')) di = DisplayImage.objects.get_or_create(display=display, image=image)[0] if request.POST.get('approved') == 'true': di.approved = True else: di.approved = False di.save() return HttpResponse('') class PhotoSelectView(View, TemplateResponseMixin): template_name = 'soundproof/pages/print.html' limit = 30 def get(self, request, slug): if not settings.PRINTER_ENABLED: raise Http404 if request.GET.get('action') == 'preview': image_id = int(request.GET.get('photo')) frame_id = int(request.GET.get('frame')) frame = PhotoFrame.objects.get(id=frame_id) image = Image.objects.get(id=image_id) photo = frame.frame_image(image) buf = StringIO() photo.save(buf, format='JPEG', quality=85) resp = HttpResponse(buf.getvalue()) resp['Content-Type'] = 'image/jpeg' return resp elif request.GET.get('action') == 'images': display = get_object_or_404(Display, slug=slug) tags = display.get_split_tags() images = Image.objects\ .filter(instagramimage__tags__name__in=tags)\ .order_by('-remote_timestamp')[:self.limit] return render_to_response('soundproof/components/printer-photos.html', {'images':images}) else: display = get_object_or_404(Display, slug=slug) tags = display.get_split_tags() images = Image.objects\ .filter(instagramimage__tags__name__in=tags)\ .order_by('-remote_timestamp')[:self.limit] frames = PhotoFrame.objects.all() return self.render_to_response({ 'display':display, 'images':images, 'frames':frames, 'override_tools': 'Insta Printer', }) def post(self, request, slug): if not settings.PRINTER_ENABLED: raise Http404 try: image_id = int(request.POST.get('photo')) frame_id = int(request.POST.get('frame')) frame = PhotoFrame.objects.get(id=frame_id) image = Image.objects.get(id=image_id) photo = frame.frame_image(image) # print the photo #photo.save('test_photo.png') util.print_image(photo) # store details of the printed image PrintedPhoto(image=image, frame=frame).save() except Exception: print(traceback.format_exc()) raise return HttpResponse() def get_directives(request): status = cache.get('browser-status',{}) ip = request.META.get('REMOTE_ADDR') ret = {} if ip: browser = status.get(ip,{}) browser['ip'] = ip browser['last seen'] = now() browser['gt_ts'] = request.GET.get('gt_ts') if 'directives' in browser: ret = browser['directives'] del browser['directives'] status[ip] = browser cache.set('browser-status', status, 86400) return ret @csrf_exempt def status(request): if request.method == 'POST': ip = request.POST.get('ip') status = cache.get('browser-status',{}) browser = status.get(ip,{}) if request.POST.get('action') == 'reload': browser['directives'] = {'reload':True} if request.POST.get('action') == 'rename': browser['name'] = request.POST.get('name') status[ip] = browser cache.set('browser-status', status) if not request.user.is_superuser: return HttpResponse('') status = cache.get('browser-status',{}) for data in status.values(): if 'last seen' in data: data['delta'] = now() - data['last seen'] return render_to_response('soundproof/pages/status.html', { 'status': status, }) class AnalyticsView(View, TemplateResponseMixin): template_name = 'soundproof/pages/analytics.html' def get(self, request, slug): display = get_object_or_404(Display, slug=slug) if not (display.public_analytics or display.auth_user(request.user)): raise Http404 tags = display.get_split_tags() images = InstagramImage.objects\ .filter(tags__name__in=tags) data = { 'masthead_title': 'Insights Report', } if request.GET.get('date_from'): d = datetime.datetime.strptime(request.GET.get('date_from'), '%Y-%m-%d') d = get_current_timezone().localize(d) d = d.replace(hour=0, minute=0, second=0) images = images.filter(remote_timestamp__gte=d) data['date_from'] = d if request.GET.get('date_to'): d = datetime.datetime.strptime(request.GET.get('date_to'), '%Y-%m-%d') d = get_current_timezone().localize(d) d = d.replace(hour=23, minute=59, second=59) images = images.filter(remote_timestamp__lte=d) data['date_to'] = d dates = images.aggregate( date_from=Min('remote_timestamp'), date_to=Max('remote_timestamp'), ) if 'date_from' not in data: data['date_from'] = dates['date_from'] if 'date_to' not in data: data['date_to'] = dates['date_to'] points = DisplayEngagementLog.objects\ .filter(display=display)\ .filter(timestamp__gte=data['date_from'])\ .filter(timestamp__lte=data['date_to'])\ .order_by('timestamp') data['graph_json'] = json.dumps([{ 'unixtime': time.mktime(point.timestamp.timetuple()), 'timestamp': point.timestamp.strftime('%Y-%m-%d %H:%M'), 'interval': { 'likes': point.interval_like_count, 'comments': point.interval_comment_count, 'images': point.interval_image_count, }, 'total': { 'likes': point.total_like_count, 'comments': point.total_comment_count, 'images': point.total_image_count, }, } for point in points]) data['tags'] = [{ 'label': '#{}'.format(tag.name), 'value': 100*float(tag.name__count)/images.count(), } for tag in InstagramTag.objects\ .filter(instagramimage__in=images)\ .annotate(Count('name'))\ .order_by('-name__count')[0:12]] data['tags_json'] = json.dumps(data['tags']) #dummy = [] #start = now() #total = 0 #for n in range(10): # t = start + n * datetime.timedelta(minutes=15) # c = int(random.uniform(5,50)) # total += c # dummy.append({ # 'unixtime': time.mktime(t.timetuple()), # 'timestamp': t.strftime('%y-%m-%d %H:%M'), # 'interval': { # 'images': c, # }, # 'total': { # 'images': total, # }, # }) #data['graph_json'] = json.dumps(dummy) tz = get_current_timezone() data['date_from'] = data['date_from'].astimezone(get_current_timezone()) data['date_to'] = data['date_to'].astimezone(get_current_timezone()) try: data['follower_count'] = len(DisplayFollowers.objects\ .get(display=display).followers.split(',')) except: data['follower_count'] = 0 data['user_by_post_count'] = User.objects\ .filter(image__in=images)\ .annotate(image_count=Count('image'))\ .order_by('-image_count')\ .distinct() data['user_by_follower_count'] = User.objects\ .filter(image__in=images)\ .order_by('-follower_count')\ .distinct() data['images_by_engagement'] = images\ .extra(select={'points':'like_count+5*comment_count'})\ .order_by('-points')\ .distinct() data['images_by_likes'] = images.order_by('-like_count').distinct() data['images_by_comments'] = images.order_by('-comment_count').distinct() data['social_impressions'] = sum([image.user.follower_count for image in images]) stale_cutoff = now() - \ datetime.timedelta(seconds=settings.REFRESH_INSTAGRAM_USER_FREQUENCY) data.update({ 'display': display, 'image_count': images.count(), 'comment_count': images.distinct()\ .aggregate(Sum('comment_count'))['comment_count__sum'], 'like_count': images.distinct()\ .aggregate(Sum('like_count'))['like_count__sum'], 'poster_count': User.objects.filter(image__in=images)\ .order_by().distinct().count(), 'stale': User.objects\ .filter(image__in=images)\ .filter(last_updated__lt=stale_cutoff)\ .count() }) return self.render_to_response(data) class GridConfigView(View, TemplateResponseMixin): template_name = 'soundproof/pages/grid.html' def get(self, request, slug): display = get_object_or_404(Display, slug=slug) if not display.auth_user(request.user): raise Http404 OptStruct = namedtuple('OptStruct', 'app_label model_name') return self.render_to_response({ 'display': display, 'opts': OptStruct( app_label='soundproof', model_name='display', ), 'range':range(5000), }) def post(self, request, slug): display = get_object_or_404(Display, slug=slug) if not display.auth_user(request.user): raise Http404 try: hcount = int(request.POST.get('tile_hcount')) Display.objects.filter(id=display.id).update( tile_width='{}vw'.format(100.0/hcount) ) except: raise return HttpResponseRedirect(reverse('admin:soundproof_display_change', args=(display.id,)))
{"/soundproof/admin.py": ["/soundproof/models.py"], "/microsite/urls.py": ["/microsite/views.py"], "/soundproof/instagram.py": ["/soundproof/models.py"], "/soundproof/migrations/0001_initial.py": ["/soundproof/models.py"], "/soundproof/management/commands/refresh_images.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/report.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/instagram_daemon.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/urls.py": ["/soundproof/views.py"]}
56,012
nathananderson03/soundproof
refs/heads/master
/soundproof/site_settings_example.py
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'soundproof_feed', 'USER': 'root', 'PASSWORD': '', } } CACHES = { 'default':{ 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', }, } AWS = { 'AWS_ACCESS_KEY_ID': 'AKIAIMCJ263SF5JO5PHA', 'AWS_SECRET_ACCESS_KEY': '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', } STORES = { 'image': { 'region': 's3-ap-southeast-2', 'bucket': 'soundproof-images', 'kvstore': { 'path': 's3://soundproof-images', 'host': 's3-ap-southeast-2.amazonaws.com', } }, # for testing #'image': { # 'fs_path': '/static/images', # 'kvstore': { # 'path': 'file://~/Workspace/soundproof-hashtag-feed/soundproof/static/images', # }, #}, } INSTAGRAM_ID = '72ce3f8050fb437c96aa81807fe93a9a' INSTAGRAM_SECRET = 'c6ed6bebf82c497696e065111e92532f' INSTAGRAM_VERIFY_TOKEN = 'PNMJ9d0n7EnjVM5CmW2j' CACHE_KEY_INSTAGRAM_UPDATE = 'instagram-tags' CACHE_KEY_INSTAGRAM_HISTORIC_SCRAPE = 'instagram-historic-scrape' CACHE_KEY_SEED_DISPLAY = 'display-seed' CACHE_TIMEOUT=3600 INSTAGRAM_ENABLE_HISTORIC_SCRAPE=True INSTAGRAM_ENABLE_SUBSCRIPTIONS=True PRINTER_ENABLED=True PRINTER_NAME='Canon_CP910_2' PRINT_DPI=(300,300,) PRINT_SIZE_INCHES=(4,6,) PRINTER_SELPHY_PRINTER_IP="10.0.0.118" PRINTER_USE_LPR=False
{"/soundproof/admin.py": ["/soundproof/models.py"], "/microsite/urls.py": ["/microsite/views.py"], "/soundproof/instagram.py": ["/soundproof/models.py"], "/soundproof/migrations/0001_initial.py": ["/soundproof/models.py"], "/soundproof/management/commands/refresh_images.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/report.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/instagram_daemon.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/urls.py": ["/soundproof/views.py"]}
56,013
nathananderson03/soundproof
refs/heads/master
/soundproof/settings.py
""" Django settings for soundproof project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ from __future__ import absolute_import, print_function # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) from django.conf import global_settings # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'xknz+ykx8yiub^vv-8i#9d%p^undw3zpfm1+zl2*t&szzu#sw$' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True TEMPLATE_DIRS = ( os.path.join(BASE_DIR, 'templates'), ) TEMPLATE_LOADERS = global_settings.TEMPLATE_LOADERS + ( 'apptemplates.Loader', ) ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'soundproof', 'storages', 'microsite', 'colorful', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'soundproof.middleware.exception_logger.ExceptionLogger', ) ROOT_URLCONF = 'soundproof.urls' WSGI_APPLICATION = 'soundproof.wsgi.application' # Database # https://docs.djangoproject.com/en/1.7/ref/settings/#databases # see site_settings.py # Internationalization # https://docs.djangoproject.com/en/1.7/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Australia/Melbourne' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.7/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = 'soundproof/staticfiles' STATICFILES_DIRS = ( os.path.abspath(os.path.join(BASE_DIR, 'soundproof', 'static')), os.path.abspath(os.path.join(BASE_DIR, 'assets')), ) SITE_ID = 1 LOGIN_URL = '/admin/login/' CACHES = { 'default':{ 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', }, } AWS = { 'AWS_ACCESS_KEY_ID': 'AKIAIMCJ263SF5JO5PHA', 'AWS_SECRET_ACCESS_KEY': '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', } STORES = { 'image': { 'region': 's3-ap-southeast-2', 'bucket': 'soundproof-images', 'kvstore': { 'path': 's3://soundproof-images', 'host': 's3-ap-southeast-2.amazonaws.com', } }, # for testing #'image': { # 'fs_path': '/static/images', # 'kvstore': { # 'path': 'file://~/Workspace/soundproof-hashtag-feed/soundproof/static/images', # }, #}, } INSTAGRAM_ID = '72ce3f8050fb437c96aa81807fe93a9a' INSTAGRAM_SECRET = 'c6ed6bebf82c497696e065111e92532f' INSTAGRAM_VERIFY_TOKEN = 'PNMJ9d0n7EnjVM5CmW2j' INSTAGRAM_HISTORIC_IMAGE_COUNT = 50 CACHE_KEY_INSTAGRAM_UPDATE = 'instagram-tags' CACHE_KEY_INSTAGRAM_HISTORIC_SCRAPE = 'instagram-historic-scrape' CACHE_KEY_SEED_DISPLAY = 'display-seed' CACHE_TIMEOUT=3600 INSTAGRAM_ENABLE_HISTORIC_SCRAPE=True INSTAGRAM_ENABLE_SUBSCRIPTIONS=False PRINTER_ENABLED=True if os.environ.get('PRINTER', 'ds40') == 'selphy': PRINTER_NAME='Selphys' PRINTER_OPTIONS=[ # this is a paper size specified in /etc/cups/ppd/<printer name> '-o media=Postcard.Fullbleed', # scale the image to fit '-o fit-to-page', ] PRINTER_SELPHY_PRINTER_IP="10.0.0.118" else: PRINTER_NAME='Dai_Nippon_Printing_DS40' PRINTER_OPTIONS=[] PRINT_DPI=(300,300,) PRINT_SIZE_INCHES=(4,6,) PRINTER_USE_LPR=True USE_PIL = False REFRESH_INSTAGRAM_IMAGE_FREQUENCY = 60*60*24 REFRESH_INSTAGRAM_USER_FREQUENCY = 60*60*24 LOG_ENGAGEMENT_FREQUENCY = 60*15 # allow loading of specific settings files # must be in full import name, ie 'soundproof.site_settings' if 'SOUNDPROOF_SITE_SETTINGS' in os.environ: ss = __import__(os.environ['SOUNDPROOF_SITE_SETTINGS'], fromlist=['*']) for name in dir(ss): globals()[name] = getattr(ss, name) else: try: from .site_settings import * except: pass # set our AWS variables if 'AWS' in globals(): if 'AWS_ACCESS_KEY_ID' not in os.environ: os.environ['AWS_ACCESS_KEY_ID'] = AWS['AWS_ACCESS_KEY_ID'] if 'AWS_SECRET_ACCESS_KEY' not in os.environ: os.environ['AWS_SECRET_ACCESS_KEY'] = AWS['AWS_SECRET_ACCESS_KEY']
{"/soundproof/admin.py": ["/soundproof/models.py"], "/microsite/urls.py": ["/microsite/views.py"], "/soundproof/instagram.py": ["/soundproof/models.py"], "/soundproof/migrations/0001_initial.py": ["/soundproof/models.py"], "/soundproof/management/commands/refresh_images.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/report.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/instagram_daemon.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/urls.py": ["/soundproof/views.py"]}
56,014
nathananderson03/soundproof
refs/heads/master
/soundproof/management/commands/refresh_images.py
#pylint: skip-file from __future__ import absolute_import, print_function import datetime import time from django.core.management.base import BaseCommand from django.conf import settings from django.core.cache import cache from django.utils.timezone import now, get_current_timezone from ...models import InstagramImage from ...instagram import refresh_social CUTOFF_SECONDS = 60*60*24 class Command(BaseCommand): def handle(self, *args, **kwargs): while True: self.refresh() def refresh(self): cutoff = now() - datetime.timedelta(seconds=CUTOFF_SECONDS) images = InstagramImage.objects\ .filter(last_updated__lt=cutoff) for image in images[0:10]: refresh_social(image) if not images.count(): print('up to date') time.sleep(5)
{"/soundproof/admin.py": ["/soundproof/models.py"], "/microsite/urls.py": ["/microsite/views.py"], "/soundproof/instagram.py": ["/soundproof/models.py"], "/soundproof/migrations/0001_initial.py": ["/soundproof/models.py"], "/soundproof/management/commands/refresh_images.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/report.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/instagram_daemon.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/urls.py": ["/soundproof/views.py"]}
56,015
nathananderson03/soundproof
refs/heads/master
/soundproof/migrations/0003_auto_20150507_1200.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import datetime from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('soundproof', '0002_follower'), ] operations = [ migrations.CreateModel( name='DisplayEngagementLog', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('timestamp', models.DateTimeField(auto_now_add=True, db_index=True)), ('interval_like_count', models.PositiveIntegerField()), ('interval_comment_count', models.PositiveIntegerField()), ('inverval_image_count', models.PositiveIntegerField()), ('total_like_count', models.PositiveIntegerField()), ('total_comment_count', models.PositiveIntegerField()), ('total_image_count', models.PositiveIntegerField()), ('display', models.ForeignKey(to='soundproof.Display')), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='DisplayFollowers', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('followers', models.TextField()), ('display', models.ForeignKey(to='soundproof.Display')), ], options={ }, bases=(models.Model,), ), migrations.AddField( model_name='display', name='active', field=models.BooleanField(default=True), preserve_default=True, ), migrations.AddField( model_name='display', name='last_updated', field=models.DateTimeField(default=datetime.datetime(2014, 5, 7, 2, 0, 49, 403720, tzinfo=utc), auto_now=True), preserve_default=False, ), migrations.AlterField( model_name='user', name='last_updated', field=models.DateTimeField(blank=True), preserve_default=True, ), ]
{"/soundproof/admin.py": ["/soundproof/models.py"], "/microsite/urls.py": ["/microsite/views.py"], "/soundproof/instagram.py": ["/soundproof/models.py"], "/soundproof/migrations/0001_initial.py": ["/soundproof/models.py"], "/soundproof/management/commands/refresh_images.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/report.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/instagram_daemon.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/urls.py": ["/soundproof/views.py"]}
56,016
nathananderson03/soundproof
refs/heads/master
/soundproof/deployment_settings/heroku.py
import os # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False TEMPLATE_DEBUG = False STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' ALLOWED_HOSTS = [ '.herokuapp.com', ] BASE_DIR = os.path.dirname(os.path.dirname(__file__)) LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, '..', 'debug.log'), }, 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'soundproof.middleware.exception_logger': { 'handlers': ['file','console',], 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), 'propagate': True, }, 'django.request': { 'handlers': ['file','console',], 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), 'propagate': True, }, 'django': { 'handlers': ['file','console',], 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), }, }, } DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'dc35jkpjsiivm1', 'USER': 'bqdmwfasgvojtm', 'PASSWORD': 'pXT66vmVWAi0XC9wnIjBXEdlC2', 'HOST': 'ec2-23-21-140-156.compute-1.amazonaws.com', 'PORT': '5432', } } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'cache_table', } } AWS = { 'REGION': 'ap-southeast-2', 'AWS_ACCESS_KEY_ID': 'AKIAIMCJ263SF5JO5PHA', 'AWS_SECRET_ACCESS_KEY': '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', } STORES = { 'image': { 'region': 's3-{}'.format(AWS['REGION']), 'bucket': 'soundproof-images-heroku', 'kvstore': { 'path': 's3://soundproof-images-heroku', 'host': 's3-ap-southeast-2.amazonaws.com', } }, } INSTAGRAM_ID='94b19564477e428792b9913f22fe969a' INSTAGRAM_SECRET='258d59a978c943a0b62b904c86f219e9' INSTAGRAM_VERIFY_TOKEN='1588538786.94b1956.835bd997d8b04452a2b5b6f7ed9f7002' CACHE_KEY_INSTAGRAM_UPDATE='instagram-tags' CACHE_KEY_INSTAGRAM_HISTORIC_SCRAPE='instagram-historic-scrape' CACHE_KEY_SEED_DISPLAY='display-seed' CACHE_TIMEOUT=3600 INSTAGRAM_ENABLE_HISTORIC_SCRAPE=True INSTAGRAM_ENABLE_SUBSCRIPTIONS=True FETCH_FOLLOWERS=True #for django-storages DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' #duplicate these for django-storages AWS_ACCESS_KEY_ID = AWS['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = AWS['AWS_SECRET_ACCESS_KEY'] AWS_STORAGE_BUCKET_NAME = STORES['image']['bucket'] #end django-storages
{"/soundproof/admin.py": ["/soundproof/models.py"], "/microsite/urls.py": ["/microsite/views.py"], "/soundproof/instagram.py": ["/soundproof/models.py"], "/soundproof/migrations/0001_initial.py": ["/soundproof/models.py"], "/soundproof/management/commands/refresh_images.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/report.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/instagram_daemon.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/urls.py": ["/soundproof/views.py"]}
56,017
nathananderson03/soundproof
refs/heads/master
/soundproof/management/commands/report.py
import datetime from django.core.management.base import BaseCommand from django.utils.timezone import get_current_timezone from soundproof.models import InstagramImage from soundproof.instagram import get_report TAGS = ('udaustralia',) PERIOD = ( datetime.datetime(2015, 3, 27, 0, 0, tzinfo=get_current_timezone()), datetime.datetime(2015, 3, 28, 0, 0, tzinfo=get_current_timezone()), ) class Command(BaseCommand): def handle(self, *args, **kwargs): report_data = get_report(TAGS, PERIOD)
{"/soundproof/admin.py": ["/soundproof/models.py"], "/microsite/urls.py": ["/microsite/views.py"], "/soundproof/instagram.py": ["/soundproof/models.py"], "/soundproof/migrations/0001_initial.py": ["/soundproof/models.py"], "/soundproof/management/commands/refresh_images.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/report.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/instagram_daemon.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/urls.py": ["/soundproof/views.py"]}
56,018
nathananderson03/soundproof
refs/heads/master
/soundproof/management/commands/instagram_daemon.py
#pylint: skip-file from __future__ import absolute_import, print_function import datetime import time from django.core.management.base import BaseCommand from django.conf import settings from django.core.cache import cache from django.utils.timezone import now, get_current_timezone from ...models import * from ...instagram import ( update_instagram_tag, scrape_instagram_tag, refresh_users, refresh_images, log_engagement, ) min_fetch_interval = datetime.timedelta(seconds=5) tz = get_current_timezone() beginning = now() - datetime.timedelta(days=365) class Command(BaseCommand): def __init__(self): self.last_fetch = beginning self.more_work = False super(Command, self).__init__() def update(self): current_time = now() if self.more_work or current_time - self.last_fetch > min_fetch_interval: self.more_work = False if getattr(settings, 'FETCH_FOLLOWERS', False): self.more_work |= refresh_users() self.more_work |= refresh_images() log_engagement() # check for display seeding display_seed = cache.get(settings.CACHE_KEY_SEED_DISPLAY,[]) if display_seed: print('Daemon found seed urls') cache.delete(settings.CACHE_KEY_SEED_DISPLAY) for display_id in display_seed: try: print('Seeding display "{}"'.format(display_id)) display = Display.objects.get(id=display_id) display.process_seed_urls() except: pass # check for historic scraping historic_scrape = cache.get(settings.CACHE_KEY_INSTAGRAM_HISTORIC_SCRAPE, []) if historic_scrape: print('Daemon found historic tags') cache.delete(settings.CACHE_KEY_INSTAGRAM_HISTORIC_SCRAPE) for tag in historic_scrape: try: print('Scraping tag "{}"'.format(tag)) scrape_instagram_tag(tag, settings.INSTAGRAM_HISTORIC_IMAGE_COUNT) except: pass # check for instagram tags # TODO: this should probably just check all tags all the time instagram_update = cache.get(settings.CACHE_KEY_INSTAGRAM_UPDATE,[]) if instagram_update: print('Daemon found update tags') cache.delete(settings.CACHE_KEY_INSTAGRAM_UPDATE) # iterate backwards through the tags for tag in instagram_update[::-1]: try: print('Updating tag "{}"'.format(tag)) model_tag = InstagramTag.objects.get(name=tag) update_instagram_tag(tag, model_tag.max_tag_id) except: pass def handle(self, *args, **kwargs): while True: self.update() if not self.more_work: time.sleep(1)
{"/soundproof/admin.py": ["/soundproof/models.py"], "/microsite/urls.py": ["/microsite/views.py"], "/soundproof/instagram.py": ["/soundproof/models.py"], "/soundproof/migrations/0001_initial.py": ["/soundproof/models.py"], "/soundproof/management/commands/refresh_images.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/report.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/instagram_daemon.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/urls.py": ["/soundproof/views.py"]}
56,019
nathananderson03/soundproof
refs/heads/master
/soundproof/urls.py
from django.conf.urls import patterns, include, url from django.contrib import admin from .views import ( SubscriptionsView, ModerateView, AnalyticsView, GridConfigView, PhotoSelectView, ) urlpatterns = patterns( 'soundproof.views', url(r'^instagram$', 'instagram_callback', name='instagram_callback'), url(r'^feed/(.+)$', 'feed', name='feed'), url(r'^moderate/(.+)$', ModerateView.as_view(), name='moderate'), url(r'^analytics/(.+)$', AnalyticsView.as_view(), name='analytics'), url(r'^grid/(.+)$', GridConfigView.as_view(), name='grid'), url(r'^update$', 'update', name='update'), url(r'^warmup$', 'warmup', name='warmup'), url(r'^subs$', SubscriptionsView.as_view(), name='subs'), url(r'^api/json-images$', 'json_images', name='json_images'), url(r'status', 'status'), url(r'^print/(?P<slug>[^/]+)$', PhotoSelectView.as_view(), name='photo_select'), url(r'^admin/', include(admin.site.urls)), ) urlpatterns += patterns( '', url('r^microsite/', include('microsite.urls')), )
{"/soundproof/admin.py": ["/soundproof/models.py"], "/microsite/urls.py": ["/microsite/views.py"], "/soundproof/instagram.py": ["/soundproof/models.py"], "/soundproof/migrations/0001_initial.py": ["/soundproof/models.py"], "/soundproof/management/commands/refresh_images.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/report.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/instagram_daemon.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/urls.py": ["/soundproof/views.py"]}
56,020
nathananderson03/soundproof
refs/heads/master
/soundproof/management/commands/instagram_update.py
from __future__ import absolute_import, print_function from django.core.management.base import BaseCommand from ... import instagram class Command(BaseCommand): def __init__(self): super(Command, self).__init__() def handle(self, *args, **kwargs): for tag in args: print('Loading tag "{}"'.format(tag)) instagram.update_instagram_tag(tag)
{"/soundproof/admin.py": ["/soundproof/models.py"], "/microsite/urls.py": ["/microsite/views.py"], "/soundproof/instagram.py": ["/soundproof/models.py"], "/soundproof/migrations/0001_initial.py": ["/soundproof/models.py"], "/soundproof/management/commands/refresh_images.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/report.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/management/commands/instagram_daemon.py": ["/soundproof/models.py", "/soundproof/instagram.py"], "/soundproof/urls.py": ["/soundproof/views.py"]}
56,040
titanbt/deep_memNN
refs/heads/master
/loader/data_helper.py
import os from collections import Counter import xml.etree.ElementTree as ET class DataHelper(object): def __init__(self, train_file, test_file, edim, init_std, embedding_path=None): self.train_file = train_file self.test_file = test_file self.embedding_path = embedding_path self.edim = edim self.init_std = init_std self.params = {'pad_idx': 0, 'nwords': 0, 'mem_size': 0, 'embedd_table': [], 'embedd_table_aspect': []} def load_data(self): source_count, target_count = [], [] source_word2idx, target_word2idx = {}, {} self.train_data = self._read_data(self.train_file, source_count, source_word2idx, target_count, target_word2idx) self.test_data = self._read_data(self.test_file, source_count, source_word2idx, target_count, target_word2idx) self.params['pad_idx'] = source_word2idx['<pad>'] self.params['nwords'] = len(source_word2idx) self.params['mem_size'] = self.train_data[4] if self.train_data[4] > self.test_data[4] else self.test_data[4] print "Loading word2vec..." self.params['embedd_table'] = self.init_word_embeddings(source_word2idx) self.params['embedd_table_aspect'] = self.init_word_embeddings(target_word2idx) return self.train_data, self.test_data, self.params def _read_data(self, fname, source_count, source_word2idx, target_count, target_word2idx): if os.path.isfile(fname) == False: raise ("[!] Data %s not found" % fname) tree = ET.parse(fname) root = tree.getroot() source_words, target_words, max_sent_len = [], [], 0 for sentence in root: text = sentence.find('text').text.lower() source_words.extend(text.split()) if len(text.split()) > max_sent_len: max_sent_len = len(text.split()) for asp_terms in sentence.iter('aspectTerms'): for asp_term in asp_terms.findall('aspectTerm'): target_words.append(asp_term.get('term').lower()) if len(source_count) == 0: source_count.append(['<pad>', 0]) source_count.extend(Counter(source_words).most_common()) target_count.extend(Counter(target_words).most_common()) for word, _ in source_count: if word not in source_word2idx: source_word2idx[word] = len(source_word2idx) for word, _ in target_count: if word not in target_word2idx: target_word2idx[word] = len(target_word2idx) source_data, source_loc_data, target_data, target_label = list(), list(), list(), list() for sentence in root: text = sentence.find('text').text.lower() if len(text.strip()) != 0: idx = [] for word in text.split(): idx.append(source_word2idx[word]) for asp_terms in sentence.iter('aspectTerms'): for asp_term in asp_terms.findall('aspectTerm'): source_data.append(idx) pos_info, lab = self._get_data_tuple(text, asp_term.get('term').lower(), int(asp_term.get('from')), int(asp_term.get('to')), asp_term.get('polarity'), source_word2idx) source_loc_data.append(pos_info) target_data.append(target_word2idx[asp_term.get('term').lower()]) target_label.append(lab) print("Read %s aspects from %s" % (len(source_data), fname)) return source_data, source_loc_data, target_data, target_label, max_sent_len def _get_abs_pos(self, cur, ids): min_dist = 1000 for i in ids: if abs(cur - i) < min_dist: min_dist = abs(cur - i) if min_dist == 1000: raise ("[!] ids list is empty") return min_dist def _count_pre_spaces(self, text): count = 0 for i in xrange(len(text)): if text[i].isspace(): count = count + 1 else: break return count def _count_mid_spaces(self, text, pos): count = 0 for i in xrange(len(text) - pos): if text[pos + i].isspace(): count = count + 1 else: break return count def _check_if_ranges_overlap(self, x1, x2, y1, y2): return x1 <= y2 and y1 <= x2 def _get_data_tuple(self, text, asp_term, fro, to, label, word2idx): words = text.split() # Find the ids of aspect term ids, st, i = [], self._count_pre_spaces(text), 0 for word in words: if self._check_if_ranges_overlap(st, st + len(word) - 1, fro, to - 1): ids.append(i) st = st + len(word) + self._count_mid_spaces(text, st + len(word)) i = i + 1 pos_info, i = [], 0 for word in words: pos_info.append(self._get_abs_pos(i, ids)) i = i + 1 lab = None if label == 'negative': lab = 0 elif label == 'neutral': lab = 1 else: lab = 2 return pos_info, lab def init_word_embeddings(self, word2idx): import numpy as np wt = np.random.normal(0, self.init_std, [len(word2idx), self.edim]) with open(self.embedding_path, 'r') as f: for line in f: content = line.strip().split() if content[0] in word2idx: wt[word2idx[content[0]]] = np.array(map(float, content[1:])) return wt
{"/main.py": ["/utils/commandParser.py", "/model/sentence_memNN_main.py"], "/loader/data_loader.py": ["/loader/funcs.py"]}
56,041
titanbt/deep_memNN
refs/heads/master
/utils/commandParser.py
import argparse def DLNLPOptParser(): parser = argparse.ArgumentParser(\ description='Default DLNLP opt parser.') parser.add_argument('-mode', default='deep_memNN') parser.add_argument('-config',default='config/sentence_memNN.cfg', help='config file to set.') return parser.parse_args()
{"/main.py": ["/utils/commandParser.py", "/model/sentence_memNN_main.py"], "/loader/data_loader.py": ["/loader/funcs.py"]}
56,042
titanbt/deep_memNN
refs/heads/master
/main.py
from utils.commandParser import DLNLPOptParser import warnings from model.sentence_memNN_main import SentenceMemNNMain warnings.simplefilter("ignore", DeprecationWarning) if __name__ == '__main__': args = DLNLPOptParser() config = args.config if args.mode == 'deep_memNN': deep_memNN = SentenceMemNNMain(config, args) deep_memNN.run()
{"/main.py": ["/utils/commandParser.py", "/model/sentence_memNN_main.py"], "/loader/data_loader.py": ["/loader/funcs.py"]}
56,043
titanbt/deep_memNN
refs/heads/master
/loader/funcs.py
import numpy as np import theano import loader.libs.utils as utils from loader.libs.alphabet import Alphabet logger = utils.get_logger("LoadData") MAX_LENGTH = 140 def load_dataset_sequence_labeling(train_path, test_path, word_column=0, target_column=1, label_column=2, label_name='senti', oov='embedding', embedding="word2Vec",embedding_path=None): def construct_tensor(word_index_sentences, target_index_sentences, label_index_sentences): X = np.empty([len(word_index_sentences), max_length], dtype=np.int32) # T = np.empty([len(target_index_sentences), max_length], dtype=np.int32) # Y = [] Y = np.empty([len(target_index_sentences), 1], dtype=np.int32) mask = np.zeros([len(word_index_sentences), max_length], dtype=theano.config.floatX) for i in range(len(word_index_sentences)): word_ids = word_index_sentences[i] # target_ids = target_index_sentences[i] label_ids = label_index_sentences[i] length = len(word_ids) # target_length = len(target_ids) for j in range(length): wid = word_ids[j] X[i, j] = wid # for j in range(target_length): # tid = target_ids[j] # T[i, j] = tid label = label_ids[0] # Y.append(label) Y[i, 0] = label # Zero out X after the end of the sequence X[i, length:] = 0 # T[i, target_length:] = 0 # Make the mask for this sample 1 within the range of length mask[i, :length] = 1 return X, target_index_sentences, Y, mask def generate_dataset_fine_tune(): embedd_dict, embedd_dim, caseless = utils.load_word_embedding_dict(embedding, embedding_path, word_alphabet, logger) logger.info("Dimension of embedding is %d, Caseless: %d" % (embedd_dim, caseless)) X_train, T_train, Y_train, mask_train = construct_tensor(word_index_sentences_train, target_index_sentences_train, label_index_sentences_train) X_test, T_test, Y_test, mask_test = construct_tensor(word_index_sentences_test, target_index_sentences_test, label_index_sentences_test) return X_train, T_train, Y_train, mask_train, X_test, T_test, Y_test, mask_test, \ build_embedd_table(word_alphabet, embedd_dict, embedd_dim, caseless), label_alphabet word_alphabet = Alphabet('word') label_alphabet = Alphabet(label_name) # read training data logger.info("Reading data from training set...") word_sentences_train, _, target_sentences_train, word_index_sentences_train, label_index_sentences_train, target_index_sentences_train = read_sequence( train_path, word_alphabet, label_alphabet, word_column, label_column, target_column) if oov == "random": logger.info("Close word alphabet.") word_alphabet.close() # read test data logger.info("Reading data from test set...") word_sentences_test, _, target_sentences_test, word_index_sentences_test, label_index_sentences_test, target_index_sentences_test = read_sequence( test_path, word_alphabet, label_alphabet, word_column, label_column, target_column) # close alphabets word_alphabet.close() label_alphabet.close() logger.info("word alphabet size: %d" % (word_alphabet.size() - 1)) logger.info("label alphabet size: %d" % (label_alphabet.size() - 1)) # get maximum length max_length_train = get_max_length(word_sentences_train) max_length_test = get_max_length(word_sentences_test) max_length = min(MAX_LENGTH, max(max_length_train, max_length_test)) logger.info("Maximum length of training set is %d" % max_length_train) logger.info("Maximum length of test set is %d" % max_length_test) logger.info("Maximum length used for training is %d" % max_length) logger.info("Generating data with fine tuning...") return generate_dataset_fine_tune() def build_embedd_table(word_alphabet, embedd_dict, embedd_dim, caseless): scale = np.sqrt(3.0 / embedd_dim) embedd_table = np.empty([word_alphabet.size(), embedd_dim], dtype=theano.config.floatX) embedd_table[word_alphabet.default_index, :] = np.random.uniform(-scale, scale, [1, embedd_dim]) for word, index in word_alphabet.iteritems(): ww = word.lower() if caseless else word embedd = embedd_dict[ww] if ww in embedd_dict else np.random.uniform(-scale, scale, [1, embedd_dim]) embedd_table[index, :] = embedd return embedd_table def get_max_length(word_sentences): max_len = 0 for sentence in word_sentences: length = len(sentence) if length > max_len: max_len = length return max_len def read_sequence(path, word_alphabet, label_alphabet, word_column=0, label_column=2, target_column=1): word_sentences = [] label_sentences = [] target_sentences = [] word_index_sentences = [] label_index_sentences = [] target_index_sentences = [] num_tokens = 0 with open(path) as file: for line in file: words = [] labels = [] targets = [] word_ids = [] label_ids = [] target_ids = [] line.decode('utf-8') if line.strip() == "": if 0 < len(words) <= MAX_LENGTH: word_sentences.append(words[:]) label_sentences.append(labels[:]) target_sentences.append(targets[:]) word_index_sentences.append(word_ids[:]) label_index_sentences.append(label_ids[:]) target_index_sentences.append((target_ids[:])) num_tokens += len(words) else: if len(words) != 0: logger.info("ignore sentence with length %d" % (len(words))) words = [] labels = [] targets = [] word_ids = [] label_ids = [] target_ids = [] else: parts = line.strip().split('\t') if len(parts) is 3: tokens = parts[word_column].strip().split() label = parts[label_column] target_tokens = parts[target_column].strip().split() for word in tokens: if word != "$t$": words.append(word) # insert str word into list word_id = word_alphabet.get_index(word) word_ids.append(word_id) for target in target_tokens: targets.append(target) target_id = word_alphabet.get_index(target) target_ids.append(target_id) labels.append(label) label_id = label_alphabet.get_index(label) label_ids.append(label_id) if 0 < len(words) <= MAX_LENGTH: word_sentences.append(words[:]) label_sentences.append(labels[:]) target_sentences.append(targets[:]) target_sentences.append(targets[:]) word_index_sentences.append(word_ids[:]) label_index_sentences.append(label_ids[:]) target_index_sentences.append((target_ids[:])) num_tokens += len(words) else: if len(words) != 0: logger.info("ignore sentence with length %d" % (len(words))) logger.info("#sentences: %d, #tokens: %d" % (len(word_sentences), num_tokens)) return word_sentences, label_sentences, target_sentences, word_index_sentences, label_index_sentences, target_index_sentences def build_aspect_embeddings(aspect_index_train, aspect_index_test, embedd_table): _, embedd_dim = embedd_table.shape def get_target_vec(target_ids): targetVec = np.zeros([embedd_dim]) for id in target_ids: xVec = embedd_table[id] for i,v in enumerate(xVec): targetVec[i] = targetVec[i] + xVec[i] for i,v in enumerate(targetVec): targetVec[i] = targetVec[i]/ len(target_ids) return targetVec target_vecs_train = np.array([get_target_vec(target_ids) for target_ids in aspect_index_train]) target_vecs_test = np.array([get_target_vec(target_ids) for target_ids in aspect_index_test]) return target_vecs_train, target_vecs_test
{"/main.py": ["/utils/commandParser.py", "/model/sentence_memNN_main.py"], "/loader/data_loader.py": ["/loader/funcs.py"]}
56,044
titanbt/deep_memNN
refs/heads/master
/model/sentence_memNN_main.py
from ConfigParser import SafeConfigParser from loader.data_helper import DataHelper from nn.sentence_memNN import SentenceMemNN import numpy as np import math import tensorflow as tf class SentenceMemNNMain(object): def __init__(self, config=None, opts=None): if config == None and opts == None: print "Please specify command option or config file ..." return parser = SafeConfigParser() parser.read(config) self.train_file = parser.get('model', 'train_file') self.test_file = parser.get('model', 'test_file') self.embedding_path = parser.get('model', 'embedding_path') self.batch_size = parser.getint('model', 'batch_size') self.num_epochs = parser.getint('model', 'num_epochs') self.lindim = parser.getint('model', 'lindim') self.init_hid = parser.getfloat('model', 'init_hid') self.init_std = parser.getfloat('model', 'init_std') self.embedd_dim = parser.getint('model', 'embedd_dim') self.max_grad_norm = parser.getint('model', 'max_grad_norm') self.num_hops = parser.getint('model', 'num_hops') self.lr = parser.getfloat('model', 'learning_rate') self.params = {'pad_idx': 0, 'nwords': 0, 'mem_size': 0, 'embedd_table': [], 'embedd_table_aspect': []} self.setupOperators() def setupOperators(self): print('Loading the training data...') self.reader = DataHelper(self.train_file, self.test_file, edim=self.embedd_dim, init_std=self.init_std, embedding_path=self.embedding_path) self.train_data, self.test_data, self.params = self.reader.load_data() def init_model(self): print "Building model..." self.model = SentenceMemNN(nwords=self.params['nwords'], init_hid=self.init_hid, init_std=self.init_std, batch_size=self.batch_size, num_epochs=self.num_epochs, num_hops=self.num_hops, embedd_dim=self.embedd_dim, mem_size=self.params['mem_size'], lindim=self.lindim, max_grad_norm=self.max_grad_norm, pad_idx=self.params['pad_idx'], embedd_table_aspect=self.params['embedd_table_aspect'], lr=self.lr) self.model.build_network() def run(self): with tf.Session() as sess: self.init_model() sess.run(self.model.A.assign(self.params['embedd_table'])) sess.run(self.model.B.assign(self.params['embedd_table'])) sess.run(self.model.ASP.assign(self.params['embedd_table_aspect'])) for idx in xrange(self.num_epochs): print('epoch ' + str(idx) + '...') train_loss, train_acc = self.train(sess) test_loss, test_acc = self.test(sess, self.test_data) print('train-loss=%.2f;train-acc=%.2f;test-acc=%.2f;' % (train_loss, train_acc, test_acc)) def train(self, sess): source_data, source_loc_data, aspect_data, aspect_label, _ = self.train_data N = int(math.ceil(len(source_data) / self.batch_size)) cost = 0 aspect = np.ndarray([self.batch_size, 1], dtype=np.float32) loc = np.ndarray([self.batch_size, self.params['mem_size']], dtype=np.int32) target = np.zeros([self.batch_size, 3]) context = np.ndarray([self.batch_size, self.params['mem_size']]) rand_idx, cur = np.random.permutation(len(source_data)), 0 for idx in xrange(N): context.fill(self.params['pad_idx']) loc.fill(self.params['mem_size']) target.fill(0) self.set_variables(sess) for b in xrange(self.batch_size): m = rand_idx[cur] aspect[b][0] = aspect_data[m] target[b][aspect_label[m]] = 1 loc[b, :len(source_loc_data[m])] = source_loc_data[m] context[b, :len(source_data[m])] = source_data[m] cur = cur + 1 a, loss, self.step = sess.run([self.model.optim, self.model.loss, self.model.global_step], feed_dict={self.model.aspect: aspect, self.model.loc: loc, self.model.target: target, self.model.context: context}) cost += np.sum(loss) _, train_acc = self.test(sess, self.train_data) return cost / N / self.batch_size, train_acc def test(self, sess, data): source_data, source_loc_data, target_data, target_label, _ = data N = int(math.ceil(len(source_data) / self.batch_size)) cost = 0 aspect = np.ndarray([self.batch_size, 1], dtype=np.float32) loc = np.ndarray([self.batch_size, self.params['mem_size']], dtype=np.int32) target = np.zeros([self.batch_size, 3]) context = np.ndarray([self.batch_size, self.params['mem_size']]) context.fill(self.params['pad_idx']) self.set_variables(sess) m, acc = 0, 0 for i in xrange(N): context.fill(self.params['pad_idx']) loc.fill(self.params['mem_size']) target.fill(0) raw_labels = [] for b in xrange(self.batch_size): aspect[b][0] = target_data[m] target[b][target_label[m]] = 1 loc[b, :len(source_loc_data[m])] = source_loc_data[m] context[b, :len(source_data[m])] = source_data[m] m += 1 raw_labels.append(target_label[m]) a, loss, self.step = sess.run([self.model.optim, self.model.loss, self.model.global_step], feed_dict={ self.model.aspect: aspect, self.model.loc: loc, self.model.target: target, self.model.context: context}) cost += np.sum(loss) predictions = sess.run(self.model.correct_prediction, feed_dict={self.model.aspect: aspect, self.model.loc: loc, self.model.target: target, self.model.context: context}) for b in xrange(self.batch_size): if raw_labels[b] == predictions[b]: acc = acc + 1 return cost, acc / float(len(source_data)) def set_variables(self, sess): emb_a = self.model.A.eval() emb_a[self.params['pad_idx'], :] = 0 emb_b = self.model.B.eval() emb_b[self.params['pad_idx'], :] = 0 emb_c = self.model.C.eval() emb_c[self.params['pad_idx'], :] = 0 emb_ta = self.model.T_A.eval() emb_ta[self.params['pad_idx'], :] = 0 emb_tb = self.model.T_B.eval() emb_tb[self.params['pad_idx'], :] = 0 sess.run(self.model.A.assign(emb_a)) sess.run(self.model.B.assign(emb_b)) sess.run(self.model.C.assign(emb_c)) sess.run(self.model.T_A.assign(emb_ta)) sess.run(self.model.T_B.assign(emb_tb))
{"/main.py": ["/utils/commandParser.py", "/model/sentence_memNN_main.py"], "/loader/data_loader.py": ["/loader/funcs.py"]}
56,045
titanbt/deep_memNN
refs/heads/master
/nn/sentence_memNN.py
from sklearn.preprocessing import LabelBinarizer import numpy as np import tensorflow as tf from sklearn import metrics import lasagne.nonlinearities as nonlinearities class SentenceMemNN(object): def __init__(self, nwords=0, init_hid=0.1, init_std=0.05, batch_size=128, num_epochs=100, num_hops=7, embedd_dim=300, mem_size=78, lindim=75, max_grad_norm=50, pad_idx=0, embedd_table_aspect=None, lr=0.01): self.nwords = nwords self.init_hid = init_hid self.init_std = init_std self.batch_size = batch_size self.nepoch = num_epochs self.nhop = num_hops self.edim = embedd_dim self.mem_size = mem_size self.lindim = lindim self.max_grad_norm = max_grad_norm self.pad_idx = pad_idx self.embedd_table_aspect = embedd_table_aspect self.lr = lr self.hid = [] self.aspect = tf.placeholder(tf.int32, [self.batch_size, 1], name="input") self.loc = tf.placeholder(tf.int32, [self.batch_size, self.mem_size], name="location") self.target = tf.placeholder(tf.float32, [self.batch_size, 3], name="target") self.context = tf.placeholder(tf.int32, [self.batch_size, self.mem_size], name="context") def build_memory(self): self.global_step = tf.Variable(0, name="global_step") self.A = tf.Variable(tf.random_normal([self.nwords, self.edim], stddev=self.init_std)) self.B = tf.Variable(tf.random_normal([self.nwords, self.edim], stddev=self.init_std)) self.ASP = tf.Variable(tf.random_normal([self.embedd_table_aspect.shape[0], self.edim], stddev=self.init_std)) self.C = tf.Variable(tf.random_normal([self.edim, self.edim], stddev=self.init_std)) self.BL_W = tf.Variable(tf.random_normal([2 * self.edim, 1], stddev=self.init_std)) self.BL_B = tf.Variable(tf.zeros([1, 1])) # Location Encoding self.T_A = tf.Variable(tf.random_normal([self.mem_size + 1, self.edim], stddev=self.init_std)) self.T_B = tf.Variable(tf.random_normal([self.mem_size + 1, self.edim], stddev=self.init_std)) # m_i = sum A_ij * x_ij + T_A_i Ain_c = tf.nn.embedding_lookup(self.A, self.context) Ain_t = tf.nn.embedding_lookup(self.T_A, self.loc) Ain = tf.add(Ain_c, Ain_t) # c_i = sum B_ij * u + T_B_i Bin_c = tf.nn.embedding_lookup(self.B, self.context) Bin_t = tf.nn.embedding_lookup(self.T_B, self.loc) Bin = tf.add(Bin_c, Bin_t) ASPin = tf.nn.embedding_lookup(self.ASP, self.aspect) ASPout2dim = tf.reshape(ASPin, [-1, self.edim]) self.hid.append(ASPout2dim) for h in xrange(self.nhop): til_hid = tf.tile(self.hid[-1], [1, self.mem_size]) til_hid3dim = tf.reshape(til_hid, [-1, self.mem_size, self.edim]) a_til_concat = tf.concat([til_hid3dim, Ain], 2) til_bl_wt = tf.tile(self.BL_W, [self.batch_size, 1]) til_bl_3dim = tf.reshape(til_bl_wt, [self.batch_size, -1, 2 * self.edim]) att = tf.matmul(a_til_concat, til_bl_3dim, adjoint_b=True) til_bl_b = tf.tile(self.BL_B, [self.batch_size, self.mem_size]) til_bl_3dim = tf.reshape(til_bl_b, [-1, self.mem_size, 1]) g = tf.nn.tanh(tf.add(att, til_bl_3dim)) g_2dim = tf.reshape(g, [-1, self.mem_size]) P = tf.nn.softmax(g_2dim) probs3dim = tf.reshape(P, [-1, 1, self.mem_size]) Bout = tf.matmul(probs3dim, Bin) Bout2dim = tf.reshape(Bout, [-1, self.edim]) Cout = tf.matmul(self.hid[-1], self.C) Dout = tf.add(Cout, Bout2dim) if self.lindim == self.edim: self.hid.append(Dout) elif self.lindim == 0: self.hid.append(tf.nn.relu(Dout)) else: F = tf.slice(Dout, [0, 0], [self.batch_size, self.lindim]) G = tf.slice(Dout, [0, self.lindim], [self.batch_size, self.edim - self.lindim]) K = tf.nn.relu(G) self.hid.append(tf.concat([F, K], 1)) def build_network(self): self.build_memory() self.W = tf.Variable(tf.random_normal([self.edim, 3], stddev=self.init_std)) z = tf.matmul(self.hid[-1], self.W) self.loss = tf.nn.softmax_cross_entropy_with_logits(logits=z, labels=self.target) self.lr = tf.Variable(self.lr) self.opt = tf.train.GradientDescentOptimizer(self.lr) params = [self.A, self.B, self.C, self.T_A, self.T_B, self.W, self.ASP, self.BL_W, self.BL_B] grads_and_vars = self.opt.compute_gradients(self.loss, params) clipped_grads_and_vars = [(tf.clip_by_norm(gv[0], self.max_grad_norm), gv[1]) for gv in grads_and_vars] inc = self.global_step.assign_add(1) with tf.control_dependencies([inc]): self.optim = self.opt.apply_gradients(clipped_grads_and_vars) tf.initialize_all_variables().run() self.correct_prediction = tf.argmax(z, 1)
{"/main.py": ["/utils/commandParser.py", "/model/sentence_memNN_main.py"], "/loader/data_loader.py": ["/loader/funcs.py"]}
56,046
titanbt/deep_memNN
refs/heads/master
/loader/data_loader.py
import loader.funcs as funcs class DataLoader(object): def __init__(self, train_file, test_file, word_column, label_column, target_column, oov='embedding', embedding='glove', embedding_path=None): self.train_file = train_file self.test_file = test_file self.word_column = word_column self.label_column = label_column self.target_column = target_column self.embedding = embedding self.embedding_path = embedding_path self.oov = oov self.data = {'X_train': [], 'T_train': [], 'Y_train': [], 'mask_train': [], 'X_test': [], 'T_test': [], 'Y_test': [], 'mask_test': [], 'embedd_table': [], 'label_alphabet': [] } def load_data(self): self.data['X_train'], self.data['T_train'], self.data['Y_train'], self.data['mask_train'], \ self.data['X_test'], self.data['T_test'], self.data['Y_test'], self.data['mask_test'], \ self.data['embedd_table'], self.data['label_alphabet'] = funcs.load_dataset_sequence_labeling(self.train_file, self.test_file, word_column=self.word_column, target_column=self.target_column, label_column=self.label_column, oov=self.oov, embedding=self.embedding, embedding_path=self.embedding_path) return self.data
{"/main.py": ["/utils/commandParser.py", "/model/sentence_memNN_main.py"], "/loader/data_loader.py": ["/loader/funcs.py"]}
56,106
kiviev/createplaylist
refs/heads/master
/functions.py
#!/usr/bin/env python3 import os def find_files(files, dirs=[], extensions=[] , search = ''): new_dirs = [] search = search.lower() repace_underscore = search.replace("_" , " ") replace_blank = search.replace(" " , "_") for d in dirs: try: new_dirs += [ os.path.join(d, f) for f in os.listdir(d) ] except OSError: pathName = os.path.splitext(d)[0].lower() exten = os.path.splitext(d)[1].lower() if (pathName.find(search) != -1 or pathName.find(repace_underscore) != -1 or pathName.find(replace_blank) != -1) and exten in extensions: files.append(d) if new_dirs: find_files(files, new_dirs, extensions , search ) else: return def create_file(content , name , ext = '' , path = './'): if name == '': name = "Todo_playlist" f = open(path + name + "." + ext, 'w') f.write(content) f.close() def get_filenames(files , string = False , sort = False): filenames = [] for i in range(0,len(files)): filepath = files[i] path = filepath.split('/') filename = path[len(path) -1] filenames.append(filename) if sort : filenames.sort() return (filenames , "\n".join(filenames))[string] def strFile(files , sort = False): if sort: files.sort() return "\n".join(files) def create_or_change_path_output(pathOutput): if not os.path.exists(pathOutput): os.makedirs(pathOutput) os.chdir(pathOutput) def createPlayListSingle(lista , directorio , tipo , path , filename = ''): for i in lista: command = 'python3.5 ./crearPlaylistSingle.py -s "' + i + '" -d ' + directorio + ' -t ' + tipo + ' -p ' + path if filename != '': command += ' -f ' + filename os.system(command)
{"/crearPlaylistSingle.py": ["/functions.py", "/config.py"], "/Sample_mySearch.py": ["/functions.py"]}
56,107
kiviev/createplaylist
refs/heads/master
/crearPlaylistSingle.py
#!/usr/bin/env python3 import os ,argparse from functions import * from config import * # comienza ejecucion files = [] search = args.search pathOutputPlaylist = args.path dirs = [args.dir] extensiones = extensions[args.type] if args.filename: newFilename = args.filename else : newFilename = search print(search) # cambiamos al directorio create_or_change_path_output(pathOutputPlaylist) # hacemos la busqueda find_files(files , dirs , extensiones , search) # creamos el archivo en el path indicado create_file( strFile(files , True), newFilename , 'm3u', pathOutputPlaylist )
{"/crearPlaylistSingle.py": ["/functions.py", "/config.py"], "/Sample_mySearch.py": ["/functions.py"]}
56,108
kiviev/createplaylist
refs/heads/master
/Sample_mySearch.py
#!/usr/bin/env python3 ########## # remove from this file part of the name "Sample_" and with it you can work ########## from functions import createPlayListSingle AllArray = { "rock" : ["Led Zeppelin","Iron Maiden","Metallica"], "acction" :["Rambo","Rambo 2","Rambo 3"], "travel" : ["Hawai","Roma","Paris","Australia"], "all" : [''] } # with this path, search the entire personal folder createPlayListSingle(AllArray['rock'] ,'../../../' , 'audio', '/home/pack/playlist/music/') createPlayListSingle(AllArray['action'] ,'../../../../' , 'video', '/home/pack/playlist/video/films/action/') createPlayListSingle(AllArray['travel'] ,'../../../' , 'image', '/home/pack/playlist/photo/travels/') createPlayListSingle(AllArray['all'] ,'../../../' , 'video', '/home/pack/playlist/video/' , 'All Videos')
{"/crearPlaylistSingle.py": ["/functions.py", "/config.py"], "/Sample_mySearch.py": ["/functions.py"]}
56,109
kiviev/createplaylist
refs/heads/master
/AllPlaylist.py
#!/usr/bin/env python3 import os from mySearch import *
{"/crearPlaylistSingle.py": ["/functions.py", "/config.py"], "/Sample_mySearch.py": ["/functions.py"]}
56,110
kiviev/createplaylist
refs/heads/master
/config.py
#!/usr/bin/env python3 import os ,argparse parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument("-f", "--file", dest="filename", help="Nombre de salida del archivo FILE", metavar="FILE") parser.add_argument("-p", "--path", dest="path", help="Path del archivo de salida", metavar="PATH" , default="./") parser.add_argument("-s", "--search", dest="search", help="Expresion a buscar", metavar="SEARCH", default="") parser.add_argument("-d", "--dir", dest="dir" , required=True, help="Ruta relativa al archivo de salida donde buscar", metavar="DIR") parser.add_argument("-t", "--type", dest="type",required=True , help="Tipos de archivos para buscar [audio,video,image]", metavar="TYPE") parser.add_argument("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print status messages to stdout") args = parser.parse_args() # print(args.search) extensions = { "video" : ['.mp4' , '.avi' , '.flv' ,'.wmv' ,'.mkv' , '.mpg' , '.mpeg'] , "audio" : ['.mp3','.ogg' , '.wab' , '.wma' , '.webm'], "image" : [ '.gif' , '.jpg' , '.jpeg' , '.png' , ' .bmp' ] }
{"/crearPlaylistSingle.py": ["/functions.py", "/config.py"], "/Sample_mySearch.py": ["/functions.py"]}
56,120
flmn/rqalpha
refs/heads/master
/rqalpha/plot.py
# -*- coding: utf-8 -*- # # Copyright 2017 Ricequant, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def plot_result(result_dict, show_windows=True, savefile=None): import os from matplotlib import rcParams rcParams['font.family'] = 'sans-serif' rcParams['font.sans-serif'] = [ u'Microsoft Yahei', u'Heiti SC', u'Heiti TC', u'STHeiti', u'WenQuanYi Zen Hei', u'WenQuanYi Micro Hei', u"文泉驿微米黑", u'SimHei', ] + rcParams['font.sans-serif'] rcParams['axes.unicode_minus'] = False import numpy as np import matplotlib from matplotlib import gridspec import matplotlib.image as mpimg import matplotlib.pyplot as plt summary = result_dict["summary"] title = summary['strategy_file'] total_portfolios = result_dict["total_portfolios"] benchmark_portfolios = result_dict.get("benchmark_portfolios") index = total_portfolios.index # maxdrawdown xs = total_portfolios.portfolio_value.values rt = total_portfolios.total_returns.values max_dd_end = np.argmax(np.maximum.accumulate(xs) / xs) if max_dd_end == 0: max_dd_end = len(xs) - 1 max_dd_start = np.argmax(xs[:max_dd_end]) # maxdrawdown duration al_cum = np.maximum.accumulate(xs) a = np.unique(al_cum, return_counts=True) start_idx = np.argmax(a[1]) m = a[0][start_idx] al_cum_array = np.where(al_cum == m) max_ddd_start_day = al_cum_array[0][0] max_ddd_end_day = al_cum_array[0][-1] max_dd_info = "MaxDD {}~{}, {} days".format(index[max_dd_start], index[max_dd_end], (index[max_dd_end] - index[max_dd_start]).days) max_dd_info += "\nMaxDDD {}~{}, {} days".format(index[max_ddd_start_day], index[max_ddd_end_day], (index[max_ddd_end_day] - index[max_ddd_start_day]).days) plt.style.use('ggplot') red = "#aa4643" blue = "#4572a7" black = "#000000" plots_area_size = 0 if "plots" in result_dict: plots_area_size = 5 figsize = (18, 6 + int(plots_area_size * 0.9)) plt.figure(title, figsize=figsize) max_height = 10 + plots_area_size gs = gridspec.GridSpec(max_height, 8) # draw logo ax = plt.subplot(gs[:3, -1:]) ax.axis("off") filename = os.path.join(os.path.dirname(os.path.realpath(__file__)), "resource") filename = os.path.join(filename, "ricequant-logo.png") img = mpimg.imread(filename) ax.imshow(img, interpolation="nearest") ax.autoscale_view() # draw risk and portfolio font_size = 12 value_font_size = 11 label_height, value_height = 0.8, 0.6 label_height2, value_height2 = 0.35, 0.15 fig_data = [ (0.00, label_height, value_height, u"回测收益", "{0:.3%}".format(summary["total_returns"]), red, black), (0.15, label_height, value_height, u"回测年化收益", "{0:.3%}".format(summary["annualized_returns"]), red, black), (0.00, label_height2, value_height2, u"基准收益", "{0:.3%}".format(summary.get("benchmark_total_returns", 0)), blue, black), (0.15, label_height2, value_height2, u"基准年化收益", "{0:.3%}".format(summary.get("benchmark_annualized_returns", 0)), blue, black), (0.30, label_height, value_height, u"Alpha", "{0:.4}".format(summary["alpha"]), black, black), (0.40, label_height, value_height, u"Beta", "{0:.4}".format(summary["beta"]), black, black), (0.55, label_height, value_height, u"Sharpe", "{0:.4}".format(summary["sharpe"]), black, black), (0.70, label_height, value_height, u"Sortino", "{0:.4}".format(summary["sortino"]), black, black), (0.85, label_height, value_height, u"Information Ratio", "{0:.4}".format(summary["information_ratio"]), black, black), (0.30, label_height2, value_height2, u"Volatility", "{0:.4}".format(summary["volatility"]), black, black), (0.40, label_height2, value_height2, u"最大回撤", "{0:.3%}".format(summary["max_drawdown"]), black, black), (0.55, label_height2, value_height2, u"Tracking Error", "{0:.4}".format(summary["tracking_error"]), black, black), (0.70, label_height2, value_height2, u"Downside Risk", "{0:.4}".format(summary["downside_risk"]), black, black), ] ax = plt.subplot(gs[:3, :-1]) ax.axis("off") for x, y1, y2, label, value, label_color, value_color in fig_data: ax.text(x, y1, label, color=label_color, fontsize=font_size) ax.text(x, y2, value, color=value_color, fontsize=value_font_size) for x, y1, y2, label, value, label_color, value_color in [ (0.85, label_height2, value_height2, u"最大回撤/最大回撤持续期", max_dd_info, black, black)]: ax.text(x, y1, label, color=label_color, fontsize=font_size) ax.text(x, y2, value, color=value_color, fontsize=8) # strategy vs benchmark ax = plt.subplot(gs[4:10, :]) ax.get_xaxis().set_minor_locator(matplotlib.ticker.AutoMinorLocator()) ax.get_yaxis().set_minor_locator(matplotlib.ticker.AutoMinorLocator()) ax.grid(b=True, which='minor', linewidth=.2) ax.grid(b=True, which='major', linewidth=1) # plot two lines ax.plot(total_portfolios["total_returns"], label=u"策略", alpha=1, linewidth=2, color=red) if benchmark_portfolios is not None: ax.plot(benchmark_portfolios["total_returns"], label=u"基准", alpha=1, linewidth=2, color=blue) # plot MaxDD/MaxDDD ax.plot([index[max_dd_end], index[max_dd_start]], [rt[max_dd_end], rt[max_dd_start]], 'v', color='Green', markersize=8, alpha=.7, label=u"最大回撤") ax.plot([index[max_ddd_start_day], index[max_ddd_end_day]], [rt[max_ddd_start_day], rt[max_ddd_end_day]], 'D', color='Blue', markersize=8, alpha=.7, label=u"最大回撤持续期") # place legend leg = plt.legend(loc="best") leg.get_frame().set_alpha(0.5) # manipulate axis vals = ax.get_yticks() ax.set_yticklabels(['{:3.2f}%'.format(x * 100) for x in vals]) # plot user plots if "plots" in result_dict: plots_df = result_dict["plots"] ax2 = plt.subplot(gs[11:, :]) for column in plots_df.columns: ax2.plot(plots_df[column], label=column) leg = plt.legend(loc="best") leg.get_frame().set_alpha(0.5) if show_windows: plt.show() if savefile: fnmame = savefile if os.path.isdir(savefile): fnmame = os.path.join(savefile, "{}.png".format(summary["strategy_name"])) plt.savefig(fnmame, bbox_inches='tight')
{"/rqalpha/mod/analyser/mod.py": ["/rqalpha/plot.py"]}
56,121
flmn/rqalpha
refs/heads/master
/rqalpha/mod/analyser/mod.py
# -*- coding: utf-8 -*- # # Copyright 2017 Ricequant, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import pickle from collections import defaultdict import six from enum import Enum import numpy as np import pandas as pd from rqalpha.interface import AbstractMod from rqalpha.events import EVENT from rqalpha.const import ACCOUNT_TYPE, EXIT_CODE from rqalpha.utils.risk import Risk from rqalpha.utils.repr import properties from rqalpha.execution_context import ExecutionContext class AnalyserMod(AbstractMod): def __init__(self): self._env = None self._mod_config = None self._enabled = False self._result = None self._orders = defaultdict(list) self._trades = [] self._total_portfolios = [] self._sub_portfolios = defaultdict(list) self._positions = defaultdict(list) self._benchmark_daily_returns = [] self._portfolio_daily_returns = [] self._latest_portfolio = None self._latest_benchmark_portfolio = None def start_up(self, env, mod_config): self._env = env self._mod_config = mod_config self._enabled = (self._mod_config.record or self._mod_config.plot or self._mod_config.output_file or self._mod_config.plot_save_file or self._mod_config.report_save_path) if self._enabled: env.event_bus.add_listener(EVENT.POST_SETTLEMENT, self._collect_daily) env.event_bus.add_listener(EVENT.TRADE, self._collect_trade) env.event_bus.add_listener(EVENT.ORDER_CREATION_PASS, self._collect_order) def _collect_trade(self, account, trade): self._trades.append(self._to_trade_record(trade)) def _collect_order(self, account, order): self._orders[order.trading_datetime.date()].append(order) def _collect_daily(self): date = self._env.calendar_dt.date() portfolio = self._env.account.get_portfolio(date) self._latest_portfolio = portfolio self._portfolio_daily_returns.append(portfolio.daily_returns) self._total_portfolios.append(self._to_portfolio_record(date, portfolio)) if ACCOUNT_TYPE.BENCHMARK in self._env.accounts: self._latest_benchmark_portfolio = self._env.accounts[ACCOUNT_TYPE.BENCHMARK].portfolio self._benchmark_daily_returns.append(self._latest_benchmark_portfolio.daily_returns) else: self._benchmark_daily_returns.append(0) for account_type, account in six.iteritems(self._env.accounts): portfolio = account.get_portfolio(date) self._sub_portfolios[account_type].append(self._to_portfolio_record2(date, portfolio)) for order_book_id, position in six.iteritems(portfolio.positions): self._positions[account_type].append(self._to_position_record(date, order_book_id, position)) def _symbol(self, order_book_id): return self._env.data_proxy.instruments(order_book_id).symbol @staticmethod def _safe_convert(value, ndigits=3): if isinstance(value, Enum): return value.name if isinstance(value, (float, np.float64, np.float32, np.float16, np.float128)): return round(value, ndigits) return value def _to_portfolio_record(self, date, portfolio): data = { k: self._safe_convert(v, 3) for k, v in six.iteritems(properties(portfolio)) if not k.startswith('_') and not k.endswith('_') and k not in { "positions", "start_date", "starting_cash" } } data['date'] = date return data def _to_portfolio_record2(self, date, portfolio): data = { k: self._safe_convert(v, 3) for k, v in six.iteritems(portfolio.__dict__) if not k.startswith('_') and not k.endswith('_') and k not in { "positions", "start_date", "starting_cash" } } data['date'] = date return data def _to_position_record(self, date, order_book_id, position): data = { k: self._safe_convert(v, 3) for k, v in six.iteritems(properties(position)) if not k.startswith('_') and not k.endswith('_') } data['order_book_id'] = order_book_id data['symbol'] = self._symbol(order_book_id) data['date'] = date def _to_trade_record(self, trade): data = { k: self._safe_convert(v) for k, v in six.iteritems(properties(trade)) if not k.startswith('_') and not k.endswith('_') and k != 'order' } data['order_book_id'] = trade.order.order_book_id data['symbol'] = self._symbol(trade.order.order_book_id) data['datetime'] = data['datetime'].strftime("%Y-%m-%d %H:%M:%S") data['trading_datetime'] = data['trading_datetime'].strftime("%Y-%m-%d %H:%M:%S") return data def tear_down(self, code, exception=None): if code != EXIT_CODE.EXIT_SUCCESS or not self._enabled: return strategy_name = os.path.basename(self._env.config.base.strategy_file).split(".")[0] data_proxy = self._env.data_proxy summary = { 'strategy_name': strategy_name, } for k, v in six.iteritems(self._env.config.base.__dict__): if k in ["trading_calendar", "account_list", "timezone", "persist_mode", "resume_mode", "data_bundle_path", "handle_split", "persist"]: continue summary[k] = self._safe_convert(v, 2) risk = Risk(np.array(self._portfolio_daily_returns), np.array(self._benchmark_daily_returns), data_proxy.get_risk_free_rate(self._env.config.base.start_date, self._env.config.base.end_date), (self._env.config.base.end_date - self._env.config.base.start_date).days + 1) summary.update({ 'alpha': self._safe_convert(risk.alpha, 3), 'beta': self._safe_convert(risk.beta, 3), 'sharpe': self._safe_convert(risk.sharpe, 3), 'information_ratio': self._safe_convert(risk.information_ratio, 3), 'downside_risk': self._safe_convert(risk.annual_downside_risk, 3), 'tracking_error': self._safe_convert(risk.annual_tracking_error, 3), 'sortino': self._safe_convert(risk.sortino, 3), 'volatility': self._safe_convert(risk.annual_volatility, 3), 'max_drawdown': self._safe_convert(risk.max_drawdown, 3), }) summary.update({ k: self._safe_convert(v, 3) for k, v in six.iteritems(properties(self._latest_portfolio)) if k not in ["positions", "daily_returns", "daily_pnl"] }) if self._latest_benchmark_portfolio: summary['benchmark_total_returns'] = self._latest_benchmark_portfolio.total_returns summary['benchmark_annualized_returns'] = self._latest_benchmark_portfolio.annualized_returns trades = pd.DataFrame(self._trades) if 'datetime' in trades.columns: trades = trades.set_index('datetime') df = pd.DataFrame(self._total_portfolios) df['date'] = pd.to_datetime(df['date']) total_portfolios = df.set_index('date').sort_index() result_dict = { 'summary': summary, 'trades': trades, 'total_portfolios': total_portfolios, } if ExecutionContext.plots is not None: plots = ExecutionContext.plots.get_plots() plots_items = defaultdict(dict) for series_name, value_dict in six.iteritems(plots): for date, value in six.iteritems(value_dict): plots_items[date][series_name] = value plots_items[date]["date"] = date df = pd.DataFrame([dict_data for date, dict_data in six.iteritems(plots_items)]) df["date"] = pd.to_datetime(df["date"]) df = df.set_index("date").sort_index() result_dict["plots"] = df for account_type, account in six.iteritems(self._env.accounts): account_name = account_type.name.lower() portfolios_list = self._sub_portfolios[account_type] df = pd.DataFrame(portfolios_list) df["date"] = pd.to_datetime(df["date"]) portfolios_df = df.set_index("date").sort_index() result_dict["{}_portfolios".format(account_name)] = portfolios_df positions_list = self._positions[account_type] positions_df = pd.DataFrame(positions_list) if "date" in positions_df.columns: positions_df["date"] = pd.to_datetime(positions_df["date"]) positions_df = positions_df.set_index("date").sort_index() result_dict["{}_positions".format(account_name)] = positions_df self._result = result_dict if self._mod_config.output_file: with open(self._mod_config.output_file, 'wb') as f: pickle.dump(result_dict, f) if self._mod_config.plot: from rqalpha.plot import plot_result plot_result(result_dict) if self._mod_config.plot_save_file: from rqalpha.plot import plot_result plot_result(result_dict, False, self._mod_config.plot_save_file) if self._mod_config.report_save_path: from rqalpha.utils.report import generate_report generate_report(result_dict, self._mod_config.report_save_path)
{"/rqalpha/mod/analyser/mod.py": ["/rqalpha/plot.py"]}
56,122
flmn/rqalpha
refs/heads/master
/rqalpha/model/account/future_account.py
# -*- coding: utf-8 -*- # # Copyright 2017 Ricequant, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import six from ..margin import Margin from ...const import SIDE, POSITION_EFFECT, ACCOUNT_TYPE from ...utils.i18n import gettext as _ from ...utils.logger import user_system_log from ...execution_context import ExecutionContext from .base_account import BaseAccount class FutureAccount(BaseAccount): def __init__(self, env, init_cash, start_date): super(FutureAccount, self).__init__(env, init_cash, start_date, ACCOUNT_TYPE.FUTURE) self._margin_decider = Margin(env.config.base.margin_multiplier) @property def margin_decider(self): return self._margin_decider def before_trading(self): super(FutureAccount, self).before_trading() positions = self.portfolio.positions removing_ids = [] for order_book_id in positions.keys(): position = positions[order_book_id] if position._quantity == 0 and position._buy_open_order_quantity == 0 \ and position._sell_open_order_quantity == 0: removing_ids.append(order_book_id) for order_book_id in removing_ids: positions.pop(order_book_id, None) def after_trading(self): pass def settlement(self): portfolio = self.portfolio portfolio._portfolio_value = None positions = portfolio.positions data_proxy = ExecutionContext.get_data_proxy() trading_date = ExecutionContext.get_current_trading_dt().date() for order_book_id, position in six.iteritems(positions): settle_price = data_proxy.get_settle_price(order_book_id, trading_date) position._last_price = settle_price self._update_market_value(position, settle_price) self.portfolio_persist() portfolio._yesterday_portfolio_value = portfolio.portfolio_value de_listed_id_list = [] for order_book_id, position in six.iteritems(positions): # 检查合约是否到期,如果到期,则按照结算价来进行平仓操作 if position._de_listed_date is not None and trading_date >= position._de_listed_date.date(): de_listed_id_list.append(order_book_id) else: settle_price = data_proxy.get_settle_price(order_book_id, trading_date) self._update_holding_by_settle(position, settle_price) position._daily_realized_pnl = 0 position._buy_daily_realized_pnl = 0 position._sell_daily_realized_pnl = 0 for de_listed_id in de_listed_id_list: if positions[de_listed_id]._quantity != 0: user_system_log.warn( _("{order_book_id} is expired, close all positions by system").format(order_book_id=de_listed_id)) del positions[de_listed_id] portfolio._daily_transaction_cost = 0 def bar(self, bar_dict): portfolio = self.portfolio portfolio._portfolio_value = None positions = portfolio.positions for order_book_id, position in six.iteritems(positions): bar = bar_dict[order_book_id] if not bar.isnan: position._last_price = bar.close self._update_market_value(position, bar.close) def tick(self, tick): portfolio = self.portfolio portfolio._portfolio_value = None position = portfolio.positions[tick.order_book_id] position._last_price = tick.last_price self._update_market_value(position, tick.last_price) def order_pending_new(self, account, order): if self != account: return if order._is_final(): return order_book_id = order.order_book_id position = self.portfolio.positions[order_book_id] position._total_orders += 1 created_quantity = order.quantity created_value = order._frozen_price * created_quantity * position._contract_multiplier frozen_margin = self.margin_decider.cal_margin(order_book_id, order.side, created_value) self._update_order_data(position, order, created_quantity, created_value) self._update_frozen_cash(order, frozen_margin) def on_order_creation_pass(self, account, order): pass def order_creation_reject(self, account, order): if self != account: return order_book_id = order.order_book_id position = self.portfolio.positions[order_book_id] cancel_quantity = order.unfilled_quantity cancel_value = -order._frozen_price * cancel_quantity * position._contract_multiplier frozen_margin = self.margin_decider.cal_margin(order_book_id, order.side, cancel_value) self._update_order_data(position, order, -cancel_quantity, cancel_value) self._update_frozen_cash(order, frozen_margin) def order_pending_cancel(self, account, order): pass def order_cancellation_pass(self, account, order): if self != account: return order_book_id = order.order_book_id position = self.portfolio.positions[order_book_id] canceled_quantity = order.unfilled_quantity canceled_value = -order._frozen_price * canceled_quantity * position._contract_multiplier frozen_margin = self.margin_decider.cal_margin(order_book_id, order.order_book_id, canceled_value) self._update_order_data(position, order, -canceled_quantity, canceled_value) self._update_frozen_cash(order, frozen_margin) def order_cancellation_reject(self, account, order): pass def trade(self, account, trade): if self != account: return order = trade.order order_book_id = order.order_book_id bar_dict = ExecutionContext.get_current_bar_dict() portfolio = self.portfolio portfolio._portfolio_value = None position = portfolio.positions[order_book_id] position._is_traded = True position._total_trades += 1 trade_quantity = trade.last_quantity if order.position_effect == POSITION_EFFECT.OPEN: if order.side == SIDE.BUY: position._buy_avg_open_price = (position._buy_avg_open_price * position.buy_quantity + trade_quantity * trade.last_price) / (position.buy_quantity + trade_quantity) elif order.side == SIDE.SELL: position._sell_avg_open_price = (position._sell_avg_open_price * position.sell_quantity + trade_quantity * trade.last_price) / (position.sell_quantity + trade_quantity) minus_value_by_trade = -order._frozen_price * trade_quantity * position._contract_multiplier trade_value = trade.last_price * trade_quantity * position._contract_multiplier frozen_margin = self.margin_decider.cal_margin(order_book_id, order.side, minus_value_by_trade) portfolio._total_tax += trade.tax portfolio._total_commission += trade.commission portfolio._daily_transaction_cost = portfolio._daily_transaction_cost + trade.tax + trade.commission self._update_frozen_cash(order, frozen_margin) self._update_order_data(position, order, -trade_quantity, minus_value_by_trade) self._update_trade_data(position, trade, trade_quantity, trade_value) self._update_market_value(position, bar_dict[order_book_id].close) def order_unsolicited_update(self, account, order): if self != account: return order_book_id = order.order_book_id position = self.portfolio.positions[order.order_book_id] rejected_quantity = order.unfilled_quantity rejected_value = -order._frozen_price * rejected_quantity * position._contract_multiplier frozen_margin = self.margin_decider.cal_margin(order_book_id, order.side, rejected_value) self._update_order_data(position, order, -rejected_quantity, rejected_value) self._update_frozen_cash(order, frozen_margin) @staticmethod def _update_holding_by_settle(position, settle_price): position._prev_settle_price = settle_price position._buy_old_holding_list += position._buy_today_holding_list position._sell_old_holding_list += position._sell_today_holding_list position._buy_today_holding_list = [] position._sell_today_holding_list = [] def _update_trade_data(self, position, trade, trade_quantity, trade_value): """ 计算 [buy|sell]_trade_[value|quantity] 计算 [buy|sell]_[open|close]_trade_quantity 计算 [buy|sell]_settle_holding 计算 [buy|sell]_today_holding_list 计算 [buy|sell]_holding_cost 计算 [bar|sell]_margin 计算 daily_realized_pnl """ order = trade.order if order.side == SIDE.BUY: if order.position_effect == POSITION_EFFECT.OPEN: position._buy_open_trade_quantity += trade_quantity position._buy_open_trade_value += trade_value position._buy_open_transaction_cost += trade.commission position._buy_today_holding_list.insert(0, (trade.last_price, trade_quantity)) else: position._buy_close_trade_quantity += trade_quantity position._buy_close_trade_value += trade_value position._buy_close_transaction_cost += trade.commission delta_daily_realized_pnl = self._update_holding_by_close_action(trade) position._daily_realized_pnl += delta_daily_realized_pnl position._sell_daily_realized_pnl += delta_daily_realized_pnl position._buy_trade_quantity += trade_quantity position._buy_trade_value += trade_value else: if order.position_effect == POSITION_EFFECT.OPEN: position._sell_open_trade_quantity += trade_quantity position._sell_open_trade_value += trade_value position._sell_open_transaction_cost += trade.commission position._sell_today_holding_list.insert(0, (trade.last_price, trade_quantity)) else: position._sell_close_trade_quantity += trade_quantity position._sell_close_trade_value += trade_value position._sell_close_transaction_cost += trade.commission delta_daily_realized_pnl = self._update_holding_by_close_action(trade) position._daily_realized_pnl += delta_daily_realized_pnl position._buy_daily_realized_pnl += delta_daily_realized_pnl position._sell_trade_quantity += trade_quantity position._sell_trade_value += trade_value @staticmethod def _update_order_data(position, order, inc_order_quantity, inc_order_value): if order.side == SIDE.BUY: if order.position_effect == POSITION_EFFECT.OPEN: position._buy_open_order_quantity += inc_order_quantity position._buy_open_order_value += inc_order_value else: position._buy_close_order_quantity += inc_order_quantity position._buy_close_order_value += inc_order_value else: if order.position_effect == POSITION_EFFECT.OPEN: position._sell_open_order_quantity += inc_order_quantity position._sell_open_order_value += inc_order_value else: position._sell_close_order_quantity += inc_order_quantity position._sell_close_order_value += inc_order_value def _update_frozen_cash(self, order, inc_order_value): if order.position_effect == POSITION_EFFECT.OPEN: self.portfolio._frozen_cash += inc_order_value def _update_holding_by_close_action(self, trade): order = trade.order order_book_id = order.order_book_id position = self.portfolio.positions[order_book_id] settle_price = position._prev_settle_price left_quantity = trade.last_quantity delta_daily_realized_pnl = 0 if order.side == SIDE.BUY: # 先平昨仓 while True: if left_quantity == 0: break if len(position._sell_old_holding_list) == 0: break oldest_price, oldest_quantity = position._sell_old_holding_list.pop() if oldest_quantity > left_quantity: consumed_quantity = left_quantity position._sell_old_holding_list.append((oldest_price, oldest_quantity - left_quantity)) else: consumed_quantity = oldest_quantity left_quantity -= consumed_quantity delta_daily_realized_pnl += self._cal_daily_realized_pnl(trade, settle_price, consumed_quantity) # 再平今仓 while True: if left_quantity <= 0: break oldest_price, oldest_quantity = position._sell_today_holding_list.pop() if oldest_quantity > left_quantity: consumed_quantity = left_quantity position._sell_today_holding_list.append((oldest_price, oldest_quantity - left_quantity)) else: consumed_quantity = oldest_quantity left_quantity -= consumed_quantity delta_daily_realized_pnl += self._cal_daily_realized_pnl(trade, oldest_price, consumed_quantity) else: # 先平昨仓 while True: if left_quantity == 0: break if len(position._buy_old_holding_list) == 0: break oldest_price, oldest_quantity = position._buy_old_holding_list.pop() if oldest_quantity > left_quantity: consumed_quantity = left_quantity position._buy_old_holding_list.append((oldest_price, oldest_quantity - left_quantity)) else: consumed_quantity = oldest_quantity left_quantity -= consumed_quantity delta_daily_realized_pnl += self._cal_daily_realized_pnl(trade, settle_price, consumed_quantity) # 再平今仓 while True: if left_quantity <= 0: break oldest_price, oldest_quantity = position._buy_today_holding_list.pop() if oldest_quantity > left_quantity: consumed_quantity = left_quantity position._buy_today_holding_list.append((oldest_price, oldest_quantity - left_quantity)) left_quantity = 0 else: consumed_quantity = oldest_quantity left_quantity -= consumed_quantity delta_daily_realized_pnl += self._cal_daily_realized_pnl(trade, oldest_price, consumed_quantity) return delta_daily_realized_pnl @staticmethod def _update_market_value(position, price): """ 计算 market_value 计算 pnl 计算 daily_holding_pnl """ botq = position._buy_open_trade_quantity sctq = position._sell_close_trade_quantity bctq = position._buy_close_trade_quantity sotq = position._sell_open_trade_quantity position._buy_market_value = (botq - sctq) * price * position._contract_multiplier position._sell_market_value = (bctq - sotq) * price * position._contract_multiplier position._market_value = position._buy_market_value + position._sell_market_value def _cal_daily_realized_pnl(self, trade, cost_price, consumed_quantity): order = trade.order position = self.portfolio.positions[order.order_book_id] if order.side == SIDE.BUY: return (cost_price - trade.last_price) * consumed_quantity * position._contract_multiplier else: return (trade.last_price - cost_price) * consumed_quantity * position._contract_multiplier
{"/rqalpha/mod/analyser/mod.py": ["/rqalpha/plot.py"]}
56,124
buraktekin/barrkoda
refs/heads/master
/app.py
from pyzbar import pyzbar from imutils.video import VideoStream from imutils.video import FPS from modules.detect_barcodes import Detector import argparse as ap import numpy as np import datetime import time import imutils import cv2 # argument parser args_parser = ap.ArgumentParser() args_parser.add_argument("-nf", "--frames", type=int, default=100, help="# of frames to loop over for FPS test") args_parser.add_argument("-d", "--display", type=int, default=-1, help="Whether or not frames should be displayed") args_parser.add_argument("-o", "--output", type=str, default="barcodes.csv", help="path to CSV file keeping barcodes") args = vars(args_parser.parse_args()) # end of parser def scale_image(image): scale = 800.0 / image.shape[1] image = cv2.resize(image, (int(image.shape[1] * scale), int(image.shape[0] * scale))) return image # start streaming by the webcam (src=0 for webcam) print("[INFO]:: starting video stream...") video_stream = VideoStream(src=0).start() time.sleep(1) # open the output CSV file for writing and initialize the set of # barcodes found thus far csv = open(args["output"], "w") found = set() # loop over the frames from the video stream while True: # grab the frame from the threaded video stream and resize it to # # have a maximum width of 400 pixels frame = video_stream.read() # frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) frame = scale_image(frame) # find the barcodes in the frame and decode each of the barcodes barcodes = pyzbar.decode(frame) for barcode in barcodes: points = barcode.polygon if len(points) > 4: hull = cv2.convexHull(np.array([point for point in points], dtype=np.float32)) hull = list(map(tuple, np.squeeze(hull))) else: hull = points # the barcode data is a bytes object so if we want to draw it on # our output image we need to convert it to a string first barcode_content = barcode.data.decode('utf-8') barcode_type = barcode.type # Number of points in the convex hull n = len(hull) # Draw the convext hull for j in range(0,n): cv2.line(frame, hull[j], hull[ (j+1) % n], (255,0,0), 3) print("[INFO]:: Barcode Type {}, Barcode Object: {}".format(barcode_type, barcode_content)) # if the barcode text is currently not in our CSV file, write # the timestamp + barcode to disk and update the set if barcode_content not in found: csv.write("{},{}\n".format(datetime.datetime.now(), barcode_content)) csv.flush() found.add(barcode_content) # show the output image # show the output frame cv2.imshow("Barcode Scanner", frame) key = cv2.waitKey(1) & 0xFF # if the `q` key was pressed, break from the loop if key == ord("q"): out = cv2.imwrite('capture.jpg', frame) break # close the output CSV file do a bit of cleanup print("[INFO] cleaning up...") csv.close() cv2.destroyAllWindows() video_stream.stop()
{"/app.py": ["/modules/detect_barcodes.py"]}
56,125
buraktekin/barrkoda
refs/heads/master
/modules/detect_barcodes.py
import cv2 import matplotlib.pyplot as plt import numpy as np class Detector: def __init__(self, frame): self.frame = frame self.scale = 800 self.image = cv2.cvtColor(frame, cv2.IMREAD_GRAYSCALE) self.image_out = frame # will be fixed def scale_image(self): self.scale = 800.0 / self.image.shape[1] self.image = cv2.resize(self.image, (int(self.image.shape[1] * self.scale), int(self.image.shape[0] * self.scale))) return self.image def morphological_transformation(self): # blackhat transformation kernel = np.ones((1, 3), np.uint8) self.image = cv2.morphologyEx(self.image, cv2.MORPH_BLACKHAT, kernel, anchor=(1, 0)) thresh, self.image = cv2.threshold(self.image, 10, 255, cv2.THRESH_BINARY) kernel = np.ones((1, 5), np.uint8) # set the kernel for convolution # dilation self.image = cv2.morphologyEx( self.image, cv2.MORPH_DILATE, kernel, anchor=(2, 0), iterations=2 ) # closing self.image = cv2.morphologyEx( self.image, cv2.MORPH_CLOSE, kernel, anchor=(2, 0), iterations=2 ) # Opening kernel = np.ones((21, 35), np.uint8) self.image = cv2.morphologyEx(self.image, cv2.MORPH_OPEN, kernel, iterations=1) return self.image def set_contours(self): contours, hierarchy = cv2.findContours(self.image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) unscale = 1.0 / self.scale if contours != None: for contour in contours: if cv2.contourArea(contour) <= 2000: continue rect = cv2.minAreaRect(contour) rect = ( (int(rect[0][0] * unscale), int(rect[0][1] * unscale)), (int(rect[1][0] * unscale), int(rect[1][1] * unscale)), rect[2] ) box = np.int0(cv2.cv2.BoxPoints(rect)) cv2.drawContours(self.image_out, [box], 0, (0, 255, 0), thickness=2) return self.image_out def detect(self): self.scale_image() self.morphological_transformation() self.set_contours() plt.imshow(self.image_out) cv2.imwrite(r'./out.png', self.image_out) return self.image_out
{"/app.py": ["/modules/detect_barcodes.py"]}
56,128
fsay2604/PI_maison_intelligente
refs/heads/main
/Sensor/gas_sensor.py
#!/usr/bin/env python ########################################################################## # Auteurs: Francois Charles Hebert & Samuel Fournier # Classe: Représente le sensor de gaz. (pour notre détecteur de fumé) ########################################################################## class Gas_Sensor: # Constructeur def __init__(self): pass # Fonction qui lit la valeur et la renvoit. def read(self, adc): value = adc.analogRead(1) # Verifier le channel, probablement a changer! le sensor de flamme est sur le channel 0 aussi. #print ('Gas concentration:', value) return value
{"/publisher_sensors.py": ["/Sensor/flame_sensor.py", "/Sensor/gas_sensor.py"], "/main.py": ["/Sensor/ventilation.py", "/Sensor/lcd.py"]}
56,129
fsay2604/PI_maison_intelligente
refs/heads/main
/publisher_sensors.py
#!/usr/bin/env python3 ########################################################################## # Auteurs: Francois Charles Hebert & Samuel Fournier # Projet: Système d'alarme d'une maison. ########################################################################## # Imports import paho.mqtt.client as mqtt import RPi.GPIO as GPIO import signal import sys from ADCDevice import * from Sensor.flame_sensor import Flame_Sensor from Sensor.gas_sensor import Gas_Sensor import Sensor.Freenove_DHT as DHT import json import time # Global variables FlamePin = 15 TempPin = 35 FlameSensor = None FLAME_SENSOR_PREVIOUS_VAL = 0 GasSensor = None GAS_SENSOR_PREVIOUS_VAL = 0 Temp_sensor = None #(DHT) TEMP_SENSOR_PREVIOUS_VAL = 0 adc = ADCDevice() TOPIC = 'SENSORS' BROKER_HOST = '192.168.137.213' BROKER_PORT = 1883 CLIENT_ID = 'SYS_ALARME_SENSORS' client = None """ ======= >>>>>>> 7553c77373322088de519233c7f57e1df8c8e1cd # Callback qui s'execute lors de la detection de l'event def myISR(ev=None): global TOPIC print("Flame is detected !") data = {'FLAME_STATE':'on'} client.publish(TOPIC, payload=json.dumps(data), qos=0, retain=False) print("send FLAME_STATE = " + data['FLAME_STATE'] + " to " + TOPIC) """ def init(): global FlameSensor global GasSensor global FlamePin global TempSensor global adc # ADC if(adc.detectI2C(0x48)): # Detect the pcf8591. adc = PCF8591() elif(adc.detectI2C(0x4b)): # Detect the ads7830 adc = ADS7830() else: print("No correct I2C address found, \n" "Please use command 'i2cdetect -y 1' to check the I2C address! \n" "Program Exit. \n"); exit(-1) #Flame sensor init GPIO.setmode(GPIO.BOARD) #GPIO.setup(FlamePin, GPIO.IN, pull_up_down=GPIO.PUD_UP) #GPIO.add_event_detect(FlamePin, GPIO.FALLING, callback=myISR) GasSensor = Gas_Sensor() TempSensor = DHT.DHT(TempPin) # Fonction qui va loop a l'infini et va lire les valeurs lu des differents sensor. # Lorsque les valeurs depassent un certain niveau, on va publier un message. def loop(): global TOPIC global FlameSensor global FLAME_SENSOR_PREVIOUS_VAL global GAS_SENSOR_PREVIOUS_VAL global GasSensor global TempSensor global TEMP_SENSOR_PREVIOUS_VAL global adc while True: # Récupération de la valeur du sensor et envoit du msg FlameSensor = readFlamme() #print(FlameSensor) if(FlameSensor > 10): data = {'FLAME_STATE':'on'} client.publish(TOPIC, payload=json.dumps(data), qos=0, retain=False) print("send FLAME_STATE = " + data['FLAME_STATE'] + " to " + TOPIC) time.sleep(0.5) if (FLAME_SENSOR_PREVIOUS_VAL >= 10 and FlameSensor < 10): data = {'FLAME_STATE':'off'} client.publish(TOPIC, payload=json.dumps(data), qos=0, retain=False) print("send FLAME_STATE = " + data['FLAME_STATE'] + " to " + TOPIC) time.sleep(0.5) # Récupération de la valeur du sensor et envoit du msg gas_val = GasSensor.read(adc) if(gas_val > 50): data = {'GAS_STATE':'on'} client.publish(TOPIC, payload=json.dumps(data), qos=0, retain=False) print("send GAS_STATE = " + data['GAS_STATE'] + " to " + TOPIC) time.sleep(0.5) if (GAS_SENSOR_PREVIOUS_VAL >= 50 and gas_val < 50): data = {'GAS_STATE':'off'} client.publish(TOPIC, payload=json.dumps(data), qos=0, retain=False) print("send GAS_STATE = " + data['GAS_STATE'] + " to " + TOPIC) time.sleep(0.5) #print(gas_val) # Récupération de la valeur du sensor et envoit du msg TempValue = TempSensor.readDHT11() if TempValue is TempSensor.DHTLIB_OK: if(TempSensor.temperature > 30): data = {'VENTILATION':'on'} client.publish(TOPIC, payload=json.dumps(data), qos=0, retain=False) print("send VENTILATION = " + data['VENTILATION'] + " to " + TOPIC) time.sleep(0.5) if (TEMP_SENSOR_PREVIOUS_VAL >= 30 and TempSensor.temperature < 30): data = {'VENTILATION':'off'} client.publish(TOPIC, payload=json.dumps(data), qos=0, retain=False) print("send VENTILATION = " + data['VENTILATION'] + " to " + TOPIC) time.sleep(0.5) #print(TempSensor.temperature) GAS_SENSOR_PREVIOUS_VAL = gas_val TEMP_SENSOR_PREVIOUS_VAL = TempSensor.temperature FLAME_SENSOR_PREVIOUS_VAL = FlameSensor time.sleep(0.7) # Fonction qui lit la valeur et la renvoit. def readFlamme(): global adc res = adc.analogRead(0) # read ADC value of channel 0 #print('res = ', res) return res #### # Fonctions pour le MQTT #### def on_connect(client, userdata, flags, rc): print("Connected with result code {rc}") def signal_handler(sig, frame): """Capture Control+C and disconnect from Broker.""" client.disconnect() # Graceful disconnection. GPIO.cleanup() sys.exit(0) def init_mqtt(): global client client = mqtt.Client(client_id=CLIENT_ID, clean_session=False) client.on_connect = on_connect # create connection, the three parameters are broker address, broker port number, and keep-alive time respectively client.connect(BROKER_HOST, BROKER_PORT) init() init_mqtt() if __name__ == "__main__": signal.signal(signal.SIGINT, signal_handler) # Capture Control + C loop() signal.pause()
{"/publisher_sensors.py": ["/Sensor/flame_sensor.py", "/Sensor/gas_sensor.py"], "/main.py": ["/Sensor/ventilation.py", "/Sensor/lcd.py"]}
56,130
fsay2604/PI_maison_intelligente
refs/heads/main
/Sensor/ventilation.py
from gpiozero import Device, Motor, OutputDevice from gpiozero.pins.pigpio import PiGPIOFactory import time class ventilation: # defining variables MOTOR_PINS = [23, 24] ENABLE_PIN = 18 motor = None def __init__(self): self.motor = Motor(forward=self.MOTOR_PINS[1], backward=self.MOTOR_PINS[0],enable=self.ENABLE_PIN,pwm=True) self.motor.stop() pass def move(self,speed=0): if(speed==0): self.motor.stop() elif(speed >0): self.motor.forward(speed) elif(speed < 0): speed = speed*-1 self.motor.backward(speed) if __name__ == '__main__': print("program starting") m = ventilation() while True: m.move(0.5) print("ending")
{"/publisher_sensors.py": ["/Sensor/flame_sensor.py", "/Sensor/gas_sensor.py"], "/main.py": ["/Sensor/ventilation.py", "/Sensor/lcd.py"]}
56,131
fsay2604/PI_maison_intelligente
refs/heads/main
/main.py
#!/usr/bin/env python ########################################################################## # Auteurs: Francois Charles Hebert & Samuel Fournier # Projet: Système d'alarme d'une maison. ########################################################################## # Imports import RPi.GPIO as GPIO from gpiozero import Device, LED, Buzzer, Button from gpiozero.pins.pigpio import PiGPIOFactory from ADCDevice import * from Sensor.ventilation import ventilation from Sensor.lcd import lcd import signal import json import paho.mqtt.client as mqtt import time # Initialize GPIO Device.pin_factory = PiGPIOFactory() # Set GPIOZero to use PiGPIO by default. # Global Variables BROKER_HOST = '192.168.137.213' # (2) BROKER_PORT = 1883 CLIENT_ID = "SYS_ALARME" # (3) TOPIC = "SENSORS" TOPIC_PUB = "MAINBOARD_WEB" TOPIC_SUB = "MAINBOARD" # (4) client = None # MQTT client instance. See init_mqtt() ## PINS (header) ButtonPin = 17 ButtonState = None BuzzerPin = 27 buzzer = None # Global variables Leds = [None, None] ventilation = ventilation() lcd = lcd() fire_state = { 'flame_state' : 'off' } gas_state = { 'gas_state' : 'off' } ventilation_state = {'ventilation' : 'off'} previous_ventilation_state = 'off' alarm_state = {'alarm' : 'off'} def button_pressed(): global alarm_state if alarm_state['alarm'] == 'on': alarm_state['alarm'] = 'off' elif alarm_state['alarm'] == 'off': alarm_state['alarm'] = 'on' client.publish(TOPIC_SUB,json.dumps(alarm_state)) client.publish(TOPIC_PUB,json.dumps(alarm_state)) # Functions def init(): global Leds global ButtonState global buzzer global ventilation lcd.set_message("Alarm active.") Leds[0] = LED(16) # Red Leds[0].on() Leds[1] = LED(21) # Green Leds[1].off() ButtonState = Button(ButtonPin, pull_up=True, bounce_time=0.1) ButtonState.when_pressed = button_pressed buzzer = Buzzer(BuzzerPin,active_high = False) buzzer.off() # Fonction qui gere les receptions de messages def logic(): global fire_state global gas_state global ventilation_state global previous_ventilation_state global alarm_state global buzzer global Leds global ventilation global lcd if previous_ventilation_state != ventilation_state['ventilation'] : if ventilation_state['ventilation'] == 'on': ventilation.move(0.25) # part la ventilation previous_ventilation_state = 'on' elif ventilation_state['ventilation'] == 'off': ventilation.move(0) previous_ventilation_state = 'off' # Si l'alarme est active if alarm_state['alarm'] == 'on': Leds[1].on() # Verifie si l'alarme doit partir en fonction des states if fire_state['flame_state'] or gas_state['gas_state'] == 'on': buzzer.on() # part l'alarme Leds[0].blink() # set la lumiere rouge a blink pour signifier un probleme lcd.set_message("Alarm active \n and triggered!") # Part la ventilation si le gas est detecté if gas_state['gas_state'] == 'on': ventilation_state['ventilation'] = 'on' if previous_ventilation_state != ventilation_state['ventilation'] : if ventilation_state['ventilation'] == 'off': ventilation.move(0.25) # part la ventilation previous_ventilation_state = 'on' else: ventilation.move(0) # Ferme la ventilation previous_ventilation_state = 'off' if fire_state['flame_state'] == 'on': time.sleep(5) fire_state['flame_state'] = 'off' client.publish(TOPIC_PUB,json.dumps(fire_state)) # Reinitilise les composants if fire_state['flame_state'] and gas_state['gas_state'] == 'off': buzzer.off() # Ferme l'alarme Leds[0].off() # Ferme la led rouge Leds[1].on() # Allume la led verte ventilation.move(0) # Ferme la ventilation previous_ventilation_state = 'off' lcd.set_message("Alarm active.") else: Leds[0].on() Leds[1].off() lcd.set_message("Alarm inactive.") time.sleep(0.2) """ MQTT Related Functions and Callbacks """ def on_connect(client, user_data, flags, connection_result_code): """on_connect is called when our program connects to the MQTT Broker. Always subscribe to topics in an on_connect() callback. This way if a connection is lost, the automatic re-connection will also results in the re-subscription occurring.""" # Subscribe to the topic client.subscribe(TOPIC, qos=0) # Recevoir les donnees des sensors client.subscribe(TOPIC_SUB, qos=0) # Recevoir les donnees du web def on_disconnect(client, user_data, disconnection_result_code): """Called disconnects from MQTT Broker.""" pass def on_message(client, userdata, msg): """Callback called when a message is received on a subscribed topic.""" global fire_state global gas_state global ventilation_state global alarm_state data = None data = json.loads(msg.payload.decode("UTF-8")) if "VENTILATION" in data: # Gestion du state de la ventilation if data['VENTILATION'] == 'on': ventilation_state['ventilation'] = 'on' if data['VENTILATION'] == 'off': ventilation_state['ventilation'] = 'off' client.publish(TOPIC_PUB,json.dumps(ventilation_state)) if "ALARM" in data: # Gestion du state du systeme d'alarme if data['ALARM'] == 'on': alarm_state['alarm'] = 'on' if data['ALARM'] == 'off': alarm_state['alarm'] = 'off' client.publish(TOPIC_PUB,json.dumps(alarm_state)) if alarm_state['alarm'] == 'on': if "FLAME_STATE" in data: #print("message received", str(msg.payload.decode("utf-8"))) #print("message Topic= ", msg.topic) # Gestion du state de la ventilation if data['FLAME_STATE'] == 'on': fire_state['flame_state'] = 'on' if data['FLAME_STATE'] == 'off': fire_state['flame_state'] = 'off' client.publish(TOPIC_PUB,json.dumps(fire_state)) if "GAS_STATE" in data: #print("message received", str(msg.payload.decode("utf-8"))) #print("message Topic= ", msg.topic) # Gestion du state de la ventilation if data['GAS_STATE'] == 'on': gas_state['gas_state'] = 'on' if data['GAS_STATE'] == 'off': gas_state['gas_state'] = 'off' client.publish(TOPIC_PUB,json.dumps(gas_state)) # Gestion de la logique en fonction des states #print(data) logic() def signal_handler(sig, frame): """Capture Control+C and disconnect from Broker.""" global buzzer global Leds #logger.info("You pressed Control + C. Shutting down, please wait...") client.disconnect() # Graceful disconnection. Leds[0].off() Leds[1].off() buzzer.off() GPIO.cleanup() #sys.exit(0) def init_mqtt(): global client global CLIENT_ID global TOPIC # Our MQTT Client. See PAHO documentation for all configurable options. # "clean_session=True" means we don"t want Broker to retain QoS 1 and 2 messages # for us when we"re offline. You"ll see the "{"session present": 0}" logged when # connected. client = mqtt.Client( # (15) client_id=CLIENT_ID, clean_session=False) # Route Paho logging to Python logging. # (16) # Setup callbacks client.on_connect = on_connect # (17) client.on_disconnect = on_disconnect client.on_message = on_message # Connect to Broker. client.connect(BROKER_HOST, BROKER_PORT) init() init_mqtt() ### DEBUT DU SCRIPT #### if __name__ == '__main__': print("program starting..") signal.signal(signal.SIGINT, signal_handler) # Capture Control + C client.loop_forever() signal.pause()
{"/publisher_sensors.py": ["/Sensor/flame_sensor.py", "/Sensor/gas_sensor.py"], "/main.py": ["/Sensor/ventilation.py", "/Sensor/lcd.py"]}
56,132
fsay2604/PI_maison_intelligente
refs/heads/main
/Sensor/lcd.py
#!/usr/bin/env python3 ######################################################################## # Filename : I2CLCD1602.py # Description : Use the LCD display data # Author : freenove # modification: 2018/08/03 ######################################################################## from Sensor import PCF8574 from Sensor import Adafruit_LCD1602 class lcd: mcp = None lcd = None def __init__(self): PCF8574_address = 0x27 # I2C address of the PCF8574 chip. PCF8574A_address = 0x3F # I2C address of the PCF8574A chip. # Create PCF8574 GPIO adapter. try: self.mcp = PCF8574.PCF8574_GPIO(PCF8574_address) except: try: self.mcp = PCF8574.PCF8574_GPIO(PCF8574A_address) except: print ('I2C Address Error !') exit(1) # Create LCD, passing in MCP GPIO adapter. self.lcd = Adafruit_LCD1602.Adafruit_CharLCD(pin_rs=0, pin_e=2, pins_db=[4,5,6,7], GPIO=self.mcp) self.mcp.output(3,1) # turn on LCD backlight self.lcd.begin(16,2) # set number of LCD lines and columns def set_message(self,msg): self.lcd.clear() self.lcd.setCursor(0,0) # set cursor position self.lcd.message(msg)
{"/publisher_sensors.py": ["/Sensor/flame_sensor.py", "/Sensor/gas_sensor.py"], "/main.py": ["/Sensor/ventilation.py", "/Sensor/lcd.py"]}
56,133
fsay2604/PI_maison_intelligente
refs/heads/main
/Sensor/flame_sensor.py
#!/usr/bin/env python ########################################################################## # Auteurs: Francois Charles Hebert & Samuel Fournier # Classe: Représente le sensor de flamme. ########################################################################## import RPi.GPIO as GPIO from ADCDevice import * from time import sleep class Flame_Sensor: FlamePin = 15 # Constructeur def __init__(self): GPIO.setmode(GPIO.BOARD) GPIO.setup(self.FlamePin, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(self.FlamePin, GPIO.FALLING, callback=self.myISR) # Callback qui s'execute lors de la detection de l'event def myISR(self,ev=None): print("Flame is detected !") if GPIO.input(self.FlamePin): print('HI') else: print('LOW') # Fonction qui lit la valeur et la renvoit. def read(self, adc): res = adc.analogRead(0) # read ADC value of channel 0 print('res = ', res) return res if __name__ == "__main__": adc = ADCDevice() # ADC if(adc.detectI2C(0x48)): # Detect the pcf8591. adc = PCF8591() elif(adc.detectI2C(0x4b)): # Detect the ads7830 adc = ADS7830() else: print("No correct I2C address found, \n" "Please use command 'i2cdetect -y 1' to check the I2C address! \n" "Program Exit. \n"); exit(-1) f = Flame_Sensor() while True: f.read(adc) sleep(0.5)
{"/publisher_sensors.py": ["/Sensor/flame_sensor.py", "/Sensor/gas_sensor.py"], "/main.py": ["/Sensor/ventilation.py", "/Sensor/lcd.py"]}
56,178
rmeritz/pycon-sweden-2015
refs/heads/master
/models.py
## job/models.py from django.db import models from .managers import JobsManager class Job(models.Model): objects = JobsManager() name = models.CharField(blank=False, max_length=100, null=False) published = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) # Ran from the command line $ python manage.py makemigrations jobs # job/managers.py from django.db.models import Manager class JobManager(Manager): #TODO: write to match publiushed def get_queryset(self): return super(JobManager, self).get_queryset().filter(published=True) # From the console >>> Job.objects.get(id=2) >>> Job.objects.all() ### Notes: # * From the docs: "A Manager is the interface through which database # query operations are provided to Django models. # At least one Manager exists for every model in a Django application." # * Migration are autogenerated by examining the changed in your models # * Migrations are order by number # * Migrations can depend_on migrations from other apps # * Migrations aren't timestamped # * Migrations are seperated by "app" # * The concept of an "app" is very different than Rail's concept # * super is super explicate # * imports are super explicate
{"/forms.py": ["/models.py"], "/routes.py": ["/views.py"]}
56,179
rmeritz/pycon-sweden-2015
refs/heads/master
/views.py
# Class Based Views: # http://ccbv.co.uk/
{"/forms.py": ["/models.py"], "/routes.py": ["/views.py"]}
56,180
rmeritz/pycon-sweden-2015
refs/heads/master
/forms.py
# jobs/forms.py from datetime import timedelta from django import forms from obscene import is_obscene from .models import Job class JobCreateForm(forms.ModelForm): class Meta: model = Job fields = ["name", "description", "start_date"] def clean_name(self): name = self.cleaned_data.get('name') if is_obscene(name): raise forms.ValidationError('You may not choose an obscene name') return name def save(self, *args, **kwargs): kwargs.update({'commit': False}) job = super(JobCreateForm, self).save(*args, **kwargs) job.end_date = job.start_date + timedelta(days=30) job.save return job ### Notes: # * Django Forms handle many aspects of handling data in one place # 1) preparing and restructuring data ready for rendering # 2) creating HTML forms for the data # 3) receiving and processing submitted forms and data from the client # * Self is
{"/forms.py": ["/models.py"], "/routes.py": ["/views.py"]}
56,181
rmeritz/pycon-sweden-2015
refs/heads/master
/routes.py
# urls.py from django.conf.urls import include, patterns urlpatterns = patterns( '', (r'^jobs/', include("skill_and_love.job.urls")), ) # job/urls.py from django.conf.urls import url, patterns from .views import CreateJobView urlpatterns = patterns( '', url(r'^create/$', CreateJobView.as_view(), name='job_create'), )
{"/forms.py": ["/models.py"], "/routes.py": ["/views.py"]}
56,182
rmeritz/pycon-sweden-2015
refs/heads/master
/view.py
# templates/base/form.html <form action="{% url create_job %}" method="post"> {% csrf_token %} {{ form.non_field_errors }} <div class="form-inputs"> {{ form.as_p }} </div> <div class="form-actions"> <input type="submit" value="Submit"> </div> </form>
{"/forms.py": ["/models.py"], "/routes.py": ["/views.py"]}
56,183
rmeritz/pycon-sweden-2015
refs/heads/master
/controller.py
#job/views.py from django.views.generic import CreateView from .models import Job from .forms import CreateJobForm class JobCreateView(CreateView): model = Job form_class = CreateJobForm # django/django/blob/1.7/django/views/generic/edit.py class CreateView ... def post(self, request, *args, **kwargs): """ Handles POST requests, instantiating a form instance with the passed POST variables and then checked for validity. """ form_class = self.get_form_class() form = self.get_form(form_class) if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) ### Notes: # * Class Based Views are awesome # * Can easily package views for third-party apps # * Easy for someone to modify any small part of their behavoir # * Instead of creating a Rails Engine
{"/forms.py": ["/models.py"], "/routes.py": ["/views.py"]}
56,192
AntonShpakovych/homework_5_PYTHON_files
refs/heads/main
/module_class.py
from datetime import datetime import os import requests succes_file = open('file_log/access.log', "a") error_file = open('file_log/error.log', "a") class GetInfo: def __init__(self, url): self.url = url def show_object(self): try: URL = self.url response = requests.get(URL) PB = response.json() succes_file.write(f"| {os.getlogin()} | {datetime.today().strftime('%d.%m.%Y %H:%M:%S')}\ | {str(response.status_code)} {str(response.reason)} Operation success!\n") return(PB) except Exception as ex: error_file.write(f"| {os.getlogin()} | {datetime.today().strftime('%d.%m.%Y %H:%M:%S')}\ | {str(response.status_code)} {str(response.reason)} Operation failed!\n") finally: succes_file.close() error_file.close() us = GetInfo( 'https://api.privatbank.ua/p24api/exchange_rates?json&date=20.06.2021') print(us.show_object())
{"/app.py": ["/module_class.py", "/module.py"]}
56,193
AntonShpakovych/homework_5_PYTHON_files
refs/heads/main
/app.py
from module_class import GetInfo from module import * data = {} data['exchangeRate'] = [] data['exchangeRate'].append({ 'baseCurrency': 'UAH', 'currency': 'USD', 'saleRateNB': 27.0275, 'purchaseRateNB': 27.0275, 'saleRate': 27.18, 'purchaseRate': 26.75 }) data['exchangeRate'].append({ 'baseCurrency': 'UAH', 'currency': 'PLZ', 'saleRateNB': 7.2526, 'purchaseRateNB': 7.2526, 'saleRate': 7.35, 'purchaseRate': 7.05 }) data['exchangeRate'].append({ 'baseCurrency': 'UAH', 'currency': 'EUR', 'saleRateNB': 32.7722, 'purchaseRateNB': 32.7722, 'saleRate': 32.95, 'purchaseRate': 32.35 }) # us = GetInfo( # 'https://api.privatbank.ua/p24api/exchange_rates?json&date=01.12.2014') # print(us.show_object()) # write_json('file/file_1.json', data)
{"/app.py": ["/module_class.py", "/module.py"]}
56,194
AntonShpakovych/homework_5_PYTHON_files
refs/heads/main
/module.py
import json import csv from os import path, sep from openpyxl import Workbook from openpyxl import load_workbook """Module with func""" # -------JSON------------------ def write_json(path_file, data): with open(path_file, 'w') as outfile: json.dump(data, outfile, indent=4, sort_keys=True, ensure_ascii=True) outfile.close() def read_json(path_file): file = open(path_file, 'r') data = json.loads(file.read()) for item in data['exchangeRate']: print(item) file.close() # ----------------CSV-------------------------- def write_csv(path_file, data): header = list(data['exchangeRate'][0].keys()) with open(path_file, 'w', encoding='UTF8', newline='') as file: writer = csv.DictWriter(file, fieldnames=header) writer.writeheader() writer.writerows(data['exchangeRate']) file.close() def read_csv(path_file): with open(path_file, 'r', encoding='UTF8', newline='') as file: filereader = csv.DictReader(file) for row in filereader: print(row) file.close() # -------------XLSX------------------------ def write_xlsx(path_name, data): workbook = Workbook() sheet = workbook.active sheet.title = 'PB_data' for index, item in enumerate(list(data['exchangeRate'][0].keys())): sheet.cell(row=1, column=index+1).value = item row_num = 1 for row in data['exchangeRate']: row_num += 1 for index, key in enumerate(list(row.keys())): sheet.cell(row=row_num, column=index+1).value = row[key] workbook.save(filename="./file/file_3.xlsx") def read_xlsx(path_name): workbook = load_workbook(filename=path_name) workbook.sheetnames sheet = workbook.active data = {} data['exchangeRate'] = [] keys = [] for value in sheet.iter_rows(min_row=1, max_row=1, min_col=1, max_col=6, values_only=True): for id, key in enumerate(value): keys.append(key) for values in sheet.iter_rows(min_row=2, max_row=4, min_col=1, max_col=6, values_only=True): row = {} for id, value in enumerate(values): row.update({keys[id]: value}) data['exchangeRate'].append(row) print(data)
{"/app.py": ["/module_class.py", "/module.py"]}
56,195
rebelopsio/apiMacroCalc
refs/heads/main
/calculations.py
from collections import namedtuple class Calculations: @staticmethod def basal_metabolic_rate(sex: str, age: int, height_inches: int, weight: int) -> float: bmr = 0.0 if sex.upper() == "MALE": bmr = (10 * (weight / 2.2)) + (6.25 * (height_inches * 2.54) ) - ((5 * age) + 5) # Mifflin-St. Jeor formula elif sex.upper() == "FEMALE": bmr = (10 * (weight / 2.2)) + (6.25 * (height_inches * 2.54) ) - ((5 * age) + 5) - 161 # Mifflin-St. Jeor formula return bmr @staticmethod def caloric_intake(bmr: float, type: str) -> float: multiplier = 0.0 if type == "rest": multiplier = 1.2 elif type == "light": multiplier = 1.375 elif type == "moderate": multiplier = 1.55 elif type == "hard": multiplier = 1.725 calories = bmr * multiplier return calories @staticmethod def create_macros(calories: int, weight: int, type: str) -> namedtuple: protein = weight * 1 carbs = 0 if type == "rest": carbs = round(weight * 0.5) elif type == "light": carbs = round(weight * 1) elif type == "moderate": carbs = round(weight * 1.5) elif type == "hard": carbs = round(weight * 2) fats = round((calories - ((carbs + protein) * 4)) / 9) if fats < 55: fats = 55 tdee = (protein * 4) + (carbs * 4) + (fats * 9) Macros = namedtuple("Macros", "protein carbs fats tdee") macros = Macros(protein, carbs, fats, tdee) return macros
{"/api.py": ["/results.py", "/calculations.py"]}
56,196
rebelopsio/apiMacroCalc
refs/heads/main
/results.py
from datetime import datetime from json import JSONEncoder class SetMacros: def __init__(self, calories=0, protein=0, carbs=0, fats=0) -> None: self._calories = calories self._protein = protein self._carbs = carbs self._fats = fats def get_calories(self) -> int: return self._calories def get_protein(self) -> int: return self._protein def get_carbs(self) -> int: return self._carbs def get_fats(self) -> int: return self._fats def set_calories(self, calories: int) -> None: self._calories = calories def set_protein(self, protein: int) -> None: self._protein = protein def set_carbs(self, carbs: int) -> None: self._carbs = carbs def set_fats(self, fats: int) -> None: self._fats = fats class Results: def __init__(self, basal_metabolic_rate=0): self._basal_metabolic_rate = basal_metabolic_rate self._created_date = datetime.now().strftime("%m-%d-%Y, %H:%M:%S") self.rest_day_macros = SetMacros() self.light_day_macros = SetMacros() self.moderate_day_macros = SetMacros() self.hard_day_macros = SetMacros() def get_created_date(self) -> datetime: return self._created_date def get_basal_metabolic_rate(self) -> int: return self._basal_metabolic_rate def set_basal_metabolic_rate(self, basal_metabolic_rate:int) -> None: self._basal_metabolic_rate = basal_metabolic_rate class ResultsEncoder(JSONEncoder): def default(self, object): if isinstance(object, Results): return object.__dict__ elif isinstance(object, SetMacros): return object.__dict__ else: # call base class implementation which takes care of # raising exceptions for unsupported types return JSONEncoder.default(self, object)
{"/api.py": ["/results.py", "/calculations.py"]}
56,197
rebelopsio/apiMacroCalc
refs/heads/main
/api.py
from flask import Flask, jsonify from flask_restful import Resource, Api, reqparse from results import ResultsEncoder, Results from calculations import Calculations import json app = Flask(__name__) api = Api(app) parser = reqparse.RequestParser() parser.add_argument('sex', type=str) parser.add_argument('weight', type=int) parser.add_argument('heightinches', type=int) parser.add_argument('age', type=int) class apiMacroCalc(Resource): def get(self): args = parser.parse_args() sex = args['sex'] weight = args['weight'] height = args['heightinches'] age = args['age'] bMR = round(Calculations.basal_metabolic_rate( sex, age, height, weight)) rest_day_calories = round(Calculations.caloric_intake(bMR, "rest")) light_day_calories = round(Calculations.caloric_intake(bMR, "light")) moderate_day_calories = round( Calculations.caloric_intake(bMR, "moderate")) hard_day_calories = round(Calculations.caloric_intake(bMR, "hard")) obj_rest_day_macros = Calculations.create_macros( rest_day_calories, weight, "rest") obj_light_day_macros = Calculations.create_macros( light_day_calories, weight, "light") obj_moderate_day_macros = Calculations.create_macros( moderate_day_calories, weight, "moderate") obj_hard_day_macros = Calculations.create_macros( hard_day_calories, weight, "hard") macros = Results() macros.rest_day_macros.set_protein(obj_rest_day_macros.protein) macros.rest_day_macros.set_carbs(obj_rest_day_macros.carbs) macros.rest_day_macros.set_fats(obj_rest_day_macros.fats) macros.rest_day_macros.set_calories(obj_rest_day_macros.tdee) macros.light_day_macros.set_protein(obj_light_day_macros.protein) macros.light_day_macros.set_carbs(obj_light_day_macros.carbs) macros.light_day_macros.set_fats(obj_light_day_macros.fats) macros.light_day_macros.set_calories(obj_light_day_macros.tdee) macros.moderate_day_macros.set_protein(obj_moderate_day_macros.protein) macros.moderate_day_macros.set_carbs(obj_moderate_day_macros.carbs) macros.moderate_day_macros.set_fats(obj_moderate_day_macros.fats) macros.moderate_day_macros.set_calories(obj_moderate_day_macros.tdee) macros.hard_day_macros.set_protein(obj_hard_day_macros.protein) macros.hard_day_macros.set_carbs(obj_hard_day_macros.carbs) macros.hard_day_macros.set_fats(obj_hard_day_macros.fats) macros.hard_day_macros.set_calories(obj_hard_day_macros.tdee) macros.set_basal_metabolic_rate(bMR) json_data = json.dumps(macros) #json_data = ResultsEncoder().encode(macros) print(type(json_data)) print(str(json_data)) print(repr(json_data)) return json_data api.add_resource(apiMacroCalc, '/') if __name__ == '__main__': app.run(debug=False)
{"/api.py": ["/results.py", "/calculations.py"]}
56,198
rebelopsio/apiMacroCalc
refs/heads/main
/test/results_tests.py
import results def
{"/api.py": ["/results.py", "/calculations.py"]}
56,213
sarveshggn/portfolio
refs/heads/master
/dsproj/apps.py
from django.apps import AppConfig class DsprojConfig(AppConfig): name = 'dsproj'
{"/pyproj/views.py": ["/pyproj/models.py"]}
56,214
sarveshggn/portfolio
refs/heads/master
/dsproj/migrations/0003_auto_20200725_2009.py
# Generated by Django 2.2.4 on 2020-07-25 14:39 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('dsproj', '0002_dsproject_github_link'), ] operations = [ migrations.AlterField( model_name='dsproject', name='github_link', field=models.CharField(default='#', max_length=300), ), ]
{"/pyproj/views.py": ["/pyproj/models.py"]}
56,215
sarveshggn/portfolio
refs/heads/master
/dsproj/admin.py
from django.contrib import admin from .models import Dsproject # Register your models here. admin.site.register(Dsproject)
{"/pyproj/views.py": ["/pyproj/models.py"]}
56,216
sarveshggn/portfolio
refs/heads/master
/jobs/migrations/0004_auto_20200725_2009.py
# Generated by Django 2.2.4 on 2020-07-25 14:39 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('jobs', '0003_job_github_link'), ] operations = [ migrations.AlterField( model_name='job', name='github_link', field=models.CharField(default='#', max_length=300), ), ]
{"/pyproj/views.py": ["/pyproj/models.py"]}
56,217
sarveshggn/portfolio
refs/heads/master
/pyproj/models.py
from django.db import models # Create your models here. class Pyproject(models.Model): image = models.ImageField(upload_to='image/') summary = models.CharField(max_length=255) github_link = models.CharField(max_length=300, default='#') def __str__(self): return self.summary
{"/pyproj/views.py": ["/pyproj/models.py"]}
56,218
sarveshggn/portfolio
refs/heads/master
/dsproj/views.py
from django.shortcuts import render from .models import Dsproject # Create your views here. def dspro(request): dsprojects = Dsproject.objects return render(request, 'dsproj/dsprojhome.html', {'dsprojects': dsprojects})
{"/pyproj/views.py": ["/pyproj/models.py"]}
56,219
sarveshggn/portfolio
refs/heads/master
/pyproj/views.py
from django.shortcuts import render from .models import Pyproject # Create your views here. def pypro(request): pyprojects = Pyproject.objects return render(request, 'pyproj/pyprojhome.html', {'pyprojects': pyprojects})
{"/pyproj/views.py": ["/pyproj/models.py"]}
56,222
scorpionhiccup/CarNet
refs/heads/master
/carnet_webserver/RestServices/models.py
from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import AbstractBaseUser class traffic_data(models.Model): """docstring for traffic_data""" car_no=models.CharField(max_length=200, default="") signal_no=models.IntegerField(default=100) objects=models.Manager() #datetime= def __str__(self): return "%s: %s" % (self.signal_no, self.car_no)
{"/carnet_webserver/RestServices/admin.py": ["/carnet_webserver/RestServices/models.py"], "/carnet_webserver/RestServices/views.py": ["/carnet_webserver/RestServices/models.py"]}
56,223
scorpionhiccup/CarNet
refs/heads/master
/carnet_webserver/RestServices/admin.py
from django.contrib import admin from .models import traffic_data # Register your models here. admin.site.register(traffic_data)
{"/carnet_webserver/RestServices/admin.py": ["/carnet_webserver/RestServices/models.py"], "/carnet_webserver/RestServices/views.py": ["/carnet_webserver/RestServices/models.py"]}
56,224
scorpionhiccup/CarNet
refs/heads/master
/carnet_webserver/RestServices/urls.py
from django.conf.urls import include, url, patterns from django.conf.urls.static import static from django.conf import settings urlpatterns = [ url(r'^postInfo/(?P<signal_no>\d+)/(?P<car_no>[-\w]{0,50})/$', 'RestServices.views.postInfo'), url(r'^getInfo/(?P<signal_no>\d+)/$', 'RestServices.views.getInfo'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
{"/carnet_webserver/RestServices/admin.py": ["/carnet_webserver/RestServices/models.py"], "/carnet_webserver/RestServices/views.py": ["/carnet_webserver/RestServices/models.py"]}
56,225
scorpionhiccup/CarNet
refs/heads/master
/carnet_webserver/RestServices/views.py
from django.shortcuts import render from django.http import HttpResponse, JsonResponse from .models import traffic_data from django.shortcuts import render_to_response from django.template import RequestContext def postInfo(request, signal_no, car_no): str= "Received: " + signal_no + " : " + car_no + " " new_entry=traffic_data( signal_no=signal_no, car_no=car_no) new_entry.save() return HttpResponse(str) def getInfo(request, signal_no): ans={} ans[signal_no]=[] for obj in traffic_data.objects.filter(signal_no=signal_no): ans[signal_no].append(obj.car_no) return JsonResponse(ans) def main(request): return render_to_response('heatmap.html', RequestContext(request, {}));
{"/carnet_webserver/RestServices/admin.py": ["/carnet_webserver/RestServices/models.py"], "/carnet_webserver/RestServices/views.py": ["/carnet_webserver/RestServices/models.py"]}
56,276
cramos1567/GitHubApi567
refs/heads/master
/GitRepo.py
import requests import json def getUserCommits(userID): if not isinstance(userID,str): return "InvalidInput" if userID == "": return "InvalidInput" theStr = "User: " + userID + '\n' getRepos = requests.get("https://api.github.com/users/" + userID + "/repos") print(str(getRepos)) if str(getRepos) != "<Response [200]>": return "Invalid Username" listOfRepos = [] for r in getRepos.json(): listOfRepos += [r['name']] #print(listOfRepos) listOfCommits = [] for r in listOfRepos: getCommits = requests.get("https://api.github.com/repos/" + userID + "/" + r + "/commits") if str(getCommits) != "<Response [200]>": return "Invalid Repo" listOfCommits += [len(getCommits.json())] #print(listOfCommits) for r in range(0, len(listOfRepos)): theStr += "Repo: " + listOfRepos[r] + " Number of commits: " + str(listOfCommits[r]) + '\n' return theStr if __name__ == '__main__': print(getUserCommits("cramos1567")) print(getUserCommits("crramos1567"))
{"/TestGitRepo.py": ["/GitRepo.py"]}
56,277
cramos1567/GitHubApi567
refs/heads/master
/TestGitRepo.py
import unittest from GitRepo import getUserCommits class testAPI(unittest.TestCase): def test_inputType(self): self.assertEqual(getUserCommits(12), "InvalidInput") self.assertNotEqual(getUserCommits("cramos1567"), "InvalidInput") self.assertEqual(getUserCommits(""), "InvalidInput") def test_validUsername(self): self.assertNotEqual(getUserCommits("cramos1567"), "Invalid Username") self.assertEqual(getUserCommits("crramos1567"), "Invalid Username") if __name__ == '__main__': print("Running unit test") unittest.main()
{"/TestGitRepo.py": ["/GitRepo.py"]}
56,278
saltant-org/saltant
refs/heads/master
/tasksapi/tests/execution_tests/executable_execution_tests.py
"""Contains executable task tests for the tasksapi. These test (unlike the other tests as of 2018-08-27) are *very* basic and should be expanded in the future. """ import os import pathlib import shutil import subprocess import uuid from django.conf import settings from django.test import TestCase from tasksapi.tasks import run_executable_command class ExecutableExecutionTests(TestCase): """Test executable task execution.""" def setUp(self): """Create some temporary directories to store job results.""" # Generate the base path for this test self.base_dir_name = os.path.join( settings.BASE_DIR, "temp-test-" + str(uuid.uuid4()) ) # Make the logs and singularity images directories logs_path = os.path.join(self.base_dir_name, "logs/") pathlib.Path(logs_path).mkdir(parents=True, exist_ok=True) # Overload our environment variables to use our generated temp # storage directories os.environ["WORKER_LOGS_DIRECTORY"] = logs_path def tearDown(self): """Clean up directories made in setUpTestData.""" shutil.rmtree(self.base_dir_name) def test_executable_success(self): """Make sure executable jobs work properly.""" run_executable_command( uuid="test-executable-success-uuid", command_to_run="echo $SHELL", env_vars_list=["SHELL"], args_dict={}, json_file_option=None, ) def test_executable_failure(self): """Make sure executable jobs that fail are noticed.""" with self.assertRaises(subprocess.CalledProcessError): run_executable_command( uuid="test-executable-failure-uuid", command_to_run="false", env_vars_list=[], args_dict={}, json_file_option=None, ) def test_executable_json_file_option(self): """Make sure the JSON file option works.""" # TODO(mwiens91): write an actual test that parses the # JSON-encoded file run_executable_command( uuid="test-executable-success-uuid", command_to_run="echo", env_vars_list=[], args_dict={"toy": "example"}, json_file_option="--json-file", )
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,279
saltant-org/saltant
refs/heads/master
/tasksapi/utils.py
"""Helpful functions for the tasksapi.""" from django.db.models import Case, IntegerField, Q, When from tasksapi.constants import DOCKER from tasksapi.models import ExecutableTaskType, TaskQueue def get_allowed_queues(user, task_type=None): """Return queryset of the allowed queues. This is with respect to the task type and user. If no task type is provided we'll skip filtering based on task type. """ # Filter down the queues by active attribute queue_qs = TaskQueue.objects.filter(active=True) # And by the private attribute queue_qs = queue_qs.filter(Q(private=False) | Q(user=user.pk)) # And by the task type if task_type is not None: # Filter based on queue's "Allows x" attributes and whitelist if isinstance(task_type, ExecutableTaskType): # Whitelist queue_qs = queue_qs.filter( whitelists__whitelisted_executable_task_types=task_type ) # Allows attr queue_qs = queue_qs.filter(runs_executable_tasks=True) else: # Whitelist queue_qs = queue_qs.filter( whitelists__whitelisted_container_task_types=task_type ) # Allows attrs if task_type.container_type == DOCKER: queue_qs = queue_qs.filter(runs_docker_container_tasks=True) else: queue_qs = queue_qs.filter( runs_singularity_container_tasks=True ) return queue_qs def get_allowed_queues_sorted(user, task_type=None): """Return sorted queryset of the allowed queues. The sorting will be alphabetical, but place the selected user's queue(s) first. """ queues = ( get_allowed_queues(user, task_type) .annotate( priority=Case( When(user__pk=user.pk, then=1), default=2, output_field=IntegerField(), ) ) .order_by("priority", "name") ) return queues
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,280
saltant-org/saltant
refs/heads/master
/tasksapi/migrations/0004_user_time_zone.py
# Generated by Django 2.1.2 on 2018-12-05 06:27 from django.db import migrations import timezone_field.fields class Migration(migrations.Migration): dependencies = [ ('tasksapi', '0003_auto_20181204_2211'), ] operations = [ migrations.AddField( model_name='user', name='time_zone', field=timezone_field.fields.TimeZoneField(default='America/Vancouver'), ), ]
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,281
saltant-org/saltant
refs/heads/master
/frontend/views/taskinstances.py
"""Views for task instances. Views for creating and cloning are in a separate module. """ from celery.result import AsyncResult from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponseRedirect from django.urls import reverse_lazy from django.views.generic import DeleteView, DetailView, ListView, UpdateView from tasksapi.constants import CONTAINER_TASK, EXECUTABLE_TASK from tasksapi.models import ContainerTaskInstance, ExecutableTaskInstance from .mixins import ( SetContainerTaskClassCookieMixin, SetExecutableTaskClassCookieMixin, ) from .utils import get_context_data_for_chartjs from .utils_logs import ( get_s3_logs_for_task_instance, get_s3_logs_for_executable_task_instance, ) class BaseTaskInstanceList(LoginRequiredMixin, ListView): """A base view for listing task instances.""" context_object_name = "taskinstance_list" task_class = None def get_context_data(self, **kwargs): """Get some stats for the task instances.""" context = super().get_context_data(**kwargs) # Get data for Chart.js context = { **context, **get_context_data_for_chartjs(task_class=self.task_class), } return context class BaseTaskInstanceDetail(LoginRequiredMixin, DetailView): """A base view for a specific task instance.""" model = None pk_url_kwarg = "uuid" context_object_name = "taskinstance" template_name = None def get_context_data(self, **kwargs): """Add task instances logs into the context.""" context = super().get_context_data(**kwargs) # Get logs in a view-specific manner context["logs"] = self.get_logs() return context def get_logs(self): """Get the logs for the task instance.""" return get_s3_logs_for_task_instance(str(self.get_object().uuid)) class BaseTaskInstanceRename(LoginRequiredMixin, UpdateView): """A base view for renaming a task instance.""" model = None pk_url_kwarg = "uuid" fields = ("name",) template_name = None def get_success_url(self): """Redirect to detail page.""" raise NotImplementedError class BaseTaskInstanceStateUpdate(LoginRequiredMixin, UpdateView): """A base view for overriding task instance state.""" model = None pk_url_kwarg = "uuid" fields = ("state",) template_name = None def get_success_url(self): """Redirect to detail page.""" raise NotImplementedError class BaseTaskInstanceTerminate(LoginRequiredMixin, DetailView): """A base view for terminating task instances.""" pk_url_kwarg = "uuid" context_object_name = "taskinstance" template_name = "frontend/base_taskinstance_terminate.html" def post(self, request, *args, **kwargs): """Terminate the task instance and redirect.""" # This will hang unless you have a Celery hooked up and running AsyncResult(self.get_object().uuid).revoke(terminate=True) return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): """Redirect to detail page.""" raise NotImplementedError class BaseTaskInstanceDelete(LoginRequiredMixin, DeleteView): """A view for deleting a container task instance.""" model = None pk_url_kwarg = "uuid" context_object_name = "taskinstance" template_name = None success_url = None class ContainerTaskInstanceList( SetContainerTaskClassCookieMixin, BaseTaskInstanceList ): """A view for listing container task instances.""" model = ContainerTaskInstance task_class = CONTAINER_TASK template_name = "frontend/containertaskinstance_list.html" class ContainerTaskInstanceDetail(BaseTaskInstanceDetail): """A view for a specific container task instance.""" model = ContainerTaskInstance template_name = "frontend/containertaskinstance_detail.html" class ContainerTaskInstanceRename(BaseTaskInstanceRename): """A view for renaming a container task instance.""" model = ContainerTaskInstance template_name = "frontend/base_taskinstance_rename.html" def get_success_url(self): """Redirect to detail page.""" return reverse_lazy( "containertaskinstance-detail", kwargs={"uuid": self.object.uuid} ) class ContainerTaskInstanceStateUpdate(BaseTaskInstanceStateUpdate): """A view for overriding container task instance state.""" model = ContainerTaskInstance template_name = "frontend/base_taskinstance_stateupdate.html" def get_success_url(self): """Redirect to detail page.""" return reverse_lazy( "containertaskinstance-detail", kwargs={"uuid": self.object.uuid} ) class ContainerTaskInstanceTerminate(BaseTaskInstanceTerminate): """A view for terminating container task instances.""" model = ContainerTaskInstance def get_success_url(self): """Redirect to detail page.""" return reverse_lazy( "containertaskinstance-detail", kwargs={"uuid": self.get_object().uuid}, ) class ContainerTaskInstanceDelete(BaseTaskInstanceDelete): """A view for deleting a container task instance.""" model = ContainerTaskInstance template_name = "frontend/base_taskinstance_delete.html" success_url = reverse_lazy("containertaskinstance-list") class ExecutableTaskInstanceList( SetExecutableTaskClassCookieMixin, BaseTaskInstanceList ): """A view for listing executable task instance.""" model = ExecutableTaskInstance task_class = EXECUTABLE_TASK template_name = "frontend/executabletaskinstance_list.html" class ExecutableTaskInstanceDetail(BaseTaskInstanceDetail): """A view for a specific executable task instance.""" model = ExecutableTaskInstance template_name = "frontend/executabletaskinstance_detail.html" def get_logs(self): """Get the logs for the task instance.""" return get_s3_logs_for_executable_task_instance( str(self.get_object().uuid) ) class ExecutableTaskInstanceRename(BaseTaskInstanceRename): """A view for renaming an executable task instance.""" model = ExecutableTaskInstance template_name = "frontend/base_taskinstance_rename.html" def get_success_url(self): """Redirect to detail page.""" return reverse_lazy( "executabletaskinstance-detail", kwargs={"uuid": self.object.uuid} ) class ExecutableTaskInstanceStateUpdate(LoginRequiredMixin, UpdateView): """A view for overriding executable task instance state.""" model = ExecutableTaskInstance pk_url_kwarg = "uuid" fields = ("state",) template_name = "frontend/base_taskinstance_stateupdate.html" def get_success_url(self): """Redirect to detail page.""" return reverse_lazy( "executabletaskinstance-detail", kwargs={"uuid": self.object.uuid} ) class ExecutableTaskInstanceTerminate(BaseTaskInstanceTerminate): """A view for terminating executable task instances.""" model = ExecutableTaskInstance def get_success_url(self): """Redirect to detail page.""" return reverse_lazy( "executabletaskinstance-detail", kwargs={"uuid": self.get_object().uuid}, ) class ExecutableTaskInstanceDelete(BaseTaskInstanceDelete): """A view for deleting an executable task instance.""" model = ExecutableTaskInstance template_name = "frontend/base_taskinstance_delete.html" success_url = reverse_lazy("executabletaskinstance-list")
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,282
saltant-org/saltant
refs/heads/master
/tasksapi/migrations/0005_auto_20181211_1415.py
# Generated by Django 2.1.2 on 2018-12-11 22:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tasksapi', '0004_user_time_zone'), ] operations = [ migrations.AddField( model_name='taskqueue', name='runs_docker_container_tasks', field=models.BooleanField(blank=True, default=True, help_text='A boolean specifying whether the queue runs container tasks that run in Docker containers. Defaults to True.', verbose_name='runs Docker container tasks'), ), migrations.AddField( model_name='taskqueue', name='runs_executable_tasks', field=models.BooleanField(blank=True, default=True, help_text='A boolean specifying whether the queue runs executable tasks. Defaults to True.'), ), migrations.AddField( model_name='taskqueue', name='runs_singularity_container_tasks', field=models.BooleanField(blank=True, default=True, help_text='A boolean specifying whether the queue runs container tasks that run in Singularity containers. Defaults to True.', verbose_name='runs Singularity container tasks'), ), ]
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,283
saltant-org/saltant
refs/heads/master
/tasksapi/admin.py
"""Register models with the admin site.""" from django.contrib import admin from django.contrib.auth.admin import UserAdmin from tasksapi.models import ( ContainerTaskInstance, ContainerTaskType, ExecutableTaskInstance, ExecutableTaskType, TaskQueue, TaskWhitelist, User, ) @admin.register(ContainerTaskInstance) class ContainerTaskInstanceAdmin(admin.ModelAdmin): """Interface modifiers for container task instances on the admin page.""" list_display = ( "uuid", "task_type", "task_queue", "state", "name", "datetime_created", "datetime_finished", "user", ) @admin.register(ContainerTaskType) class ContainerTaskTypeAdmin(admin.ModelAdmin): """Interface modifiers for container task types on the admin page.""" list_display = ( "name", "user", "container_image", "container_type", "command_to_run", "datetime_created", "user", ) @admin.register(ExecutableTaskInstance) class ExecutableTaskInstanceAdmin(admin.ModelAdmin): """Interface modifiers for container task instances on the admin page.""" list_display = ( "uuid", "task_type", "task_queue", "state", "name", "datetime_created", "datetime_finished", "user", ) @admin.register(ExecutableTaskType) class ExecutableTaskTypeAdmin(admin.ModelAdmin): """Interface modifiers for container task types on the admin page.""" list_display = ( "name", "user", "command_to_run", "datetime_created", "user", ) @admin.register(TaskQueue) class TaskQueueAdmin(admin.ModelAdmin): """Interface modifiers for task queues on the admin page.""" list_display = ("name", "user", "private", "active") @admin.register(TaskWhitelist) class TaskWhitelistAdmin(admin.ModelAdmin): """Interface modifiers for task queues on the admin page.""" list_display = ("name",) # Register custom user admin.site.register(User, UserAdmin)
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,284
saltant-org/saltant
refs/heads/master
/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py
"""Contains requests tests for user queue permissions.""" from rest_framework import status from rest_framework.test import APITestCase # Put info about our fixtures data as constants here NON_ADMIN_USER_AUTH_TOKEN = "02d205bc79d5e8f15f83e249ac227ef0085f953f" NOT_USERS_PRIVATE_QUEUE_PK = 3 PUBLIC_INACTIVE_QUEUE_PK = 2 CONTAINER_TASK_TYPE_PK = 1 EXECUTABLE_TASK_TYPE_PK = 1 class UserQueuePermissionsRequestsTests(APITestCase): """Test user queue permissions.""" fixtures = ["test-fixture.yaml"] def setUp(self): """Add in user's auth to client.""" self.client.credentials( HTTP_AUTHORIZATION="Token " + NON_ADMIN_USER_AUTH_TOKEN ) def test_posting_to_inactive_queue(self): """Test posting a job to an inactive queue.""" post_response_1 = self.client.post( "/api/containertaskinstances/", dict( name="my-task-instance", task_type=CONTAINER_TASK_TYPE_PK, task_queue=PUBLIC_INACTIVE_QUEUE_PK, ), format="json", ) post_response_2 = self.client.post( "/api/executabletaskinstances/", dict( name="my-task-instance", task_type=EXECUTABLE_TASK_TYPE_PK, task_queue=PUBLIC_INACTIVE_QUEUE_PK, ), format="json", ) self.assertEqual( post_response_1.status_code, status.HTTP_400_BAD_REQUEST ) self.assertEqual( post_response_2.status_code, status.HTTP_400_BAD_REQUEST ) def test_posting_to_other_users_private_queue(self): """Test posting a job to another user's private queue.""" post_response_1 = self.client.post( "/api/containertaskinstances/", dict( name="my-task-instance", task_type=CONTAINER_TASK_TYPE_PK, task_queue=NOT_USERS_PRIVATE_QUEUE_PK, ), format="json", ) post_response_2 = self.client.post( "/api/executabletaskinstances/", dict( name="my-task-instance", task_type=EXECUTABLE_TASK_TYPE_PK, task_queue=NOT_USERS_PRIVATE_QUEUE_PK, ), format="json", ) self.assertEqual( post_response_1.status_code, status.HTTP_400_BAD_REQUEST ) self.assertEqual( post_response_2.status_code, status.HTTP_400_BAD_REQUEST )
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,285
saltant-org/saltant
refs/heads/master
/frontend/views/utils.py
"""Contains general helpers for frontend views.""" from datetime import date, timedelta import json from .utils_stats import determine_days_to_plot, get_job_state_data def translate_num_days_to_plot_title(num_days): """Translate a date range to a plot title. Args: num_days: An integer specifying how many days back to look. Returns: A string to be used for the pie plot title. """ if num_days == 7: return "last week's jobs" # Get the number of weeks num_weeks = num_days / 7 if num_weeks.is_integer(): num_weeks_str = str(int(num_weeks)) else: num_weeks_str = "{0:.1f}".format(num_weeks) return "last %s weeks' jobs" % num_weeks_str def get_context_data_for_chartjs(task_class="both", task_type_pk=None): """Get Chart.js data to pass to the context. Args: task_class: An optional string indicating which task class to use. Can be either "container", "executable", or "both". task_type_pk: An optional integer indicating the primary key of the task type to use. Defaults to None, which means, consider all task types. Returns: A dictionary ready to meld with the context dictionary. """ context = {} # Get data for Chart.js days_to_plot = determine_days_to_plot( task_class=task_class, task_type_pk=task_type_pk ) today = date.today() other_date = date.today() - timedelta(days=days_to_plot - 1) chart_data = get_job_state_data( task_class=task_class, task_type_pk=task_type_pk, start_date=other_date, end_date=today, ) # Add the Charts.js stuff to our context context["show_chart"] = chart_data["has_data"] context["labels"] = json.dumps(chart_data["labels"]) context["datasets"] = json.dumps(chart_data["datasets"]) context["chart_title"] = translate_num_days_to_plot_title(days_to_plot) return context
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,286
saltant-org/saltant
refs/heads/master
/tasksapi/permissions.py
"""Contains permissions for the API.""" from rest_framework import permissions class IsAdminOrOwnerThenWriteElseReadOnly(permissions.IsAuthenticated): """Allow editing objects only for admin or associated object user. Inherits from the IsAuthenticated permission, which is the default saltant permission class. """ def has_object_permission(self, request, view, obj): """Allow only admins and owners write permissions.""" if request.method in permissions.SAFE_METHODS: return True # Instance must have an attribute named `owner`. return obj.user == request.user or request.user.is_superuser
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,287
saltant-org/saltant
refs/heads/master
/tasksapi/constants.py
"""Constants for the tasksapi app.""" # Choices for the task instance's state field. The states are based off # of signals provided by Celery (which in fact set the state field): # http://docs.celeryproject.org/en/master/userguide/signals.html. CREATED = "created" PUBLISHED = "published" RUNNING = "running" SUCCESSFUL = "successful" FAILED = "failed" TERMINATED = "terminated" # Tuple of (key, display_name)s STATE_CHOICES = ( (CREATED, "created"), (PUBLISHED, "published"), (RUNNING, "running"), (SUCCESSFUL, "successful"), (FAILED, "failed"), (TERMINATED, "terminated"), ) STATE_MAX_LENGTH = 10 # Choices for container types. DOCKER = "docker" SINGULARITY = "singularity" # Tuple of (key, display_name)s CONTAINER_CHOICES = ((DOCKER, "Docker"), (SINGULARITY, "Singularity")) CONTAINER_TYPE_MAX_LENGTH = 11 # Choices for class of task CONTAINER_TASK = "container" EXECUTABLE_TASK = "executable"
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,288
saltant-org/saltant
refs/heads/master
/tasksapi/urls.py
"""Contains URLs for the tasksapi app.""" from django.urls import include, path, re_path from drf_yasg import openapi from drf_yasg.views import get_schema_view from rest_framework import permissions from rest_framework.routers import DefaultRouter from tasksapi import views # A router to register Django REST Framework viewsets class OptionalSlashRouter(DefaultRouter): """A router that makes a trailing slash optional Thanks to Ryan Allen on StackOverflow. """ def __init__(self): """Make trailing slashes optional.""" super().__init__() self.trailing_slash = "/?" # Register the routes router = OptionalSlashRouter() router.register("users", views.UserViewSet) router.register("containertaskinstances", views.ContainerTaskInstanceViewSet) router.register("containertasktypes", views.ContainerTaskTypeViewSet) router.register("executabletaskinstances", views.ExecutableTaskInstanceViewSet) router.register("executabletasktypes", views.ExecutableTaskTypeViewSet) router.register("taskqueues", views.TaskQueueViewSet) router.register("taskwhitelists", views.TaskWhitelistViewSet) # Schema for Swagger API schema_view = get_schema_view( openapi.Info(title="saltant API", default_version="v1"), validators=["flex", "ssv"], public=True, permission_classes=(permissions.IsAuthenticatedOrReadOnly,), ) app_name = "tasksapi" urlpatterns = [ path(r"", include(router.urls)), path(r"auth/", include("rest_framework.urls")), path( r"redoc/", schema_view.with_ui("redoc", cache_timeout=None), name="schema-redoc", ), path( r"swagger/", schema_view.with_ui("swagger", cache_timeout=None), name="schema-swagger-ui", ), re_path( r"^swagger/(?P<format>\.json|\.yaml)$", schema_view.without_ui(cache_timeout=None), name="schema-json", ), path( r"updatetaskinstancestatus/<slug:uuid>/", views.update_task_instance_status, name="update_task_instance_status", ), path( r"token/", views.TokenObtainPairPermissiveView.as_view(), name="token_obtain_pair", ), path( r"token/refresh/", views.TokenRefreshPermissiveView.as_view(), name="token_refresh", ), ]
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,289
saltant-org/saltant
refs/heads/master
/saltant/settings.py
""" Django settings for saltant project. There are two parts to this file. The first part deals with settings that both Django and Celery workers need to worry about. The second part deals with settings that only Django needs to worry about. Generated by 'django-admin startproject' using Django 2.0.6. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ from datetime import timedelta import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # First part: Django and Celery worker settings # Is this is a Celery worker? IM_A_CELERY_WORKER_RAW = os.environ["IM_A_CELERY_WORKER"] if IM_A_CELERY_WORKER_RAW == "False": IM_A_CELERY_WORKER = False elif IM_A_CELERY_WORKER_RAW == "True": IM_A_CELERY_WORKER = True else: # Bad value in config file! raise ValueError("IM_A_CELERY_WORKER must be True/False") # SECURITY WARNING: don't run with debug turned on in production! DEBUG_RAW = os.environ["DEBUG"] if DEBUG_RAW == "False": DEBUG = False elif DEBUG_RAW == "True": DEBUG = True else: # Bad value in config file! raise ValueError("DEBUG must be True/False") # Celery settings CELERY_BROKER_POOL_LIMIT_RAW = os.environ["CELERY_BROKER_POOL_LIMIT"] CELERY_BROKER_POOL_LIMIT = ( CELERY_BROKER_POOL_LIMIT_RAW if CELERY_BROKER_POOL_LIMIT_RAW == "None" else int(CELERY_BROKER_POOL_LIMIT_RAW) ) CELERY_BROKER_URL = os.environ["CELERY_BROKER_URL"] CELERY_TIMEZONE = os.environ["CELERY_TIMEZONE"] # SSL settings if os.environ["RABBITMQ_USES_SSL"] == "True": import ssl BROKER_USE_SSL = {"cert_reqs": ssl.CERT_NONE} # Rollbar settings PROJECT_USES_ROLLBAR_RAW = os.environ["PROJECT_USES_ROLLBAR"] if PROJECT_USES_ROLLBAR_RAW == "False": PROJECT_USES_ROLLBAR = False elif PROJECT_USES_ROLLBAR_RAW == "True": PROJECT_USES_ROLLBAR = True else: # Bad value in config file! raise ValueError("PROJECT_USES_ROLLBAR must be True/False") if PROJECT_USES_ROLLBAR: ROLLBAR = { "access_token": os.environ["ROLLBAR_ACCESS_TOKEN"], "environment": "development" if DEBUG else "production", "root": BASE_DIR, } # Second part: Django only settings if not IM_A_CELERY_WORKER: # Make sure '.env' is secure SECRET_KEY = os.environ["SECRET_KEY"] # Hosts - separate the comma-separated hosts and clean up any empty # strings caused by a terminal comma in ".env" ALLOWED_HOSTS = os.environ["ALLOWED_HOSTS"].replace("'", "").split(",") ALLOWED_HOSTS = list(filter(None, ALLOWED_HOSTS)) # Application definition INSTALLED_APPS = [ "frontend.apps.FrontEndConfig", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "tasksapi.apps.TasksApiConfig", "crispy_forms", "django_extensions", "django_filters", "drf_yasg", "rest_framework", "rest_framework.authtoken", "timezone_field", "widget_tweaks", ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "rollbar.contrib.django.middleware.RollbarNotifierMiddlewareExcluding404", "tasksapi.middleware.TimezoneMiddleware", ] ROOT_URLCONF = "saltant.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", "frontend.context_processors.export_env_vars", ] }, } ] WSGI_APPLICATION = "saltant.wsgi.application" LOGIN_REDIRECT_URL = "splash-page" LOGOUT_REDIRECT_URL = "splash-page" # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": os.environ["DATABASE_NAME"], "USER": os.environ["DATABASE_USER"], "PASSWORD": os.environ["DATABASE_USER_PASSWORD"], "HOST": os.environ["DATABASE_HOST"], "PORT": os.environ["DATABASE_PORT"], } } # User model AUTH_USER_MODEL = "tasksapi.User" # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator" }, { "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator" }, { "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator" }, { "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator" }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = "en-us" TIME_ZONE = os.environ["TIME_ZONE"] USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, "static/") # REST framework settings REST_FRAMEWORK = { "DEFAULT_PAGINATION_CLASS": "tasksapi.paginators.LargeResultsSetPagination", "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework.authentication.SessionAuthentication", "rest_framework.authentication.TokenAuthentication", "rest_framework_simplejwt.authentication.JWTAuthentication", ), "DEFAULT_FILTER_BACKENDS": ( "django_filters.rest_framework.DjangoFilterBackend", ), "DEFAULT_PERMISSION_CLASSES": ( "rest_framework.permissions.IsAuthenticated", ), "EXCEPTION_HANDLER": ( "rollbar.contrib.django_rest_framework.post_exception_handler" ), } # Swagger and ReDoc settings (see # https://drf-yasg.readthedocs.io/en/stable/settings.html) SWAGGER_SETTINGS = { "USE_SESSION_AUTH": False, "SECURITY_DEFINITIONS": { "Bearer": { "type": "apiKey", "description": "JWT access token (all users; transient)", "name": "Authorization", "in": "header", }, "Token": { "type": "apiKey", "description": "DRF TokenAuthentication token (select users; permanent)", "name": "Authorization", "in": "header", }, }, } # JWT authentication settings (see # https://github.com/davesque/django-rest-framework-simplejwt) SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta( days=int(os.environ["JWT_ACCESS_TOKEN_LIFETIME"]) ), "REFRESH_TOKEN_LIFETIME": timedelta( days=int(os.environ["JWT_REFRESH_TOKEN_LIFETIME"]) ), } # Email settings - currently email isn't used # EMAIL_HOST = os.environ["EMAIL_HOST"] # EMAIL_HOST_USER = os.environ["EMAIL_HOST_USER"] # EMAIL_HOST_PASSWORD = os.environ["EMAIL_HOST_PASSWORD"] # EMAIL_PORT = os.environ["EMAIL_PORT"] # EMAIL_USE_TLS_RAW = os.environ["EMAIL_USE_TLS"] # if EMAIL_USE_TLS_RAW == "False": # EMAIL_USE_TLS = False # elif EMAIL_USE_TLS_RAW == "True": # EMAIL_USE_TLS = True # else: # # Bad value in config file! # raise ValueError("EMAIL_USE_TLS must be True/False") # DEFAULT_FROM_EMAIL = os.environ["DEFAULT_FROM_EMAIL"] # AWS S3 logs bucket settings AWS_LOGS_BUCKET_NAME = os.environ["AWS_LOGS_BUCKET_NAME"] # Where to redirect to after login and logout LOGIN_URL = "login" LOGIN_REDIRECT_URL = "home" LOGOUT_REDIRECT_URL = "home" # Session settings SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies" # Whether to favour the container or executable task class by # default (cookies will take precedence over this). Must be either # "container" or "executable". DEFAULT_TASK_CLASS = os.environ["DEFAULT_TASK_CLASS"].lower()
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,290
saltant-org/saltant
refs/heads/master
/frontend/tests.py
"""Contains tests for the front-end.""" from django.test import TestCase from django.urls import reverse from rest_framework import status ADMIN_USER_USERNAME = "adminuser" ADMIN_USER_PASSWORD = "qwertyuiop" EXECUTABLE_TASK_INSTANCE_UUID = "aa07248f-fdf3-4d34-8215-0c7b21b892ad" CONTAINER_TASK_INSTANCE_UUID = "e7133970-ac3c-4026-adcf-55ee170d4eb3" EXECUTABLE_TASK_TYPE_PK = 1 CONTAINER_TASK_TYPE_PK = 1 TASK_QUEUE_PK = 1 TASK_WHITELIST_PK = 1 class FrontendRenderTests(TestCase): """Just make sure pages render properly.""" fixtures = ["test-fixture.yaml"] def setUp(self): """Authenticate the client in.""" login_response = self.client.post( reverse("login"), {"username": ADMIN_USER_USERNAME, "password": ADMIN_USER_PASSWORD}, ) self.assertEqual(login_response.status_code, status.HTTP_302_FOUND) def test_getting_frontend_pages(self): """Try GETting a bunch of pages.""" # Build a list of pages to iterate over that return the same # status code. The ordering here isn't significant, but its in # the order that the URLs appear in the urls module. pages_to_get = [ reverse("home"), reverse("about"), reverse("account-edit-profile"), reverse("account-change-password"), reverse("containertaskinstance-list"), reverse("containertaskinstance-create-menu"), reverse( "containertaskinstance-detail", kwargs={"uuid": CONTAINER_TASK_INSTANCE_UUID}, ), reverse( "containertaskinstance-rename", kwargs={"uuid": CONTAINER_TASK_INSTANCE_UUID}, ), reverse( "containertaskinstance-clone", kwargs={"uuid": CONTAINER_TASK_INSTANCE_UUID}, ), reverse( "containertaskinstance-stateupdate", kwargs={"uuid": CONTAINER_TASK_INSTANCE_UUID}, ), reverse( "containertaskinstance-terminate", kwargs={"uuid": CONTAINER_TASK_INSTANCE_UUID}, ), reverse( "containertaskinstance-delete", kwargs={"uuid": CONTAINER_TASK_INSTANCE_UUID}, ), reverse("containertasktype-list"), reverse("containertasktype-create"), reverse( "containertasktype-detail", kwargs={"pk": CONTAINER_TASK_TYPE_PK}, ), reverse( "containertaskinstance-create", kwargs={"pk": CONTAINER_TASK_TYPE_PK}, ), reverse( "containertasktype-delete", kwargs={"pk": CONTAINER_TASK_TYPE_PK}, ), reverse( "containertasktype-update", kwargs={"pk": CONTAINER_TASK_TYPE_PK}, ), reverse("executabletaskinstance-list"), reverse("executabletaskinstance-create-menu"), reverse( "executabletaskinstance-detail", kwargs={"uuid": EXECUTABLE_TASK_INSTANCE_UUID}, ), reverse( "executabletaskinstance-rename", kwargs={"uuid": EXECUTABLE_TASK_INSTANCE_UUID}, ), reverse( "executabletaskinstance-clone", kwargs={"uuid": EXECUTABLE_TASK_INSTANCE_UUID}, ), reverse( "executabletaskinstance-stateupdate", kwargs={"uuid": EXECUTABLE_TASK_INSTANCE_UUID}, ), reverse( "executabletaskinstance-terminate", kwargs={"uuid": EXECUTABLE_TASK_INSTANCE_UUID}, ), reverse( "executabletaskinstance-delete", kwargs={"uuid": EXECUTABLE_TASK_INSTANCE_UUID}, ), reverse("executabletasktype-list"), reverse("executabletasktype-create"), reverse( "executabletasktype-detail", kwargs={"pk": EXECUTABLE_TASK_TYPE_PK}, ), reverse( "executabletaskinstance-create", kwargs={"pk": EXECUTABLE_TASK_TYPE_PK}, ), reverse( "executabletasktype-delete", kwargs={"pk": EXECUTABLE_TASK_TYPE_PK}, ), reverse( "executabletasktype-update", kwargs={"pk": EXECUTABLE_TASK_TYPE_PK}, ), reverse("queue-list"), reverse("queue-create"), reverse("queue-detail", kwargs={"pk": TASK_QUEUE_PK}), reverse("queue-delete", kwargs={"pk": TASK_QUEUE_PK}), reverse("queue-update", kwargs={"pk": TASK_QUEUE_PK}), reverse("whitelist-list"), reverse("whitelist-create"), reverse("whitelist-detail", kwargs={"pk": TASK_WHITELIST_PK}), reverse("whitelist-delete", kwargs={"pk": TASK_WHITELIST_PK}), reverse("whitelist-update", kwargs={"pk": TASK_WHITELIST_PK}), ] # Iterate over each page and make sure it's okay for page in pages_to_get: get_response = self.client.get(page) self.assertEqual(get_response.status_code, status.HTTP_200_OK)
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,291
saltant-org/saltant
refs/heads/master
/tasksapi/serializers/task_instance_update.py
"""Contains a serializer to update any task instance state. Emphasis on "any". This works for both container *and* executable tasks. """ from rest_framework import serializers from tasksapi.constants import STATE_CHOICES class TaskInstanceStateUpdateRequestSerializer(serializers.Serializer): """A serializer for a task instance update's request.""" state = serializers.ChoiceField(choices=STATE_CHOICES) class TaskInstanceStateUpdateResponseSerializer(serializers.Serializer): """A serializer for a task instance update's response.""" uuid = serializers.CharField(max_length=36) state = serializers.ChoiceField(choices=STATE_CHOICES)
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,292
saltant-org/saltant
refs/heads/master
/tasksapi/serializers/users.py
"""Contains serializers for users.""" from rest_framework import serializers from tasksapi.models import User class UserSerializer(serializers.ModelSerializer): """A serializer for a user, without password details.""" class Meta: model = User lookup_field = "username" fields = ("username", "email")
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,293
saltant-org/saltant
refs/heads/master
/tasksapi/tests/execution_tests/container_execution_tests.py
"""Contains container task tests for the tasksapi.""" import os import pathlib import subprocess import uuid import docker from django.conf import settings from django.test import TestCase from tasksapi.tasks import ( run_docker_container_command, run_singularity_container_command, ) class ContainerExecutionTests(TestCase): """Test container task execution. Using the Docker container defined here: https://github.com/mwiens91/saltant-test-docker-container. """ @classmethod def setUpTestData(cls): """Create some temporary directories to store job results.""" # Generate the base path for this test base_dir_name = os.path.join( settings.BASE_DIR, "temp-test-" + str(uuid.uuid4()) ) # Make the logs and singularity images directories logs_path = os.path.join(base_dir_name, "logs/") results_path = os.path.join(base_dir_name, "results/") singularity_path = os.path.join(base_dir_name, "images/") pathlib.Path(logs_path).mkdir(parents=True, exist_ok=True) pathlib.Path(results_path).mkdir(parents=True, exist_ok=True) pathlib.Path(singularity_path).mkdir(parents=True, exist_ok=True) # Overload our environment variables to use our generated temp # storage directories os.environ["WORKER_LOGS_DIRECTORY"] = logs_path os.environ["WORKER_RESULTS_DIRECTORY"] = results_path os.environ["WORKER_SINGULARITY_IMAGES_DIRECTORY"] = singularity_path def tearDown(self): """Clean up directories made in setUpTestData.""" # TODO: this command fails because the files that the Docker # container creates are owned by 'root'. Looked into this a bit, # but couldn't find a clean solution, so right now there's no # automatic cleanup :( # # Note that since first writing this, base_dir_name was an # object attribute and shutil was imported. To test this again, # implement the things I just mentioned again. # shutil.rmtree(self.base_dir_name) pass def test_docker_success(self): """Make sure Docker jobs work properly.""" run_docker_container_command( uuid="test-docker-success-uuid", container_image="mwiens91/hello-world", command_to_run="/app/hello_world.py", logs_path="/logs/", results_path="/results/", env_vars_list=["SHELL"], args_dict={"name": "AzureDiamond"}, ) def test_singularity_success(self): """Make sure Singularity jobs work properly.""" run_singularity_container_command( uuid="test-singularity-success-uuid", container_image="docker://mwiens91/hello-world", command_to_run="/app/hello_world.py", logs_path="/logs/", results_path="/results/", env_vars_list=["SHELL"], args_dict={"name": "AzureDiamond"}, ) def test_docker_failure(self): """Make sure Docker jobs that fail are noticed.""" with self.assertRaises(docker.errors.ContainerError): run_docker_container_command( uuid="test-docker-failure-uuid", container_image="mwiens91/test-error-containers", command_to_run="/app/error_raise.py", logs_path=None, results_path=None, env_vars_list=[], args_dict={}, ) def test_singularity_failure(self): """Make sure Singularity jobs that fail are noticed.""" with self.assertRaises(subprocess.CalledProcessError): run_singularity_container_command( uuid="test-docker-failure-uuid", container_image="shub://mwiens91/test-error-containers", command_to_run="/error_raise.py", logs_path=None, results_path=None, env_vars_list=[], args_dict={}, )
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,294
saltant-org/saltant
refs/heads/master
/frontend/views/whitelists.py
"""Views for task whitelists.""" from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse_lazy from django.views.generic import ( CreateView, DeleteView, DetailView, ListView, UpdateView, ) from tasksapi.models import TaskWhitelist from .mixins import ( DisableUserSelectFormViewMixin, IsAdminOrOwnerOnlyMixin, UserFormViewMixin, ) class WhitelistList(LoginRequiredMixin, ListView): """A view for listing whitelists.""" model = TaskWhitelist template_name = "frontend/whitelist_list.html" class WhitelistCreate( UserFormViewMixin, DisableUserSelectFormViewMixin, LoginRequiredMixin, CreateView, ): """A view for creating a whitelist.""" model = TaskWhitelist fields = "__all__" template_name = "frontend/whitelist_create.html" def get_success_url(self): """Redirect to whitelist detail page.""" return reverse_lazy("whitelist-detail", kwargs={"pk": self.object.pk}) class WhitelistDetail(LoginRequiredMixin, DetailView): """A view for a specific whitelist.""" model = TaskWhitelist template_name = "frontend/whitelist_detail.html" class WhitelistUpdate( LoginRequiredMixin, IsAdminOrOwnerOnlyMixin, DisableUserSelectFormViewMixin, UpdateView, ): """A view for deleting a whitelist.""" model = TaskWhitelist fields = "__all__" template_name = "frontend/whitelist_update.html" def get_success_url(self): """Redirect to whitelist detail page.""" return reverse_lazy("whitelist-detail", kwargs={"pk": self.object.pk}) class WhitelistDelete(LoginRequiredMixin, IsAdminOrOwnerOnlyMixin, DeleteView): """A view for deleting a whitelist.""" model = TaskWhitelist template_name = "frontend/whitelist_delete.html" success_url = reverse_lazy("whitelist-list")
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,295
saltant-org/saltant
refs/heads/master
/frontend/views/utils_stats.py
"""Contains helpers for getting and packaging data statistics.""" from datetime import date, timedelta from frontend.constants import ( DATES_LIST, DEFAULT_DAYS_TO_PLOT, INTERESTING_STATES, STATE_COLOR_DICT, ) from tasksapi.constants import CONTAINER_TASK, CREATED from tasksapi.models import ContainerTaskInstance, ExecutableTaskInstance def translate_date_to_string( this_date, day_of_week=False, today_and_yesterday=True, today=None ): """Translate a date to a string. Args: this_date: A datetime.date to translate. day_of_week: An optional Boolean specifying whether to use the days of the week as the string names. Defaults to False. today_and_yesterday: An optional Boolean specifying whether to use the "Today" and "Yesterday" as strings for the current and previous date, respectively. Defaults to True. today: A datetime.date indicating the current date. If this is None and today_and_yesterday is True, then a datetime.date.today call will be made per function call, which might not be efficient. Defaults to None. Does nothing if day_of_week is False. """ if today_and_yesterday: # Load up today if necessary if today is None: today = date.today() # Translate if this_date == today: return "Today" elif this_date == today - timedelta(days=1): return "Yesterday" if day_of_week: return DATES_LIST[this_date.weekday()] # Use ISO 8601 return this_date.isoformat() def determine_days_to_plot(task_class="both", task_type_pk=None): """Determine how many days to plot using the "default behavior". The default behavior is as follows: use a default number of days, but if there aren't any tasks within the default, then show up to the week before the most recent task. And if there aren't any tasks, just use the default number of days. Args: task_class: An optional string indicating which task class to use. Can be either "container", "executable", or "both". The former two are defined as constants in tasksapi, which we'll be using here. Defaults to "both". task_type_pk: An optional integer indicating the primary key of the task type to use. Defaults to None, which means, consider all task types. Returns: An integer specifying the number of days to plot. """ # First build a list of the task instance models to use if task_class == "both": instance_models = [ContainerTaskInstance, ExecutableTaskInstance] elif task_class == CONTAINER_TASK: instance_models = [ContainerTaskInstance] else: instance_models = [ExecutableTaskInstance] # Now build the corresponding querysets querysets = [x.objects.all() for x in instance_models] # Now filter by task type, possibly if task_type_pk is not None: querysets = [x.filter(task_type__pk=task_type_pk) for x in querysets] # Grab the latest dates of an instance for each queryset, making # sure to not include jobs with "created" state (since these aren't # shown in the plot). latest_dates = [ i.datetime_created.date() for i in [q.exclude(state=CREATED).first() for q in querysets] if i is not None ] # Make sure we have any instances at all, if not, just use default # value. if not latest_dates: return DEFAULT_DAYS_TO_PLOT # Now pick out the latest date latest_date = max(latest_dates) # Count how many days between today and that date delta_days = (date.today() - latest_date).days # If the latest date is within the range of the default, just use # the default if delta_days < DEFAULT_DAYS_TO_PLOT: return DEFAULT_DAYS_TO_PLOT # Otherwise use the number of days between today and that date, plus # 7 days return delta_days + 7 def get_job_state_data( task_class="both", task_type_pk=None, start_date=date.today(), end_date=date.today(), ): """Get data for job states. This gets the state counts of jobs created in a time range. In the arguments below, both start and end date are inclusive. Note that providing both task_class = "both" and a non-None task_type_pk doesn't really make sense, since task types are specific to task classes. Args: task_class: An optional string indicating which task class to use. Can be either "container", "executable", or "both". The former two are defined as constants in tasksapi, which we'll be using here. Defaults to "both". task_type_pk: An optional integer indicating the primary key of the task type to use. Defaults to None, which means, consider all task types. start_date: An optional datetime.date indicating the start of the date range. Defaults to today. end_date: An optional datetime.date indicating the end of the date range. Defaults to today. Returns: Nested dictionaries following the "datasets" and "labels" schema for Chart.js pie chargs. To use with Chart.js, make sure to encode the dictionaries to JSON strings first. """ # First build a list of the task instance models to use if task_class == "both": instance_models = [ContainerTaskInstance, ExecutableTaskInstance] elif task_class == CONTAINER_TASK: instance_models = [ContainerTaskInstance] else: instance_models = [ExecutableTaskInstance] # Now build the corresponding querysets querysets = [x.objects.all() for x in instance_models] # Now filter by task type, possibly if task_type_pk is not None: querysets = [x.filter(task_type__pk=task_type_pk) for x in querysets] # And filter by date if start_date == end_date: querysets = [ x.filter(datetime_created__date=start_date) for x in querysets ] else: querysets = [ x.filter(datetime_created__date__gte=start_date).filter( datetime_created__date__lte=end_date ) for x in querysets ] # Now build up the dataset based on state dataset = dict() dataset["data"] = [ sum([x.filter(state=state).count() for x in querysets]) for state in INTERESTING_STATES ] dataset["backgroundColor"] = [ STATE_COLOR_DICT[state] for state in INTERESTING_STATES ] # Record if our datasets has any non-zero data has_data = bool(sum(dataset["data"]) > 0) # List the labels labels = list(INTERESTING_STATES) return {"labels": labels, "datasets": [dataset], "has_data": has_data} def get_job_state_data_date_enumerated( task_class="both", task_type_pk=None, start_date=date.today(), end_date=date.today(), use_day_of_week=False, use_today_and_yesterday=True, ): """Get data for job states eumerated by date. This is very similar too the "get_job_state" function above, but different enough that it warrants another function. The main differences are how the datasets dictionary is structured (which is an essential difference). Args: task_class: An optional string indicating which task class to use. Can be either "container", "executable", or "both". The former two are defined as constants in tasksapi, which we'll be using here. Defaults to "both". task_type_pk: An optional integer indicating the primary key of the task type to use. Defaults to None, which means, consider all task types. start_date: An optional datetime.date indicating the start of the date range. Defaults to today. end_date: An optional datetime.date indicating the end of the date range. Defaults to today. use_day_of_week: An optional Boolean specifying whether to enumerate dates as Mon, Tues, Wed, etc. Defaults to False, which means that it will use ISO 8601 dates instead. use_today_and_yesterday: An optional Boolean specifying whether to label dates which are the current or previous date with "Today" and "Yesterday", respectively. Defaults to True. Returns: Nested dictionaries following the "datasets" and "labels" schema for Chart.js pie chargs. To use with Chart.js, make sure to encode the dictionaries to JSON strings first. """ # First build a list of the task instance models to use if task_class == "both": instance_models = [ContainerTaskInstance, ExecutableTaskInstance] elif task_class == CONTAINER_TASK: instance_models = [ContainerTaskInstance] else: instance_models = [ExecutableTaskInstance] # Now build the corresponding querysets querysets = [x.objects.all() for x in instance_models] # Now filter by task type, possibly if task_type_pk is not None: querysets = [x.filter(task_type__pk=task_type_pk) for x in querysets] # Now figure out what dates we care about delta = end_date - start_date my_dates = [start_date + timedelta(i) for i in range(delta.days + 1)] # Here we have datasets for each state, each of which has data per # date datasets = [] for state in INTERESTING_STATES: dataset = dict() dataset["backgroundColor"] = STATE_COLOR_DICT[state] dataset["label"] = state dataset["data"] = [ sum( [ x.filter(state=state) .filter(datetime_created__date=d) .count() for x in querysets ] ) for d in my_dates ] datasets.append(dataset) # List the dates for the chart labels labels = [ translate_date_to_string( d, day_of_week=use_day_of_week, today_and_yesterday=use_today_and_yesterday, today=date.today(), ) for d in my_dates ] return {"labels": labels, "datasets": datasets}
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,296
saltant-org/saltant
refs/heads/master
/tasksapi/tests/requests_tests/utils.py
"""Contains helpers for requests tests.""" from tasksapi.constants import DOCKER TEST_CONTAINER_TASK_TYPE_DICT = dict( name="my-task-type", description="Fantastic task type", container_image="mwiens91/hello-world", container_type=DOCKER, command_to_run="/app/hello_world.py", logs_path="/logs/", results_path="/results/", environment_variables=["HOME"], required_arguments=["name"], required_arguments_default_values={"name": "AzureDiamond"}, ) TEST_EXECUTABLE_TASK_TYPE_DICT = dict( name="my-task-type", description="Fantastic task type", command_to_run="true", environment_variables=["HOME"], required_arguments=["name"], required_arguments_default_values={"name": "AzureDiamond"}, ) TEST_TASK_QUEUE_DICT = dict( name="my-task-queue", description="Fantastic task queue", whitelists=[1] ) TEST_TASK_WHITELIST_DICT = dict( name="my-task-whitelist", description="Fantastic task whitelist", whitelisted_container_task_types=[1], whitelisted_executable_task_types=[1], )
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,297
saltant-org/saltant
refs/heads/master
/frontend/widgets.py
"""Custom widgets for forms.""" from django import forms from django.template.loader import render_to_string from django.utils.safestring import mark_safe class JSONEditorWidget(forms.Widget): """A JSONField widget using JSONEditor. See https://github.com/josdejong/jsoneditor. Note that this code is mostly derived from django-json-widget (https://github.com/jmrivas86/django-json-widget), but has been stripped down to be more lightweight. """ template_name = "frontend/widgets/json_editor.html" def __init__(self, attrs=None, mode="code"): """Add in the display mode.""" super().__init__(attrs=attrs) self.mode = mode def render(self, name, value, attrs=None, renderer=None): """Render the JSONField as a JSONEditor widget.""" context = {"data": value, "name": name, "mode": self.mode} return mark_safe(render_to_string(self.template_name, context))
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,298
saltant-org/saltant
refs/heads/master
/tasksapi/tests/models_tests/queue_whitelist_tests.py
"""Contains tests for queue whitelists.""" from django.core.exceptions import ValidationError from django.test import TestCase from tasksapi.models import ( ContainerTaskInstance, ContainerTaskType, ExecutableTaskInstance, ExecutableTaskType, TaskQueue, User, ) # Put info about our fixtures data as constants here QUEUE_PK = 1 USER_PK = 1 NON_WHITELISTED_CONTAINER_TASK_TYPE_PK = 3 NON_WHITELISTED_EXECUTABLE_TASK_TYPE_PK = 2 class TaskQueueWhitelistTests(TestCase): """Test task queue whitelists.""" fixtures = ["test-fixture.yaml"] def setUp(self): """Prep common test objects.""" self.user = User.objects.get(pk=USER_PK) self.executable_task_type = ExecutableTaskType.objects.get( pk=NON_WHITELISTED_EXECUTABLE_TASK_TYPE_PK ) self.container_task_type = ContainerTaskType.objects.get( pk=NON_WHITELISTED_CONTAINER_TASK_TYPE_PK ) self.queue = TaskQueue.objects.get(pk=QUEUE_PK) def test_non_whitelisted_container_task(self): """Test rejection of non-whtielisted container task.""" # Ensure this doesn't go through with self.assertRaises(ValidationError): ContainerTaskInstance.objects.create( user=self.user, task_type=self.container_task_type, task_queue=self.queue, ) def test_non_whitelisted_executable_task(self): """Test rejection of non-whtielisted executable task.""" # Ensure this doesn't go through with self.assertRaises(ValidationError): ExecutableTaskInstance.objects.create( user=self.user, task_type=self.executable_task_type, task_queue=self.queue, )
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,299
saltant-org/saltant
refs/heads/master
/tasksapi/tests/models_tests/queue_permission_attrs_tests.py
"""Contains tests for queue permission attributes.""" from django.core.exceptions import ValidationError from django.test import TestCase from tasksapi.models import ( ContainerTaskInstance, ContainerTaskType, ExecutableTaskInstance, ExecutableTaskType, TaskQueue, User, ) # Put info about our fixtures data as constants here ADMIN_PRIVATE_TASK_QUEUE_PK = 3 ADMIN_INACTIVE_TASK_QUEUE_PK = 2 EXECUTABLE_ONLY_TASK_QUEUE_PK = 4 DOCKER_CONTAINER_ONLY_TASK_QUEUE_PK = 5 SINGULARITY_CONTAINER_ONLY_TASK_QUEUE_PK = 6 EXECUTABLE_TASK_TYPE_PK = 1 DOCKER_CONTAINER_TASK_TYPE_PK = 1 SINGULARITY_CONTAINER_TASK_TYPE_PK = 2 ADMIN_USER_PK = 1 NON_ADMIN_USER_PK = 2 class TaskQueuePermissionAttributesTests(TestCase): """Test task queue permission attributes.""" fixtures = ["test-fixture.yaml"] def setUp(self): """Prep common test objects.""" # Users self.admin_user = User.objects.get(pk=ADMIN_USER_PK) self.non_admin_user = User.objects.get(pk=NON_ADMIN_USER_PK) # Task types self.executable_task_type = ExecutableTaskType.objects.get( pk=EXECUTABLE_TASK_TYPE_PK ) self.docker_container_task_type = ContainerTaskType.objects.get( pk=DOCKER_CONTAINER_TASK_TYPE_PK ) self.singularity_container_task_type = ContainerTaskType.objects.get( pk=SINGULARITY_CONTAINER_TASK_TYPE_PK ) # Queues self.admin_private_queue = TaskQueue.objects.get( pk=ADMIN_PRIVATE_TASK_QUEUE_PK ) self.admin_inactive_queue = TaskQueue.objects.get( pk=ADMIN_INACTIVE_TASK_QUEUE_PK ) self.executable_only_queue = TaskQueue.objects.get( pk=EXECUTABLE_ONLY_TASK_QUEUE_PK ) self.docker_container_only_queue = TaskQueue.objects.get( pk=DOCKER_CONTAINER_ONLY_TASK_QUEUE_PK ) self.singularity_container_only_queue = TaskQueue.objects.get( pk=SINGULARITY_CONTAINER_ONLY_TASK_QUEUE_PK ) def test_private_permission_attr(self): """Test private task queue attribute.""" # Ensure user can post to its own private queue ExecutableTaskInstance.objects.create( user=self.admin_user, task_type=self.executable_task_type, task_queue=self.admin_private_queue, ) ContainerTaskInstance.objects.create( user=self.admin_user, task_type=self.docker_container_task_type, task_queue=self.admin_private_queue, ) ContainerTaskInstance.objects.create( user=self.admin_user, task_type=self.singularity_container_task_type, task_queue=self.admin_private_queue, ) # Ensure user can't post to other private queue with self.assertRaises(ValidationError): ExecutableTaskInstance.objects.create( name="test", user=self.non_admin_user, task_type=self.executable_task_type, task_queue=self.admin_private_queue, ) with self.assertRaises(ValidationError): ContainerTaskInstance.objects.create( user=self.non_admin_user, task_type=self.docker_container_task_type, task_queue=self.admin_private_queue, ) with self.assertRaises(ValidationError): ContainerTaskInstance.objects.create( user=self.non_admin_user, task_type=self.singularity_container_task_type, task_queue=self.admin_private_queue, ) def test_executable_permission_attr(self): """Test "accepts executable tasks" task queue attribute.""" # Ensure executable tasks run fine on executable-task-only queue ExecutableTaskInstance.objects.create( user=self.admin_user, task_type=self.executable_task_type, task_queue=self.executable_only_queue, ) # Ensure other tasks do not run on executable-task-only queue with self.assertRaises(ValidationError): ContainerTaskInstance.objects.create( user=self.admin_user, task_type=self.docker_container_task_type, task_queue=self.executable_only_queue, ) with self.assertRaises(ValidationError): ContainerTaskInstance.objects.create( user=self.admin_user, task_type=self.singularity_container_task_type, task_queue=self.executable_only_queue, ) def test_docker_container_permission_attr(self): """Test "accepts Docker container tasks" task queue attribute.""" # Ensure Docker container tasks run fine on # Docker-container-tasks-only queue ContainerTaskInstance.objects.create( user=self.admin_user, task_type=self.docker_container_task_type, task_queue=self.docker_container_only_queue, ) # Ensure other tasks do not run on this queue with self.assertRaises(ValidationError): ExecutableTaskInstance.objects.create( user=self.admin_user, task_type=self.executable_task_type, task_queue=self.docker_container_only_queue, ) with self.assertRaises(ValidationError): ContainerTaskInstance.objects.create( user=self.admin_user, task_type=self.singularity_container_task_type, task_queue=self.docker_container_only_queue, ) def test_singularity_container_permission_attr(self): """Test "accepts Singularity container tasks" task queue attribute.""" # Ensure Singularity container tasks run fine on # Singularity-container-tasks-only queue ContainerTaskInstance.objects.create( user=self.admin_user, task_type=self.singularity_container_task_type, task_queue=self.singularity_container_only_queue, ) # Ensure other tasks do not run on this queue with self.assertRaises(ValidationError): ExecutableTaskInstance.objects.create( user=self.admin_user, task_type=self.executable_task_type, task_queue=self.singularity_container_only_queue, ) with self.assertRaises(ValidationError): ContainerTaskInstance.objects.create( user=self.admin_user, task_type=self.docker_container_task_type, task_queue=self.singularity_container_only_queue, ) def test_active_permission_attr(self): """Test active task queue attribute.""" # Ensure user can't post to its own inactive queue with self.assertRaises(ValidationError): ExecutableTaskInstance.objects.create( user=self.admin_user, task_type=self.executable_task_type, task_queue=self.admin_inactive_queue, ) with self.assertRaises(ValidationError): ContainerTaskInstance.objects.create( user=self.admin_user, task_type=self.docker_container_task_type, task_queue=self.admin_inactive_queue, ) with self.assertRaises(ValidationError): ContainerTaskInstance.objects.create( user=self.admin_user, task_type=self.singularity_container_task_type, task_queue=self.admin_inactive_queue, ) # Ensure user can't post to other inactive queue with self.assertRaises(ValidationError): ExecutableTaskInstance.objects.create( user=self.non_admin_user, task_type=self.executable_task_type, task_queue=self.admin_inactive_queue, ) with self.assertRaises(ValidationError): ContainerTaskInstance.objects.create( user=self.non_admin_user, task_type=self.docker_container_task_type, task_queue=self.admin_inactive_queue, ) with self.assertRaises(ValidationError): ContainerTaskInstance.objects.create( user=self.non_admin_user, task_type=self.singularity_container_task_type, task_queue=self.admin_inactive_queue, )
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,300
saltant-org/saltant
refs/heads/master
/tasksapi/tasks/utils.py
"""Contains utility functions for tasks.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import errno import os import sys def create_local_directory(path): """Create a local directory as in mkdir_p. Replace this function with os.makedirs(path, exist_ok=True) when support for Python 2.7 is deprecated. """ if sys.version_info.major >= 3 and sys.version_info.minor >= 2: # Use standard library functionality for Python 3 os.makedirs(path, exist_ok=True) else: # For Python < 3.2, the exist_ok argument for the above # function doesn't exist mkdir_p(path) def mkdir_p(path): """Emulate mkdir -p. There's not built-in for this with Python 2, so have to write a custom function for it. Thanks to Chris for his answer at StackOverflow at https://stackoverflow.com/questions/9079036/detect-python-version-at-runtime. """ try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,301
saltant-org/saltant
refs/heads/master
/tasksapi/models/utils.py
"""Common bits of code used by model files.""" from django.core.validators import RegexValidator from tasksapi.constants import CONTAINER_TASK, EXECUTABLE_TASK # RegexValidator for validating a names. sane_name_validator = RegexValidator( regex=r"^[\w@+-]+$", message=" @/+/-/_ only" ) def determine_task_class(obj): """Determine the task class of an object. The object obj being passed in must be a task instance or task type, else an exception is raised. To avoid circular imports we test against the string representation of the object, which is very much unideal, but I have no better ideas right now. TODO: come up with better ideas """ obj_class_string = str(obj.__class__) if obj_class_string in ( "<class 'tasksapi.models.container_tasks.ContainerTaskInstance'>", "<class 'tasksapi.models.container_tasks.ContainerTaskType'>", ): return CONTAINER_TASK elif obj_class_string in ( "<class 'tasksapi.models.executable_tasks.ExecutableTaskInstance'>", "<class 'tasksapi.models.executable_tasks.ExecutableTaskType'>", ): return EXECUTABLE_TASK raise TypeError("Must pass in task types or instances!")
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,302
saltant-org/saltant
refs/heads/master
/tasksapi/filters.py
"""Contains filters to go along with viewsets for the REST API.""" from django_filters import rest_framework as filters from tasksapi.models import ( ContainerTaskInstance, ContainerTaskType, ExecutableTaskInstance, ExecutableTaskType, TaskQueue, TaskWhitelist, User, ) # Common lookups for filter fields CHAR_FIELD_LOOKUPS = [ "exact", "contains", "in", "startswith", "endswith", "regex", ] BOOLEAN_FIELD_LOOKUPS = ["exact"] FOREIGN_KEY_FIELD_LOOKUPS = ["exact", "in"] DATE_FIELD_LOOKUPS = ["exact", "year", "range", "lt", "lte", "gt", "gte"] # Common sets of fields to use or extend ABSTRACT_TASK_INSTANCE_FIELDS = { "name": CHAR_FIELD_LOOKUPS, "state": CHAR_FIELD_LOOKUPS, "user__username": CHAR_FIELD_LOOKUPS, "task_type": FOREIGN_KEY_FIELD_LOOKUPS, "task_queue": FOREIGN_KEY_FIELD_LOOKUPS, "datetime_created": DATE_FIELD_LOOKUPS, "datetime_finished": DATE_FIELD_LOOKUPS, } ABSTRACT_TASK_TYPE_FIELDS = { "name": CHAR_FIELD_LOOKUPS, "description": CHAR_FIELD_LOOKUPS, "user__username": CHAR_FIELD_LOOKUPS, "command_to_run": CHAR_FIELD_LOOKUPS, "datetime_created": DATE_FIELD_LOOKUPS, } class UserFilter(filters.FilterSet): """A filterset to support queries for Users.""" class Meta: model = User fields = {"username": CHAR_FIELD_LOOKUPS, "email": CHAR_FIELD_LOOKUPS} class ContainerTaskInstanceFilter(filters.FilterSet): """A filterset to support queries for container task instance attributes.""" class Meta: model = ContainerTaskInstance fields = ABSTRACT_TASK_INSTANCE_FIELDS class ContainerTaskTypeFilter(filters.FilterSet): """A filterset to support queries for container task type attributes.""" class Meta: model = ContainerTaskType container_fields = { "container_image": CHAR_FIELD_LOOKUPS, "container_type": CHAR_FIELD_LOOKUPS, } fields = {**ABSTRACT_TASK_TYPE_FIELDS, **container_fields} class ExecutableTaskInstanceFilter(filters.FilterSet): """A filterset to support queries for executable task instance attributes.""" class Meta: model = ExecutableTaskInstance fields = ABSTRACT_TASK_INSTANCE_FIELDS class ExecutableTaskTypeFilter(filters.FilterSet): """A filterset to support queries for executable task type attributes.""" class Meta: model = ExecutableTaskType fields = ABSTRACT_TASK_TYPE_FIELDS class TaskQueueFilter(filters.FilterSet): """A filterset to support queries for task queue attributes.""" class Meta: model = TaskQueue fields = { "name": CHAR_FIELD_LOOKUPS, "description": CHAR_FIELD_LOOKUPS, "user__username": CHAR_FIELD_LOOKUPS, "private": BOOLEAN_FIELD_LOOKUPS, "runs_executable_tasks": BOOLEAN_FIELD_LOOKUPS, "runs_docker_container_tasks": BOOLEAN_FIELD_LOOKUPS, "runs_singularity_container_tasks": BOOLEAN_FIELD_LOOKUPS, "active": BOOLEAN_FIELD_LOOKUPS, } class TaskWhitelistFilter(filters.FilterSet): """A filterset to support queries for task whitelist attributes.""" class Meta: model = TaskWhitelist fields = { "name": CHAR_FIELD_LOOKUPS, "description": CHAR_FIELD_LOOKUPS, "user__username": CHAR_FIELD_LOOKUPS, }
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,303
saltant-org/saltant
refs/heads/master
/frontend/templatetags/jsonify.py
"""Filter to provide JSON dump transforms.""" import json from django.template import Library register = Library() @register.filter(is_safe=True) def jsonify(val): """Perform a naive JSON dump.""" return json.dumps(val)
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,304
saltant-org/saltant
refs/heads/master
/frontend/views/errors.py
"""Views for error pages.""" from django.views.generic import TemplateView class BadRequest400(TemplateView): """A 400 page.""" template_name = "frontend/400.html" def get(self, request, *args, **kwargs): """Show the 400 page.""" return self.render_to_response( self.get_context_data(**kwargs), status=400 ) class PermissionDenied403(TemplateView): """A 403 page.""" template_name = "frontend/403.html" def get(self, request, *args, **kwargs): """Show the 403 page.""" return self.render_to_response( self.get_context_data(**kwargs), status=403 ) class PageNotFound404(TemplateView): """A 404 page.""" template_name = "frontend/404.html" def get(self, request, *args, **kwargs): """Show the 404 page.""" return self.render_to_response( self.get_context_data(**kwargs), status=404 ) class ServerError500(TemplateView): """A 500 page.""" template_name = "frontend/500.html" def get(self, request, *args, **kwargs): """Show the 500 page.""" return self.render_to_response( self.get_context_data(**kwargs), status=500 )
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,305
saltant-org/saltant
refs/heads/master
/tasksapi/models/task_queues.py
"""Model to represent task queues.""" from django.db import models from .users import User from .utils import sane_name_validator class TaskWhitelist(models.Model): """A whitelist of tasks for queues to run.""" name = models.CharField( max_length=50, unique=True, help_text="The name of the whitelist." ) description = models.TextField( blank=True, help_text="A description of the whitelist." ) user = models.ForeignKey( User, on_delete=models.CASCADE, help_text="The maintainer of the whitelist.", ) whitelisted_container_task_types = models.ManyToManyField( "tasksapi.ContainerTaskType", blank=True, help_text="The set of container task types to whitelist.", ) whitelisted_executable_task_types = models.ManyToManyField( "tasksapi.ExecutableTaskType", blank=True, help_text="The set of executable task types to whitelist.", ) class Meta: ordering = ["id"] def __str__(self): """String representation of the whitelist.""" return self.name class TaskQueue(models.Model): """The Celery queue on which task instances run. With some extra annotations and *light* security measures. ("*light*" meaning that you can probably get around them pretty easily if you decide to hit the messaging queue (e.g., RabbitMQ) directly.) """ name = models.CharField( max_length=50, unique=True, validators=[sane_name_validator], help_text="The name of the Celery queue.", ) description = models.TextField( blank=True, help_text="A description of the queue." ) user = models.ForeignKey( User, on_delete=models.CASCADE, help_text="The creator of the queue." ) private = models.BooleanField( blank=True, default=False, help_text=( "A boolean specifying whether " "other users besides the queue creator " "can use the queue. Defaults to False." ), ) runs_executable_tasks = models.BooleanField( blank=True, default=True, help_text=( "A boolean specifying whether the queue runs executable tasks. " "Defaults to True." ), ) runs_docker_container_tasks = models.BooleanField( blank=True, default=True, verbose_name="runs Docker container tasks", help_text=( "A boolean specifying whether the queue runs container " "tasks that run in Docker containers. Defaults to True." ), ) runs_singularity_container_tasks = models.BooleanField( blank=True, default=True, verbose_name="runs Singularity container tasks", help_text=( "A boolean specifying whether the queue runs container " "tasks that run in Singularity containers. Defaults to True." ), ) active = models.BooleanField( blank=True, default=True, help_text=( "A boolean showing the status of the " "queue. As of now, this needs to be " "toggled manually. Defaults to True." ), ) whitelists = models.ManyToManyField( TaskWhitelist, blank=True, help_text="A set of task whitelists." ) class Meta: ordering = ["id"] def __str__(self): """String representation of a queue.""" return self.name
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,306
saltant-org/saltant
refs/heads/master
/tasksapi/tasks/__init__.py
"""Collect import task code to "export" from this directory.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from .base_task import run_task from .container_tasks import ( run_docker_container_command, run_singularity_container_command, ) from .executable_tasks import run_executable_command
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,307
saltant-org/saltant
refs/heads/master
/frontend/templatetags/fontawesomize.py
"""Filter to convert booleans to icons.""" import json from django.template import Library register = Library() @register.filter(is_safe=True) def fontawesomize(val): """Convert boolean to font awesome icon.""" if val: return '<i class="fa fa-check" style="color: green"></i>' return '<i class="fa fa-times" style="color: red"></i>'
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,308
saltant-org/saltant
refs/heads/master
/tasksapi/tests/requests_tests/basic_requests_tests.py
"""Contains tests for basic API requests.""" from rest_framework import status from rest_framework.authtoken.models import Token from rest_framework.test import APITransactionTestCase from tasksapi.constants import PUBLISHED from tasksapi.models import User from .utils import ( TEST_CONTAINER_TASK_TYPE_DICT, TEST_EXECUTABLE_TASK_TYPE_DICT, TEST_TASK_QUEUE_DICT, TEST_TASK_WHITELIST_DICT, ) # The user and their password used in these tests USER_USERNAME = "AzureDiamond" USER_PASSWORD = "hunter2" class BasicHTTPRequestsTests(APITransactionTestCase): """Test basic HTTP requests. I.e., GET, POST, and PUT for most models. Nothing fancy here exploring permissions. """ # Ensure the PKs get reset after each test reset_sequences = True def setUp(self): """Generate the user used by the tests.""" self.user = User(username=USER_USERNAME) self.user.set_password(USER_PASSWORD) self.user.save() def http_requests_barrage(self): """Fire a barrage of HTTP requests at the API. """ # POST, GET, and PUT a container task type post_response = self.client.post( "/api/containertasktypes/", TEST_CONTAINER_TASK_TYPE_DICT, format="json", ) get_response_1 = self.client.get( "/api/containertasktypes/", format="json" ) get_response_2 = self.client.get( "/api/containertasktypes/1/", format="json" ) put_response = self.client.put( "/api/containertasktypes/1/", {**TEST_CONTAINER_TASK_TYPE_DICT, "name": "different"}, format="json", ) # Make sure we get the right statuses in response to our # requests self.assertEqual(post_response.status_code, status.HTTP_201_CREATED) self.assertEqual(get_response_1.status_code, status.HTTP_200_OK) self.assertEqual(get_response_2.status_code, status.HTTP_200_OK) self.assertEqual(put_response.status_code, status.HTTP_200_OK) # POST, GET, and PUT an executable task type. "true" doesn't # really do anything, but I guess that's ideal for a test? post_response = self.client.post( "/api/executabletasktypes/", TEST_EXECUTABLE_TASK_TYPE_DICT, format="json", ) get_response_1 = self.client.get( "/api/executabletasktypes/", format="json" ) get_response_2 = self.client.get( "/api/executabletasktypes/1/", format="json" ) put_response = self.client.put( "/api/executabletasktypes/1/", {**TEST_EXECUTABLE_TASK_TYPE_DICT, "name": "different"}, format="json", ) # Make sure we get the right statuses in response to our # requests self.assertEqual(post_response.status_code, status.HTTP_201_CREATED) self.assertEqual(get_response_1.status_code, status.HTTP_200_OK) self.assertEqual(get_response_2.status_code, status.HTTP_200_OK) self.assertEqual(put_response.status_code, status.HTTP_200_OK) # POST, GET, and PUT a task whitelist. post_response = self.client.post( "/api/taskwhitelists/", TEST_TASK_WHITELIST_DICT, format="json" ) get_response_1 = self.client.get("/api/taskwhitelists/", format="json") get_response_2 = self.client.get( "/api/taskwhitelists/1/", format="json" ) put_response = self.client.put( "/api/taskwhitelists/1/", {**TEST_TASK_WHITELIST_DICT, "name": "different"}, format="json", ) patch_response = self.client.patch( "/api/taskwhitelists/1/", {"name": "also different"}, format="json" ) # Make sure we get the right statuses in response to our # requests self.assertEqual(post_response.status_code, status.HTTP_201_CREATED) self.assertEqual(get_response_1.status_code, status.HTTP_200_OK) self.assertEqual(get_response_2.status_code, status.HTTP_200_OK) self.assertEqual(put_response.status_code, status.HTTP_200_OK) self.assertEqual(patch_response.status_code, status.HTTP_200_OK) # POST, GET, and PUT a task queue post_response = self.client.post( "/api/taskqueues/", TEST_TASK_QUEUE_DICT, format="json" ) get_response_1 = self.client.get("/api/taskqueues/", format="json") get_response_2 = self.client.get("/api/taskqueues/1/", format="json") put_response = self.client.put( "/api/taskqueues/1/", {**TEST_TASK_QUEUE_DICT, "name": "different"}, format="json", ) patch_response = self.client.patch( "/api/taskqueues/1/", {"name": "also_different"}, format="json" ) # Make sure we get the right statuses in response to our # requests self.assertEqual(post_response.status_code, status.HTTP_201_CREATED) self.assertEqual(get_response_1.status_code, status.HTTP_200_OK) self.assertEqual(get_response_2.status_code, status.HTTP_200_OK) self.assertEqual(put_response.status_code, status.HTTP_200_OK) self.assertEqual(patch_response.status_code, status.HTTP_200_OK) # POST, GET, and PATCH a container task instance post_response = self.client.post( "/api/containertaskinstances/", dict( name="my-task-instance", task_type=1, task_queue=1, arguments={"name": "Daniel"}, ), format="json", ) # Get the UUID of the task instance we just made new_uuid = post_response.data["uuid"] # Continue with the requests get_response_1 = self.client.get( "/api/containertaskinstances/", format="json" ) get_response_2 = self.client.get( "/api/containertaskinstances/" + new_uuid + "/", format="json" ) patch_response = self.client.patch( "/api/updatetaskinstancestatus/" + new_uuid + "/", dict(state=PUBLISHED), format="json", ) # Make sure we get the right statuses in response to our # requests self.assertEqual(post_response.status_code, status.HTTP_201_CREATED) self.assertEqual(get_response_1.status_code, status.HTTP_200_OK) self.assertEqual(get_response_2.status_code, status.HTTP_200_OK) self.assertEqual(patch_response.status_code, status.HTTP_200_OK) # Now let's test the clone and terminate endpoints for task # instances clone_response = self.client.post( "/api/containertaskinstances/" + new_uuid + "/clone/", format="json", ) new_uuid = clone_response.data["uuid"] terminate_response = self.client.post( "/api/containertaskinstances/" + new_uuid + "/terminate/", format="json", ) # Make sure we get the right statuses in response to our # requests self.assertEqual(clone_response.status_code, status.HTTP_201_CREATED) self.assertEqual( terminate_response.status_code, status.HTTP_202_ACCEPTED ) # POST, GET, and PATCH an executable task instance post_response = self.client.post( "/api/executabletaskinstances/", dict( name="my-task-instance", task_type=1, task_queue=1, arguments={"name": "Daniel"}, ), format="json", ) # Get the UUID of the task instance we just made new_uuid = post_response.data["uuid"] # Continue with the requests get_response_1 = self.client.get( "/api/executabletaskinstances/", format="json" ) get_response_2 = self.client.get( "/api/executabletaskinstances/" + new_uuid + "/", format="json" ) patch_response = self.client.patch( "/api/updatetaskinstancestatus/" + new_uuid + "/", dict(state=PUBLISHED), format="json", ) # Make sure we get the right statuses in response to our # requests self.assertEqual(post_response.status_code, status.HTTP_201_CREATED) self.assertEqual(get_response_1.status_code, status.HTTP_200_OK) self.assertEqual(get_response_2.status_code, status.HTTP_200_OK) self.assertEqual(patch_response.status_code, status.HTTP_200_OK) # Now let's test the clone and terminate endpoints for task # instances clone_response = self.client.post( "/api/executabletaskinstances/" + new_uuid + "/clone/", format="json", ) new_uuid = clone_response.data["uuid"] terminate_response = self.client.post( "/api/executabletaskinstances/" + new_uuid + "/terminate/", format="json", ) # Make sure we get the right statuses in response to our # requests self.assertEqual(clone_response.status_code, status.HTTP_201_CREATED) self.assertEqual( terminate_response.status_code, status.HTTP_202_ACCEPTED ) def test_basic_http_requests_token_auth(self): """Make sure basic HTTP requests work using token authentication.""" # Create an authentication token token = Token.objects.create(user=self.user) # Authenticate with the auth token we made self.client.credentials(HTTP_AUTHORIZATION="Token " + token.key) # Run tests self.http_requests_barrage() def test_basic_http_requests_jwt_auth(self): """Make sure basic HTTP requests work using JWT authentication.""" # Get a JWT access token and use it jwt_response = self.client.post( "/api/token/", dict(username=USER_USERNAME, password=USER_PASSWORD), format="json", ) access_token = jwt_response.data["access"] self.client.credentials(HTTP_AUTHORIZATION="Bearer " + access_token) # Run tests self.http_requests_barrage() def test_basic_http_requests_session_auth(self): """Make sure basic HTTP requests work using session authentication.""" # Authenticate with a session self.client.login(username=USER_USERNAME, password=USER_PASSWORD) # Run tests self.http_requests_barrage() # Log out of the session self.client.logout()
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,309
saltant-org/saltant
refs/heads/master
/tasksapi/models/container_tasks.py
"""Models to represent task types and instances which use containers.""" from django.db import models from django.db.models.signals import post_save, pre_save from django.dispatch import receiver from django.utils import timezone from tasksapi.constants import ( SUCCESSFUL, FAILED, CONTAINER_CHOICES, CONTAINER_TYPE_MAX_LENGTH, CONTAINER_TASK, ) from tasksapi.tasks import run_task from .abstract_tasks import AbstractTaskInstance, AbstractTaskType class ContainerTaskType(AbstractTaskType): """A type of task to create containerized instances with.""" # Paths in the container for logs and results logs_path = models.CharField( max_length=400, blank=True, null=True, default=None, help_text=( "The path of the logs directory inside the container. " "Specify null if no logs directory. Defaults to null." ), ) results_path = models.CharField( max_length=400, blank=True, null=True, default=None, help_text=( 'The path of the results (or "outputs") directory inside ' "the container. Specify null if no results directory. " "Defaults to null." ), ) # Container info container_image = models.CharField( max_length=200, help_text=( 'The container name and tag. For example, "ubuntu:14.04" ' 'for Docker; and "docker://ubuntu:14.04" or ' '"shub://vsoch/hello-world" for Singularity.' ), ) container_type = models.CharField( max_length=CONTAINER_TYPE_MAX_LENGTH, choices=CONTAINER_CHOICES, help_text="The type of container provided.", ) class ContainerTaskInstance(AbstractTaskInstance): """A running instance of a container task type.""" task_type = models.ForeignKey( ContainerTaskType, on_delete=models.CASCADE, help_text="The task type for which this is an instance.", ) @receiver(pre_save, sender=ContainerTaskInstance) def container_task_instance_pre_save_handler(instance, **_): """Adds additional behavior before saving a task instance. If the state is about to be changed to a finished change, update the datetime finished field. Args: instance: The task instance about to be saved. """ if instance.state in (SUCCESSFUL, FAILED): instance.datetime_finished = timezone.now() @receiver(post_save, sender=ContainerTaskInstance) def container_task_instance_post_save_handler(instance, created, **_): """Adds additional behavior after saving a task instance. Right now this just queues up the task instance upon creation. Args: instance: The task instance just saved. created: A boolean telling us if the task instance was just created (cf. modified). """ # Only start the job if the instance was just created if created: kwargs = { "uuid": instance.uuid, "task_class": CONTAINER_TASK, "command_to_run": instance.task_type.command_to_run, "env_vars_list": instance.task_type.environment_variables, "args_dict": instance.arguments, "logs_path": instance.task_type.logs_path, "results_path": instance.task_type.results_path, "container_image": instance.task_type.container_image, "container_type": instance.task_type.container_type, } run_task.apply_async( kwargs=kwargs, queue=instance.task_queue.name, task_id=str(instance.uuid), )
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}