コード例 #1
0
    def validate(self, attrs):
        username_or_email = attrs['username_or_email']
        password = attrs['password']

        user_username = User.objects.filter(
            username__iexact=username_or_email).first()
        user_email = User.objects.filter(
            email__iexact=username_or_email).first()

        if user_email and user_username is None:
            msg = self.default_error_messages['email or username not verified']
            raise exceptions.AuthenticationFailed(msg)

        if user_username:

            if not user_username.check_password(password):
                msg = self.default_error_messages['wrong_password']
                raise exceptions.AuthenticationFailed(msg)
            access_token = generate(size=48)
            person, created = UserAuthInfo.objects.update_or_create(
                user=user_username, defaults={"access_token": access_token})
            data = {'access_token': str(access_token)}
        else:

            if not user_email.check_password(password):
                msg = self.default_error_messages['wrong_password']
                raise exceptions.AuthenticationFailed(msg)

            access_token = generate(size=48)
            person, created = UserAuthInfo.objects.update_or_create(
                user=user_email, defaults={"access_token": access_token})
            data = {'access_token': str(access_token)}

        attrs['data'] = data
        return attrs
コード例 #2
0
def create_new_user(socket_id):
    user = {
        "id": generate(),
        "username": "******" + generate(size=6),
        "socket_ids": [socket_id],
        "color": generate_random_hex_color()
    }
    return user
コード例 #3
0
def add_new_thread(board_id):
    try:
        db = get_db()
        now_timestamp = datetime.now(timezone.utc).timestamp()
        db.cursor().execute(
            """
            INSERT INTO thread(
                _id, board_id, text, created_on, bumped_on, reported, delete_password
            )
            VALUES (?, ?, ?, ?, ?, ?, ?)
            """,
            (
                nanoid.generate(),
                board_id,
                request.form["text"],
                now_timestamp,
                now_timestamp,
                False,
                request.form["delete_password"],
            ),
        )
        db.commit()

        return redirect(f"/b/{board_id}")

    except:
        return {"error": "Database error"}
コード例 #4
0
def signupUser(APP_ROOT, email, name, password):
    json_file = open(f"{APP_ROOT}/db/login.json", "r")
    users = json.load(json_file)
    backup = copy.deepcopy(users)
    json_file.close()
    resp = {}
    for user in users:
        if user["email"] == email:
            resp = {"status": "not-ok", "message": "Email already in use!"}
            return resp
    try:
        data = {
            "id": str(nanoid.generate()),
            "email": email,
            "name": name,
            "password": password,
        }
        users.append(data)
        json_file = open(f"{APP_ROOT}/db/login.json", "w")
        json_file.seek(0)
        json.dump(users, json_file, indent=2)
        json_file.close()
        resp = {"status": "ok", "message": "Signup successful!"}
        return resp
    except Exception:
        json_file = open(f"{APP_ROOT}/db/login.json", "w")
        json_file.seek(0)
        json.dump(backup, json_file, indent=2)
        json_file.close()
        resp = {"status": "not-ok", "message": "Signup failed!"}
        return resp
コード例 #5
0
    def reset_password(cls, data):
        new_password = nanoid.generate(size=20)
        display_name = normalize_display_name(data.get('username'))
        username = to_username(display_name)
        email = data.get('email', '')
        uuid = data.get('uuid')

        try:
            user, is_created = User.objects.reset_password(
                username, display_name, email, uuid, new_password)
        except ValidationError:
            logger.info({
                'event': 'password_reset_failed',
                'username': username,
                'uuid': uuid
            })
            raise

        logger.info({
            'event': 'password_reset_success',
            'username': user.username,
            'uuid': user.uuid,
            'is_created': is_created
        })

        return Response({'password': new_password})
