Exemple #1
0
    def __init__(self, poll_type_id, title, prompt, **kwargs):
        """Create Poll from poll_type_id, title, and prompt
           and add to db."""

        admin_code = uuid4().hex
        short_code = ShortUUID().random(length=8)

        # check for duplicates
        while Poll.query.filter(Poll.admin_code == admin_code).first():
            admin_code = uuid4().hex

        while Poll.query.filter(Poll.short_code == short_code).first():
            short_code = ShortUUID().random(length=8)

        self.admin_code = admin_code
        self.short_code = short_code
        self.poll_type_id = poll_type_id
        self.title = title
        self.prompt = prompt

        if kwargs is not None:
            for attr, val in kwargs.iteritems():
                setattr(self, attr, val)

        db.session.add(self)
        db.session.commit()
Exemple #2
0
    def form_valid(self, form):
        child_profile = form.save(commit=False)

        # generate a random username; this use won't log in
        username = ShortUUID().random(length=10)
        while User.objects.filter(username=username).exists():
            username = ShortUUID().random(length=10)
        child_user = User.objects.create(
            first_name=form.cleaned_data["first_name"],
            last_name=form.cleaned_data["last_name"],
            username=username)
        child_user.set_unusable_password()
        child_profile.user = child_user
        child_profile.parent_user_profile = self.request.user.userprofile
        child_profile.save()
        if not self.request.user.is_manager:
            self.request.user.userprofile.manager = True
            self.request.user.userprofile.save()
        ActivityLog.objects.create(
            log=
            f"Managed user account created for {child_user.first_name} {child_user.last_name} by {self.request.user.first_name} { self.request.user.last_name}"
        )

        # Delete user_id from session so it can be set to the child user if applicable
        if "user_id" in self.request.session:
            del self.request.session["user_id"]
        return HttpResponseRedirect(self.get_success_url(child_user.id))
Exemple #3
0
def create_room():
    room_id = ShortUUID().random(length=8)
    while redis.exists(room_id):
        room_id = ShortUUID().random(length=8)
    session['room'] = room_id
    session['user'] = None
    redis.hmset(room_id, {'user_1': '', 'user_2': ''})
    redis.expire(room_id, timedelta(days=1))
    return jsonify({'room_id': room_id})
 def __init__(self, table_prefix="", region_name=None,
              endpoint_url=None):
     self._client = boto3.client('dynamodb',
                                 region_name=region_name,
                                 endpoint_url=endpoint_url)
     self._db = boto3.resource("dynamodb",
                               region_name=region_name,
                               endpoint_url=endpoint_url)
     self._table_prefix = table_prefix
     self._create_all_tables()
     self._uuid = ShortUUID()
     self._uuid.set_alphabet('23456789abcdefghijkmnopqrstuvwxyz')
Exemple #5
0
    def generate_hash_path():
        """Generates a hash ussing UUID

        WARNING: There is a chance that hash will be repeated especially since
        UUID is only 8 characters long
        """
        return ShortUUID().random(HASH_LENGTH)
Exemple #6
0
def createBackupCodes(user_id, key, p):
    pwd_check = check_for_password_and_backup_codes(user_id, p['password'])
    if not pwd_check['success']:
        return {'success': False, 'message': 'Wrong password!'}

    file_content = read_users()
    new_backup_codes = []

    if isinstance(file_content, dict):
        for user in file_content['users']:
            if user['user_id'] == user_id:
                user['backup_codes'] = []
                for x in range(6):
                    backup_code = ShortUUID().random(length=10)
                    backup_code_key = create_new_key_from_password(backup_code)
                    enc_orig_password = encrypt_by_key(
                        pwd_check['password'].encode(), backup_code_key['key'])

                    user['backup_codes'].append({'password': generate_password_hash(backup_code, method='sha256'), 'salt': backup_code_key['salt'].decode(
                    ), 'enc_orig_password': enc_orig_password.decode()})
                    new_backup_codes.append(backup_code)
    else:
        return {'success': False}

    if write_users(file_content):
        return {'success': True, 'backupCodes': new_backup_codes}
    else:
        return {'success': False, 'message': 'Internal Error on generating new backup codes!'}
def _create_replay(user, game, friendly_player_id=1):
    replay = GameReplay(user=user,
                        global_game=game,
                        friendly_player_id=friendly_player_id,
                        shortid=ShortUUID().random())
    replay.save()

    return replay