コード例 #6
0
ファイル: views.py プロジェクト: Allirey/mps
    def post(self, request):
        data = request.data

        opening = Opening.objects.get(slug=data['slug'])
        chapter_number = int(
            data.get('chapter_number') or opening.chapters.count() + 1)

        jsoned_games = pgn_to_json(data['pgn'], False, True)

        with atomic():
            opening.chapters.filter(
                Q(chapter_number__gte=chapter_number)).update(
                    chapter_number=F('chapter_number') + len(jsoned_games))

            for i, game in enumerate(jsoned_games, start=chapter_number):
                title = f"{game['headers'].get('White')}. " \
                        f"{(game['headers'].get('Black')) if game['headers'].get('Black') else ''}"
                description = f"{game['headers'].get('Event')}"
                OpeningChapter(
                    title=title,
                    description=description,
                    chapter_number=i,
                    opening=opening,
                    url=generate(
                        '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
                        8),
                    data=game).save()

            opening.save()

            return Response(OpeningDetailSerializer(opening).data)
コード例 #7
0
ファイル: app.py プロジェクト: onderonur/bubbly-flask
def handle_chat_message(room_id, message_input):
    trimmed_body = message_input["body"]
    if trimmed_body:
        trimmed_body = utils.trim_spaces(trimmed_body)

    file = message_input["file"]
    if not trimmed_body and not file:
        return

    if file:
        is_image = utils.is_image_file(file)
        if not is_image:
            return

    current_user = session["current_user"]

    message = {
        "id": generate(),
        "author": current_user,
        "body": trimmed_body,
        "file": file,
        "timestamp": time() * 1000
    }
    emit("chat message", message, room=room_id, include_self=False)
    return message
コード例 #8
0
ファイル: views.py プロジェクト: pcp11/link-lizard
def index(request):
    """
    Index view for handling form data and generating shortened URLs
    """
    if request.method == "POST":
        form = URLMappingForm(request.POST)
        if form.is_valid():
            original_url = form.cleaned_data["original_url"]
            generated_hash = form.cleaned_data["generated_hash"] \
                if form.cleaned_data["generated_hash"] \
                else generate(size=5)

            mapping = URLMapping(original_url=original_url,
                                 generated_hash=generated_hash)
            mapping.save()

            base_url = request.META["HTTP_ORIGIN"] + "/"
            generated_url = base_url + mapping.generated_hash

            return JsonResponse({
                "original_url": original_url,
                "generated_url": generated_url
            })

        return JsonResponse({"errors": form.errors})

    form = URLMappingForm()
    return render(request, "home.html", {"form": form})
コード例 #9
0
def match_make(request: Dict[str, Any]):
    if request[GAME_ID] is None:
        publish(request[CONNECTION_CHANNEL], request[CONNECTION_KEY], {
            'type': 'response',
            'error': 'game-id was not specified'
        })

    existing_room = redis.spop('rooms:waiting:' + request[GAME_ID])
    player_id = generate()
    player_password = generate()
    register_player(request[CONNECTION_CHANNEL], request[CONNECTION_KEY],
                    player_id, player_password)
    if existing_room is not None:
        join_room(request, existing_room, player_id, player_password)
    else:
        create_room(request, player_id, player_password)
コード例 #10
0
 def __init__(self):
     self.state: Type[Fitting_State] = Fitting_State(self.broadcast)
     self.fso: Type[FSO] = FSO
     self.__guid: str = generate()
     self._subscribers: List[Callable] = []
     # self.client:Type[AsyncClient] = client
     self.client = None
コード例 #11
0
    def put_item(self, item: dict) -> dict:
        if '_id' not in item or bool(item['_id']) == False:
            item['_id'] = nanoid.generate()

        self.table.put_item(Item=item)

        return item
コード例 #12
0
    def create(self, request, *args, **kwargs):
        '''
        @param {string} message
        @param {string} user_id
        @param {string} post_id
        '''
        data = request.data
        try:
            user = User.objects.get(id=data['user_id'])
        except User.DoesNotExist:
            return Response(data={
                "success": False,
                "message": "User not found"
            },
                            status=406)
        try:
            post = Post.objects.get(id=data['post_id'])
        except Post.DoesNotExist:
            return Response(data={
                "success": False,
                "message": "Post not found"
            },
                            status=406)

        comment = Comment(id=generate(),
                          user=user,
                          message=data['message'],
                          post=post)
        comment.save()
        serialized = CommentSerializer(comment)
        return Response(data=serialized.data, status=201)
コード例 #13
0
def create_quiz():
    body = request.get_json()
    quiz_ott = body["ott"]

    # Create quiz record
    quiz_uuid = generate(size=8)
    quiz = Quiz(uuid=quiz_uuid, ott=quiz_ott, num_questions=5)
    db.session.add(quiz)
    db.session.flush()

    # Get node data for  the passed in OTT
    top_node = (db.session.query(Node.id, Node.name,
                                 Vernacular.vernacular).join(
                                     Vernacular,
                                     and_(
                                         Vernacular.ott == Node.ott,
                                         Vernacular.lang_primary == "en",
                                         Vernacular.preferred,
                                     ),
                                     isouter=True,
                                 ).where(Node.ott == quiz_ott).first())

    if not top_node:
        raise BadRequest("No node found with that ott.")

    db.session.commit()

    return {
        "uuid": quiz.uuid,
        "title": top_node.vernacular or top_node.name,
        "num_questions": quiz.num_questions,
    }
コード例 #14
0
def save_bracket_to_database(shared_bracket_data) -> str:
    """saves user's bracket & all its info/data to the database

    Args:
        shared_bracket_data (dict): a validated (via pydantic) bracket dict-like structure

    Returns:
        (str) bracket unique id for further sharing
    """
    # generate unique id for saving & sharing
    bracket_id = generate(size=13)
    # prepare bracket data
    bracket_type = shared_bracket_data["bracket_type"]
    title = shared_bracket_data["title"]
    value1 = shared_bracket_data["value1"]
    value2 = shared_bracket_data["value2"]
    extra = shared_bracket_data["extra"]
    bracket_info = shared_bracket_data["bracket_info"]
    bracket_info = json.dumps(bracket_info)
    bracket_entry = BracketData(bracket_id=bracket_id,
                                bracket_type=bracket_type,
                                title=title,
                                bracket_info=bracket_info,
                                value1=value1,
                                value2=value2,
                                extra=extra)
    # check if bracket has a winner, save if true
    if shared_bracket_data["winner"]:
        winner = shared_bracket_data["winner"]
        bracket_entry.winner = winner
    db.session.add(bracket_entry)
    db.session.commit()
    return bracket_id
コード例 #15
0
async def test(url: UrlSchema):
    url = dict(url)

    if url["customCode"]:
        shortCode = url["customCode"]
        shortCode = shortCode.replace(' ', '')
    else:
        shortCode = nanoid.generate(size=8)

    shortUrl = os.path.join(config("BASE_URL"), shortCode)

    urlExists = Url.objects(shortCode=shortCode)
    if len(urlExists) != 0:
        raise HTTPException(status_code=400,
                            detail="Short code is invalid, It has been used.")

    try:
        url = Url(longUrl=url["longUrl"],
                  shortCode=shortCode,
                  shortUrl=shortUrl)

        url.save()

        return {
            "message": "Successfully shortened URL.",
            "shortUrl": shortUrl,
            "longUrl": url["longUrl"]
        }

    except Exception as e:
        print(e)
        raise HTTPException(status_code=500,
                            detail="An unknown error occurred.")
コード例 #16
0
ファイル: api.py プロジェクト: leonhazen/python-qlink
def create(event, context):
    data = json.loads(event['body'])

    if 'url' not in data:
        logging.error('URL parameter not provided')
        return {
            'statusCode': 422,
            'body': json.dumps({'error_message': 'Insufficient data'})
        }

    url = data['url']

    if not url:
        logging.error('URL value missing')
        return {
            'statusCode': 422,
            'body': json.dumps({'error_message': 'URL missing'})
        }

    if not checkers.is_url(url):
        logging.error('URL is invalid')
        return {
            'statusCode': 422,
            'body': json.dumps({'error_message': 'URL invalid'})
        }

    if 'id' in data:
        id = data['id']
    else:
        id = generate(size=6)

    url_added = UrlModel(id=id, url=url, created=datetime.now())
    url_added.save()

    return {'statusCode': 200, 'body': json.dumps({'id': id, 'url': url})}