Exemple #8
0
 def create(cls, poll, vote_points, voter_name, voter_code):
     import string
     alphabet = string.ascii_uppercase
     if voter_code is None:
         voter_code = ShortUUID(alphabet=alphabet).random(length=6)
     return Vote(poll=poll,
                 vote_points=vote_points,
                 voter_name=voter_name,
                 voter_code=voter_code)
Exemple #9
0
def capture_photo():
    photo.set_filepath(
        ShortUUID(alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ").random(length=9))
    myGPIO.spots_on(True)
    sleep(0.3)
    photo.capture()
    print("Capturing " + photo.pathname)
    GUI.show_success()
    sleep(0.3)
    myGPIO.spots_on(False)
def share_list(event, context):
    list_id = event['pathParameters']['id']
    if event['isBase64Encoded']:
        body = base64.b64decode(event['body'])
    else:
        body = event['body']

    try:
        seconds_from_now = int(body)
    except ValueError:
        return {
            'statusCode':
            400,
            'body':
            json.dumps({
                'status': 'error',
                'reason': 'Incorrect TTL value'
            })
        }

    if seconds_from_now <= 0:
        return {
            'statusCode':
            400,
            'body':
            json.dumps({
                'status': 'error',
                'reason': 'TTL value must be positive'
            })
        }
    lists = l_table.get_item(Key={'id': list_id})

    if 'Item' not in lists:
        return {
            'statusCode':
            404,
            'body':
            json.dumps({
                'status': 'error',
                'reason': 'List does not exist'
            })
        }

    valid_until = datetime.now() + timedelta(seconds=seconds_from_now)
    item = {
        'id': ShortUUID().random(length=4),
        'list_id': list_id,
        'valid_until': int(valid_until.timestamp())
    }
    sharing_table.put_item(Item=item)

    return {'statusCode': 200, 'body': json.dumps(item, cls=DecimalEncoder)}
Exemple #11
0
    def __init__(self, original_url=None, generated_url=None):
        """
        Parameters
        ----------

        original_url : str
            The URL received in the request
        generated_url : str
            The URL generated with a length of 7 characters
        """
        self.id = ShortUUID().random(length=10)
        self.original_url = original_url
        self.generated_url = generated_url
Exemple #12
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["random_quote"] = random.choice(self.quotes)
        user = self.request.user

        if user.is_authenticated and feature_enabled_for_user(
                "reflinks", user):
            try:
                context["reflink"] = ReferralLink.objects.get(user=user)
            except ReferralLink.DoesNotExist:
                context["reflink"] = ReferralLink.objects.create(
                    identifier=ShortUUID().uuid()[:6], user=user)

        return context
 def create(new_list_dto: NewList, user_sub: str) -> ListModel:
     list_dto = ListModel(
         id=ShortUUID.random(length=6),
         userId=user_sub,
         listName=new_list_dto.name,
         createdAt=datetime.utcnow(),
         items=new_list_dto.items,
         guests=new_list_dto.guests,
     )
     Lists.save(ListMappers.map_dto_to_doc(list_dto))
     UserToLists.add_list(user_sub, list_dto.id)
     for guest_id in new_list_dto.guests:
         UserToLists.add_list(guest_id, list_dto.id)
     return list_dto
Exemple #14
0
	def get_context_data(self, **kwargs):
		context = super().get_context_data(**kwargs)

		if feature_enabled_for_user("reflinks", self.request.user):
			try:
				context["reflink"] = ReferralLink.objects.get(user=self.request.user)
				context["hits"] = ReferralHit.objects.filter(
					referral_link=context["reflink"]
				).exclude(confirmed=None).count()
			except ReferralLink.DoesNotExist:
				context["reflink"] = ReferralLink.objects.create(
					identifier=ShortUUID().uuid()[:6], user=self.request.user
				)

		return context
Exemple #15
0
    def get_react_context(self):
        ret = {}

        user = self.request.user
        if user.is_authenticated:
            reflink = ReferralLink.objects.filter(user=user).first()
            if not reflink:
                reflink = ReferralLink.objects.create(
                    identifier=ShortUUID().uuid()[:6], user=user)
            if not reflink.disabled:
                ret["reflink"] = "https://hsreplay.net" + reflink.get_absolute_url(
                )
                ret["discount"] = "$2.50 USD"

        return ret
Exemple #16
0
def create_new_room():
    room_code = ShortUUID().random(length=5)

    room = Room(code=room_code)
    connection = Connection(room=room)

    db.session.add(room)
    db.session.add(connection)
    try:
        db.session.commit()
    except Exception as e:
        print(e)
        db.session.rollback()
        return jsonify(status='err', reason='db error')

    return jsonify(status='suc', roomcode=room_code, cid=connection.id)
Exemple #17
0
def server(obj, port: int, password: str):
    config = obj['config']
    cache = obj['cache']

    config['password'] = sha256(password)
    cache.set('config', config)
    print('服务器 最终设置', cache.get('config'))

    app = Sanic()

    Account.cache = cache
    Account.uuid = ShortUUID()

    @app.listener('before_server_start')
    async def setup_db(app, loop):
        app.cache = cache

    @app.exception(Forbidden)
    async def _403(request, exception):
        return text(exception, status=403)

    @app.exception(NotFound)
    async def _404(request, exception):
        return text(exception, status=404)

    @app.exception(ServerError)
    async def _500(request, exception):
        return text(exception, status=500)

    app.blueprint(index)
    app.blueprint(admin)
    app.blueprint(admin_api)

    # 静态文件资源
    res_path = os.path.join(os.path.dirname(__file__), 'res', 'resources')
    app.static('/resources/', res_path)

    favicon = os.path.join(os.path.dirname(__file__), 'res', 'favicon.ico')
    app.static('/favicon.ico', favicon)

    loop_task.run(cache=cache)

    if 'win' in sys.platform:
        app.run(host='0.0.0.0', port=port)
    else:
        app.run(host='0.0.0.0', port=port, workers=4)
Exemple #18
0
def create(event, context):
    logger.debug(event)

    if event['isBase64Encoded']:
        body = base64.b64decode(event['body'])
    else:
        body = event['body']
    data = json.loads(body)

    user_data = event['requestContext']['authorizer']['jwt']['claims']

    if 'name' not in data:
        return {
            'statusCode':
            400,
            'body':
            json.dumps({
                'status': 'error',
                'reason': '"name" attribute has not been provided'
            })
        }
    items = data.get('items', [])
    guests = data.get('guests', [])

    item_id = ShortUUID().random(length=6)
    timestamp = int(time.time())

    item = {
        'id': item_id,
        'user_id': user_data['sub'],
        'list_name': data['name'],
        'created_at': timestamp,
        'items': items,
        'guests': guests
    }

    l_table.put_item(Item=item)

    _add_to_users_lists(user_data['sub'], item_id)

    return {'statusCode': 200, 'body': json.dumps(item)}
Exemple #19
0
    def get_react_context(self):
        reflink = ReferralLink.objects.filter(user=self.request.user).first()
        if not reflink:
            reflink = ReferralLink.objects.create(
                identifier=ShortUUID().uuid()[:6], user=self.request.user)

        if reflink.disabled:
            reflink_url = ""
        else:
            reflink_url = "https://hsreplay.net" + reflink.get_absolute_url()

        return {
            "collection_visibility":
            self.request.user.settings.get("collection-visibility", ""),
            "default_replay_visibility":
            self.request.user.default_replay_visibility,
            "exclude_from_statistics":
            self.request.user.exclude_from_statistics,
            "reflink":
            reflink_url,
            "hits":
            ReferralHit.objects.filter(referral_link=reflink).exclude(
                confirmed=None).count(),
        }
Exemple #20
0
from pyonedesk.config import stylizes as default_stylizes
from pyonedesk.utils import upload
from .account import Account, make_header
from .utils import sha256, createAppUrl, getCodeUrl

admin = Blueprint('admin', url_prefix='/admin')
admin_api = Blueprint('admin_api', url_prefix='/admin/api')

prefix = '/admin'

res_dir = os.path.join(os.path.dirname(__file__), 'res')

__iv = 'This is an IV456'

uuid = ShortUUID()


def __check_token(request) -> bool:
    """
    检查cookies['token']
    :param request:
    :return:
    """
    token = request.cookies.get('token')
    cache: Cache = request.app.cache

    if token is None:
        return False
    # todo 测试
    test = cache.get(token, default=False)
Exemple #21
0
 def generate_uid(self):
     return self.uid_prefix + ShortUUID().random(UUID_LENGTH)
Exemple #22
0
from django.dispatch import receiver
from django.utils import timezone
from django.utils.functional import cached_property
from django.utils.module_loading import import_string
from django_fsm import FSMField, transition
from elasticsearch import TransportError
from elasticsearch_dsl import Index
from model_utils import Choices, managers
from shortuuid import ShortUUID

from yurika.utils import utils, validators

from . import documents

# Elasticsearch-friendly identifiers (no uppercase characters)
b36_uuid = ShortUUID(alphabet='0123456789abcdefghijklmnopqrstuvwxyz')


def validate_domains(text):
    for domain in text.splitlines():
        msg = "Invalid domain name: '%(domain)s'." % {'domain': domain}
        validators.DomainValidator(message=msg)(domain)


def validate_dict(value):
    if not isinstance(value, dict):
        raise ValidationError("Value is not a 'dictionary' type.")


class CastingManager(managers.InheritanceManager):
    """
class DynamoDBStorage(Storage):
    _logger = logging.getLogger("flask-blogging")

    def __init__(self, table_prefix="", region_name=None,
                 endpoint_url=None):
        self._client = boto3.client('dynamodb',
                                    region_name=region_name,
                                    endpoint_url=endpoint_url)
        self._db = boto3.resource("dynamodb",
                                  region_name=region_name,
                                  endpoint_url=endpoint_url)
        self._table_prefix = table_prefix
        self._create_all_tables()
        self._uuid = ShortUUID()
        self._uuid.set_alphabet('23456789abcdefghijkmnopqrstuvwxyz')

    def save_post(self, title, text, user_id, tags, draft=False,
                  post_date=None, last_modified_date=None, meta_data=None,
                  post_id=None):
        try:
            current_datetime = datetime.datetime.utcnow()
            post_date = post_date or current_datetime
            post_date = self._to_timestamp(post_date)
            last_modified_date = last_modified_date or current_datetime
            tags = self.normalize_tags(tags)
            draft = 1 if draft else 0
            r = {'title': title,
                 'text': text,
                 'user_id': user_id,
                 'tags': tags,
                 'draft': draft,
                 'post_date': post_date,
                 'last_modified_date': self._to_timestamp(last_modified_date),
                 'meta_data': meta_data
                 }
            if post_id is not None:
                response = self._blog_posts_table.get_item(
                    Key={'post_id': post_id})
                r0 = response.get("Item")
                post_id = r0['post_id'] if r0 else None

            if post_id is None:
                post_id = self._uuid.uuid()
                r['post_id'] = post_id
                self._blog_posts_table.put_item(Item=r)
                self._insert_tags(tags, post_id, post_date, draft)
            else:
                expr = 'SET title = :title, #t = :text, user_id = :user_id, '\
                       'tags = :tags, draft = :draft, '\
                       'post_date = :post_date, '\
                       'last_modified_date = :last_modified_date, '\
                       'meta_data = :meta_data'
                self._blog_posts_table.update_item(
                    Key={'post_id': post_id},
                    UpdateExpression=expr,
                    ExpressionAttributeValues={
                        ':title': r['title'],
                        ':text': r['text'],
                        ':user_id': r['user_id'],
                        ':tags': r['tags'],
                        ':draft': r['draft'],
                        ':post_date': r['post_date'],
                        ':last_modified_date': r["last_modified_date"],
                        ':meta_data': r['meta_data']
                    },
                    ExpressionAttributeNames={'#t': 'text'},
                    ReturnValues="ALL_NEW"
                )

                tag_inserts = set(r['tags']) - set(r0['tags'])
                tag_deletes = set(r0['tags']) - set(r['tags'])
                self._insert_tags(tag_inserts, post_id, post_date, draft)
                self._delete_tags(tag_deletes, post_id)
        except Exception as e:
            self._logger.exception(str(e))
            post_id = None
        return post_id

    def get_posts(self, count=10, offset=0, recent=True, tag=None,
                  user_id=None, include_draft=False):
        try:
            post_ids = self._get_post_ids(count=count, offset=offset,
                                          recent=recent,
                                          tag=tag, user_id=user_id,
                                          include_draft=include_draft)
        except Exception as e:
            self._logger.exception(str(e))
            post_ids = []
        return [self.get_post_by_id(p) for p in post_ids]

    def _get_post_ids(self, count=10, offset=0, recent=True, tag=None,
                      user_id=None, include_draft=False):
        # include_draft is not supported yet
        kwargs = dict(ProjectionExpression='post_id',
                      ScanIndexForward=not recent)
        if count:
            kwargs['Limit'] = count
        table = self._blog_posts_table
        if user_id:
            kwargs.update(
                dict(IndexName='user_id_index',
                     KeyConditionExpression=Key('user_id').eq(user_id))
            )

        elif tag:
            table = self._tag_posts_table
            norm_tag = self.normalize_tag(tag)
            kwargs.update(
                dict(IndexName='tag_index',
                     KeyConditionExpression=Key('tag').eq(norm_tag))
            )
        else:
            kwargs.update(
                dict(IndexName='post_index',
                     KeyConditionExpression=Key('draft').eq(0))
            )
        if offset and offset > 0:
            kwargs2 = copy.deepcopy(kwargs)
            kwargs2['Limit'] = offset
            response = getattr(table, "query")(**kwargs2)
            last_key = response.get('LastEvaluatedKey')
        else:
            last_key = None

        if last_key:
            kwargs["ExclusiveStartKey"] = last_key
        response = getattr(table, "query")(**kwargs)
        return [p['post_id'] for p in response['Items']]

    def count_posts(self, tag=None, user_id=None, include_draft=False):
        try:
            post_ids = self._get_post_ids(count=None, offset=0, tag=tag,
                                          user_id=user_id,
                                          include_draft=include_draft)
            result = len(post_ids)
        except Exception as e:
            self._logger.exception(str(e))
            result = 0
        return result

    def get_post_by_id(self, post_id):
        try:
            response = self._blog_posts_table.get_item(
                Key={'post_id': post_id}
            )
            item = response.get('Item')
            if item:
                r = item
                r['post_date'] = self._from_timestamp(r['post_date'])
                r['last_modified_date'] = \
                    self._from_timestamp(r['last_modified_date'])
                r["draft"] = bool(r["draft"])
            else:
                r = None
        except Exception as e:
            self._logger.exception(str(e))
            r = None
        return r

    def delete_post(self, post_id):
        try:
            r = self.get_post_by_id(post_id)
            if r:
                response = self._blog_posts_table.delete_item(
                    Key={'post_id': post_id})
                self._delete_tags(r["tags"], post_id)
                return True
            else:
                return False
        except Exception as e:
            self._logger.exception(str(e))
            return False

    @staticmethod
    def _to_timestamp(date_time):
        return date_time.isoformat()

    @staticmethod
    def _from_timestamp(timestamp):
        return datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S.%f")

    def _table_name(self, table_name):
        return self._table_prefix + table_name

    def _create_all_tables(self):
        response = self._client.list_tables()
        table_names = response["TableNames"]
        self._create_blog_posts_table(table_names)
        self._create_tag_posts_table(table_names)

    def _create_blog_posts_table(self, table_names):
        bp_table_name = self._table_name("blog_posts")
        if bp_table_name not in table_names:
            self._client.create_table(
                TableName=bp_table_name,
                KeySchema=[{
                    'AttributeName': 'post_id',
                    'KeyType': 'HASH'
                }
                ],
                GlobalSecondaryIndexes=[
                    {
                        'IndexName': "user_id_index",
                        'KeySchema': [
                            {
                                'AttributeName': 'user_id',
                                'KeyType': 'HASH',
                            },
                            {
                                'AttributeName': 'post_date',
                                'KeyType': 'RANGE',
                            }
                        ],
                        'Projection': {
                            'ProjectionType': 'ALL'
                        },
                        'ProvisionedThroughput': {
                            'ReadCapacityUnits': 2,
                            'WriteCapacityUnits': 2
                        }
                    },
                    {
                        'IndexName': "post_index",
                        'KeySchema': [
                            {
                                'AttributeName': 'draft',
                                'KeyType': 'HASH',
                            },
                            {
                                'AttributeName': 'post_date',
                                'KeyType': 'RANGE',
                            }
                        ],
                        'Projection': {
                            'ProjectionType': 'ALL'
                        },
                        'ProvisionedThroughput': {
                            'ReadCapacityUnits': 2,
                            'WriteCapacityUnits': 2
                        }
                    }
                ],
                AttributeDefinitions=[
                    {
                        'AttributeName': 'post_id',
                        'AttributeType': 'S'
                    },
                    {
                        'AttributeName': 'user_id',
                        'AttributeType': 'S'
                    },
                    {
                        'AttributeName': 'post_date',
                        'AttributeType': 'S'
                    },
                    {
                        'AttributeName': 'draft',
                        'AttributeType': 'N'
                    },
                ],
                ProvisionedThroughput={
                    'ReadCapacityUnits': 10,
                    'WriteCapacityUnits': 10
                }
            )
        self._blog_posts_table = self._db.Table(bp_table_name)

    def _create_tag_posts_table(self, table_names):
        tp_table_name = self._table_name("tag_posts")
        if tp_table_name not in table_names:
            self._client.create_table(
                TableName=tp_table_name,
                KeySchema=[{
                    'AttributeName': 'tag_id',
                    'KeyType': 'HASH'
                }
                ],
                GlobalSecondaryIndexes=[
                    {
                        'IndexName': "tag_index",
                        'KeySchema': [
                            {
                                'AttributeName': 'tag',
                                'KeyType': 'HASH',
                            },
                            {
                                'AttributeName': 'post_date',
                                'KeyType': 'RANGE',
                            }
                        ],
                        'Projection': {
                            'ProjectionType': 'ALL'
                        },
                        'ProvisionedThroughput': {
                            'ReadCapacityUnits': 2,
                            'WriteCapacityUnits': 2
                        }
                    },
                ],
                AttributeDefinitions=[
                    {
                        'AttributeName': 'tag_id',
                        'AttributeType': 'S'
                    },
                    {
                        'AttributeName': 'tag',
                        'AttributeType': 'S'
                    },
                    {
                        'AttributeName': 'post_date',
                        'AttributeType': 'S'
                    }
                ],
                ProvisionedThroughput={
                    'ReadCapacityUnits': 10,
                    'WriteCapacityUnits': 10
                }
            )
        self._tag_posts_table = self._db.Table(tp_table_name)

    def _insert_tags(self, tags, post_id, post_date, draft):
        for t in tags:
            tag_id = "%s_%s" % (t, post_id)
            _ = self._tag_posts_table.put_item(
                Item={'tag_id': tag_id, 'tag': t, 'post_date': post_date,
                      'post_id': post_id, 'draft': draft}
            )

    def _delete_tags(self, tags, post_id):
        for t in tags:
            tag_id = "%s_%s" % (t, post_id)
            _ = self._tag_posts_table.delete_item(
                Key={'tag_id': tag_id}
            )
Exemple #24
0
from shortuuid import ShortUUID

random_gen = ShortUUID()


def random_string(length=24):
    return random_gen.random(length)
Exemple #25
0
# 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.
#

from .exceptions import CannotEvaluateFunctionException
from .. import InvalidValueError
from ..presentation import Value
from ..utils import puts
from collections import OrderedDict
from shortuuid import ShortUUID
from random import randrange

#UUID = ShortUUID() # default alphabet is base57, which is alphanumeric without visually ambiguous characters; ID length is 22
UUID = ShortUUID(alphabet='abcdefghijklmnopqrstuvwxyz0123456789'
                 )  # alphanumeric; ID length is 25


def generate_id_string(length=None):
    """
    A random string with a strong guarantee of universal uniqueness (uses UUID).
    
    The default length is 25 characters.
    """

    the_id = UUID.uuid()
    if length is not None:
        the_id = the_id[:length]
    return the_id

Exemple #26
0
from shortuuid import ShortUUID
import string

alphabet = string.ascii_uppercase
helper = ShortUUID(alphabet=alphabet)


def code(length):
    return helper.random(length=length)


def code_6():
    return code(6)
 def gen_short_id():
     """
     Helper which randomly generates base62 id
     """
     return ShortUUID().random(length=settings.SHORT_ID_LEN)
Exemple #28
0
from . import WUSA_BASE_DIR
from . import WUSA_RUNNER_DIR
from .docker import wusa_docker_commit
from .docker import wusa_docker_container_stop
from .docker import wusa_docker_list_containers
from .docker import wusa_docker_remove
from .docker import wusa_docker_remove_image
from .docker import wusa_docker_run
from .exceptions import InvalidRunnerName
from .exceptions import RunnerFileIOError
from .gh import api_runner_removal
from .gh import post_gh_api
from .output import silent_print

UUID = ShortUUID(alphabet=ascii_lowercase)


@contextmanager
def open_runner_file(mode: str) -> Generator[IO, None, None]:
    runner_file = WUSA_BASE_DIR / "runners.json"
    runner_file.touch()
    with runner_file.open(mode) as fp:
        yield fp


@dataclass
class Runner:
    name: str
    repo: str
    status: str
Exemple #29
0
 def set_id(cls, id):
     return id or ShortUUID().random(length=10)
Exemple #30
0
 def store_data(self, values: dict):
     self.__stored_data_key = ShortUUID().random(24)
     values['_stored_data_key'] = self.__stored_data_key
     self.asset._deployment_data.update(values)  # noqa
Exemple #31
0
class Base(db.Model):
    """
    Convenience base DB model class. Makes sure tables in MySQL are created as InnoDB.
    This is to enforce foreign key constraints (MyISAM doesn't support constraints)
    outside of production. Tables are also named to avoid collisions.
    """
    @declared_attr
    def __tablename__(self):
        return '{}'.format(self.__name__.lower())

    __abstract__ = True
    __table_args__ = dict(mysql_charset='utf8', mysql_engine='InnoDB')

    id = Column(Integer, primary_key=True, autoincrement=True, nullable=True)
    uid = Column(db.String(STRING_LEN),
                 unique=True,
                 default=lambda: ShortUUID().random(length=8))
    _created_at = db.Column(db.DateTime, default=dt.utcnow, nullable=False)
    _updated_at = db.Column(db.DateTime,
                            default=dt.utcnow,
                            nullable=False,
                            onupdate=dt.utcnow)

    def _isinstance(self, model, raise_error=True):
        """Checks if the specified model instance matches the base's model.
        By default this method will raise a `ValueError` if the model is not the
        expected type.
        :param model: the model instance to check
        :param raise_error: flag to raise an error on a mismatch
        """
        rv = isinstance(model, self.__class__)
        if not rv and raise_error:
            raise ValueError('%s is not of type %s' % (model, self.__class__))
        return rv

    def _preprocess_params(self, kwargs):
        """Returns a preprocessed dictionary of parameters. Used by default
        before creating a new instance or updating an existing instance.
        :param kwargs: a dictionary of parameters
        """
        kwargs.pop('csrf_token', None)
        return kwargs

    def save(self, model):
        """Commits the model to the database and returns the model
        :param model: the model to save
        """
        self._isinstance(model)
        db.session.add(model)
        db.session.commit()
        return model

    def update(self, model, **kwargs):
        """Returns an updated instance of the base model class.
        :param model: the model to update
        :param **kwargs: update parameters
        """
        self._isinstance(model)
        for k, v in self._preprocess_params(kwargs).items():
            setattr(model, k, v)
        db.session.commit()
        return model

    def all(self):
        """Returns a generator containing all instances of the base model.
        """
        return self.__class__.query.all()

    def get_by_id(self, id):
        """Returns an instance of the base model with the specified id.
        Returns `None` if an instance with the specified id does not exist.
        :param id: the instance id
        """
        return self.__class__.query.get(id)

    def get_all(self, *ids):
        """Returns a list of instances of the base model with the specified
        ids.
        :param *ids: instance ids
        """
        return self.__class__.query.filter(self.__class__.id.in_(ids)).all()

    def find(self, **kwargs):
        """Returns a list of instances of the base model filtered by the
        specified key word arguments.
        :param **kwargs: filter parameters
        """
        return self.__class__.query.filter_by(**kwargs)

    def first(self, **kwargs):
        """Returns the first instance found of the base model filtered by
        the specified key word arguments.
        :param **kwargs: filter parameters
        """
        return self.find(**kwargs).first()

    def get_or_404(self, id):
        """Returns an instance of the base model with the specified id or
        raises an 404 error if an instance with the specified id does not exist.
        :param id: the instance id
        """
        return self.__class__.query.get_or_404(id)

    def new(self, **kwargs):
        """Returns a new, unsaved instance of the base model class.
        :param **kwargs: instance parameters
        """
        return self.__class__(**self._preprocess_params(kwargs))

    def create(self, **kwargs):
        """Returns a new, saved instance of the base model class.
        :param **kwargs: instance parameters
        """
        return self.save(self.new(**kwargs))

    def delete(self, model):
        """Immediately deletes the specified model instance.
        :param model: the model instance to delete
        """
        self._isinstance(model)
        db.session.delete(model)
        db.session.commit()

    def to_dict(self, *args, **kwargs):
        """returns a dict of all model attributes.
        excludes primary_key and foreign_keys
        :param d: an empty dictionary
        """
        d = dict((c.name, getattr(self, c.name))
                 for c in self.__table__.columns
                 if not c.primary_key and not c.foreign_keys)
        return d