コード例 #17
0
    def test_flat_distribution(self):
        count = 100 * 1000
        length = 5
        alphabet = 'abcdefghijklmnopqrstuvwxyz'

        chars = {}
        for _ in range(count):
            id = generate(alphabet, length)
            for j in range(len(id)):
                char = id[j]
                if not chars.get(char):
                    chars[char] = 0
                chars[char] += 1

        self.assertEqual(len(chars.keys()), len(alphabet))

        max = 0
        min = maxsize
        for k in chars:
            distribution = (chars[k] * len(alphabet)) / float((count * length))
            if distribution > max:
                max = distribution
            if distribution < min:
                min = distribution
        self.assertLessEqual(max - min, 0.05)
コード例 #18
0
 def test_has_no_collisions(self):
     count = 100 * 1000
     used = {}
     for _ in range(count):
         id = generate()
         self.assertIsNotNone(id in used)
         used[id] = True
コード例 #19
0
ファイル: REST.py プロジェクト: shaw-rohit/wscs_tut_2019
 def post(self):
     if not re.match(regex, request.form['url']):  # check if input is URL
         abort(400)
     id = generate(size=max_id_size
                   )  # Generate new id and add it to the URL dictionary
     urls[id] = request.form['url']
     return {'id': id}, 201
コード例 #20
0
    def save(self):
        if self.reset_slug or not self.slug:
            hash = generate('1234567890abcdefefghijklmneoprstyuvwxyz')
            self.slug = slugify(hash)

        self.reset_slug = False
        return super(CV, self).save()
コード例 #21
0
def get_new_cavas():
    incoming = request.get_json()
    canvas_id = nanoid.generate(size=20)
    canvas_type = incoming["canvas_type"]
    canvas = Canvas({
        'canvas_id':
        canvas_id,
        'canvas_name':
        "New Canvas",
        'canvas_description':
        choice(awesome_text),
        'canvas_type':
        canvas_type,
        'canvas_team': [{
            "user": g.current_user["email"],
            "role": "creator"
        }],
        'canvas_preview':
        None,
        'canvas_notes':
        None,
        'canvas_lastUpdate':
        int(1000 * time.time())
    })
    try:
        canvas.save()
    except:
        return "Couldn't save that!", 501
    last_canvas = Canvas.find_one({"canvas_id": canvas_id}, {"_id": 0})
    return jsonify(canvas=last_canvas)
コード例 #22
0
def get_poses_from_video(video_download_path):

    poses = []
    images = []

    video_cap = cv2.VideoCapture(video_download_path)
    ret, frame = video_cap.read()
    height, width, ch = frame.shape
    
    output_path = "tmp/videos/output-videos/" + generate() + ".MOV"
    ffmpeg = "ffmpeg"
    dimension = f"{width}x{height}"
    f_format = "bgr24"
    fps = str(video_cap.get(cv2.CAP_PROP_FPS))

    command = [ffmpeg, "-y", "-f", "rawvideo", "-vcodec", "rawvideo", "-s", dimension, "-pix_fmt", f_format, "-r", fps, "-i", "-", "-an", "-vcodec", "mpeg4", "-b:v", "5000k", output_path]
    proc = sp.Popen(command, stdin=sp.PIPE, stderr=sp.PIPE)

    with mp_pose.Pose(min_detection_confidence=0.99, min_tracking_confidence=0.99) as pose:
        while video_cap.isOpened():
            success, image = video_cap.read()
            if not success:
                print("Can't receive frame")
                break

            image = cv2.cvtColor(cv2.flip(image, 1), cv2.COLOR_BGR2RGB)

            image.flags.writeable = False
            results = pose.process(image)

            image.flags.writeable = True
            image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
            mp_drawing.draw_landmarks(image, results.pose_landmarks, mp_pose.POSE_CONNECTIONS)

            images.append(image)
            
            proc.stdin.write(image.tostring())

            frame_pose = {}

            if results.pose_landmarks is not None:
                for lm_id, lm in enumerate(results.pose_landmarks.landmark):
                    h, w, _ = image.shape
                    frame_pose[str(2 * lm_id)] = lm.x * w
                    frame_pose[str(2 * lm_id + 1)] = lm.y * h
                
                poses.append(frame_pose)

            if cv2.waitKey(5) & 0xFF == ord("q"):
                break

        video_cap.release()
        proc.stdin.close()
        proc.stderr.close()
        proc.wait()

    os.remove(video_download_path)

    return poses, images, output_path
コード例 #23
0
 def __init__(self, path: str, fittings: list, props: dict):
     self.state: Type[FSO_State] = FSO_State(fittings, self)
     self.props: dict = Box(props)
     self._subscribers: list = []
     self.__guid: str = generate()
     self.__path: str = path
     self.__locked: bool = False
     self.__inbound_name: str = self.extract_inbound_name(path)
コード例 #24
0
 def new_or_get(self, name:str):
     new_client, _ = self.get_or_create(
         name = name,
         defaults = {
             'guid': generate()
         }
     )
     return new_client
コード例 #25
0
def _generate_slug_and_save(url):
    _slug = generate('1234567890abcdef', 5)
    _errors = ''
    global mappings
    if not mappings.save_mapping(_slug, url):
        _errors = 'Failed to save'
        logging.warning('failed to save document {}'.format(_errors))
    return (_slug, _errors)
コード例 #26
0
 def new_or_get(self, client: Type[Client], prod_num: int, **kwargs):
     new_project, _ = self.get_or_create(client=client,
                                         production_number=prod_num,
                                         defaults={
                                             'guid': generate(),
                                             **kwargs
                                         })
     return new_project
コード例 #27
0
ファイル: stream_writer.py プロジェクト: Mu-L/airbyte
    def generate_object_key(self, prefix=None):
        salt = nanoid.generate(size=10)
        base = datetime.now().strftime("%Y%m%d%H%M%S")
        path = f"{base}.{salt}.json"
        if prefix:
            path = f"{prefix}/{base}.{salt}.json"

        return path
コード例 #28
0
class BlogPost(models.Model):
    id = models.CharField(max_length=21, primary_key=True, default=generate(), editable=False)
    title = models.CharField(max_length=50, unique=True)
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title
コード例 #29
0
ファイル: motion_model.py プロジェクト: gerkx/big-bang-pipe
 def new_or_get(self, shot: Type[Shot], name: str, location: str, **kwargs):
     new_motion_shot, _ = self.get_or_create(shot=shot,
                                             name=name,
                                             defaults={
                                                 'guid': generate(),
                                                 'location': location,
                                                 **kwargs,
                                             })
     return new_motion_shot
コード例 #30
0
    def __init__(
        self,
        params: ObjMap,
        pop: Optional["population.Population"] = None,
    ):
        """
        This is the core class used to simulate the spread of exposures through a relationship based network.

        args:
            params: the parameter object for this model
            pop: an initialized population to run the model on
        """

        self.params = params
        # pre-fetch commonly used param sub-sets for performance
        self.calibration = params.calibration

        print("=== Begin Initialization Protocol ===\n")

        if pop is None:
            print("\tGenerating new population")
            self.pop = population.Population(params)
        else:
            print("\tUsing provided population")
            self.pop = pop

        self.time = -1 * self.params.model.time.burn_steps  # burn is negative time
        self.id = nanoid.generate(size=8)

        self.features = [
            feature for feature in features.BaseFeature.__subclasses__()
            if self.params.features[feature.name]
        ]

        # set up the in-scope exposures
        self.exposures = [
            exposure for exposure in exposures.BaseExposure.__subclasses__()
            if self.params.exposures[exposure.name]
        ]

        self.interactions = {
            interaction.name: interaction
            for interaction in interactions.BaseInteraction.__subclasses__()
        }

        # Set seed format. 0: pure random, else: fixed value
        self.run_seed = utils.get_check_rand_int(params.model.seed.run)
        print(f"\tRun seed was set to: {self.run_seed}")
        self.run_random = random.Random(self.run_seed)
        self.np_random = np.random.default_rng(self.run_seed)
        random.seed(self.run_seed)
        print(("\tFIRST RANDOM CALL {}".format(random.randint(0, 100))))

        print("\tResetting death count")
        self.deaths: List["ag.Agent"] = []  # Number of death

        print("\n === Initialization Protocol Finished ===")