Exemplo n.º 1
0
Arquivo: photo.py Projeto: ganap/so
    def post(self, request, *args, **kwargs):
        if not request.user.is_authenticated():
            return Response({}, status.HTTP_401_UNAUTHORIZED)
        data = dict(request.data)
        photo = data['photo'][0]
        name = photo.name
        ext = os.path.splitext(name)[-1]
        user_pk = data.get('user_pk', [0])
        user_pk = int(user_pk[0])
        if not user_pk:
            user_pk = request.user.pk
            user = request.user
        else:
            user = models.MainUser.objects.get(pk=user_pk)
            if request.user.pk != user_pk:
                if request.user.pk not in user.pk_can_edit:
                    if not request.user.is_admin:
                        return Response({}, status.HTTP_403_FORBIDDEN)

        filepath = "profile_photos/" + \
            helpers.id_generator() + str(helpers.timestamp_sec() / 100) + ext

        helpers.fs.save_file(filepath, photo)
        helpers.fs.generate_single_avatar(filepath, user.pk)
        if not user.is_organization and not user.is_expert:
            patient = users.Patient.objects.get(pk=user.patient)
            patient.photo = [filepath]
            patient.save()
        elif user.is_expert:
            expert = users.Expert.objects.get(pk=user.expert)
            expert.photo = [filepath]
            expert.save()

        return Response({'path': filepath})
Exemplo n.º 2
0
Arquivo: photo.py Projeto: ganap/so
    def post(self, request, *args, **kwargs):
        if not request.user.is_authenticated():
            return Response({}, status.HTTP_401_UNAUTHORIZED)
        data = dict(request.data)
        photo = data['photo'][0]
        name = photo.name
        ext = os.path.splitext(name)[-1]
        user_pk = data.get('user_pk', [0])
        user_pk = int(user_pk[0])
        if not user_pk:
            user_pk = request.user.pk
            user = request.user
        else:
            user = models.MainUser.objects.get(pk=user_pk)
            if request.user.pk != user_pk:
                if request.user.pk not in user.pk_can_edit:
                    if not request.user.is_admin:
                        return Response({}, status.HTTP_403_FORBIDDEN)

        filepath = "profile_photos/" + \
            helpers.id_generator() + str(helpers.timestamp_sec() / 100) + ext

        helpers.fs.save_file(filepath, photo)
        helpers.fs.generate_single_avatar(filepath, user.pk)
        if not user.is_organization and not user.is_expert:
            patient = users.Patient.objects.get(pk=user.patient)
            patient.photo = [filepath]
            patient.save()
        elif user.is_expert:
            expert = users.Expert.objects.get(pk=user.expert)
            expert.photo = [filepath]
            expert.save()

        return Response({'path': filepath})
Exemplo n.º 3
0
def saveDicomFromImagingStudy(reference, user_pk):
    r = requests.get("https://fhir-open-api.smarthealthit.org/" + reference,
                     stream=True)
    filename = helpers.id_generator(13)
    with open("/tmp/" + filename + ".dcm", 'wb') as f:
        r.raw.decode_content = True
        shutil.copyfileobj(r.raw, f)
    f = open("/tmp/" + filename + ".dcm")
    path = google_cloud.upload_to_gc(f)
    return path
Exemplo n.º 4
0
def deploy_dind(repo, branch):
    """ Deploys an isolated `Docker-In-Docker` environment and
    mounts the pulled repository to the container.
    :param oauth_token: Authorization token for Owner.
    :type oauth_token: String
    :param repo: Name of the cloned github repository.
    :type repo: String
    :param branch: Branch for the pull request.
    :type branch: String
    """
    oauth_token = session.get('oauth_token')
    name = "exdous-{}".format(id_generator())
    # to ssh into container use `docker exec -ti <name> /bin/sh`
    print("logging: Reading Testfile config")
    test_file_params = parse(repo, oauth_token)
    print("logging: Testfile config read")
    client = docker.from_env()
    try:
        volume = test_file_params['VOL']
        vol_host = os.getcwd() + "/{}".format(repo)
    except KeyError:
        volume = '/{}'.format(repo)
    try:
        cwd = test_file_params['CWD']
    except KeyError:
        cwd = '/'
    print("logging: find free port for the application")
    try:
        port = test_file_params['PORTS']
        free_port = find_free_port(1)[0]
    except KeyError:
        return redirect("404/Ports_Not_Mentioned")
    print("logging: will accept tcp request on port: {}".format(free_port))
    print("logging: deploying prmod/base-image")
    dind_env = client.containers.run(
        'prmod/base-image',
        name=name,
        ports={port: free_port},
        volumes={
            vol_host: {
                'bind': volume,
                'mode': 'rw'
            }
        },
        working_dir=cwd,
        privileged=True,
        detach=True)
    session['container_id'] = dind_env.id
    print("logging: prmod/base-image deployed")
    execute_testfile(dind_env, test_file_params)
    print("logging: application deployed on server")
    url = "{}:{}".format(Config.SERVER_IP, port)
    session['{0}-{1}'.format(repo, session.get('pr_no'))] = url
    return redirect(url)
Exemplo n.º 5
0
def git_pull_repo(user, owner, repo, branch):
    """ Pulls a repo from github and changes the branch.
    :param user: Authorized User.
    :type user: String
    :param owner: Repository Owner.
    :type owner: String
    :param repo: Name of the github repository.
    :type repo: String
    :param branch: Branch of the PR owner.
    :type branch: String
    :returns: Redirects to deploy_dind.
    """
    oauth_token = session.get('oauth_token')
    print("logging: Pulling Repository from github")
    # name of the cloned repository on server
    repo_name = "{0}-{1}".format(repo, id_generator())
    session['repo_name'] = repo_name
    try:
        # Clone the forked repository
        remote_url = constants.remote_url_string.format(user, repo)
        https_remote_url = constants.https_url_string.format(
            oauth_token,
            remote_url)
        Repo.clone_from(https_remote_url, repo_name)
    except KeyError:
        # Fork doesnot exist, Clone from main repository
        remote_url = constants.remote_url_string.format(owner, repo)
        https_remote_url = constants.https_url_string.format(
            oauth_token,
            remote_url)
        Repo.clone_from(https_remote_url, repo_name)
    print("logging: Repo pull complete")
    # change branch in the cloreponed repository
    os.chdir(repo_name)  # changes dir to the cloned repo
    os.system('git checkout {}'.format(branch))
    os.chdir('../')  # change back to the pwd
    return redirect(
        url_for(
            'deploy_dind',
            oauth_token=oauth_token,
            repo=repo_name,
            branch=branch)
        )
Exemplo n.º 6
0
def upload_photo():
    if request.method == 'POST':
        if 'file_data' not in request.files:
            return "File data not found"
        file = request.files['file_data']
        filename = file.filename
        if file and allowed_file(file.filename):
            logical_id = choice([1, 2])
            physical_ids = machine_mapping[logical_id]
            photoid = id_generator()
            payload = {"logicalFile": logical_id, "imageId": photoid}
            try:
                for phy in physical_ids:
                    r1 = requests.post("http://%s/addimage" %
                                       (port_mapping[phy]),
                                       data=payload,
                                       files={'file': file})
                    file.seek(0)
                r2 = get_caption(file)
            except Exception, e:
                print e
                return jsonify({
                    "error":
                    "There was some issue in uploading you files. Please try again."
                })
            # Insert into Mongo if request succeeded
            item = {
                "logical_id": logical_id,
                "_id": photoid,
                "physical_ids": physical_ids,
                "caption": r2["caption"],
                "category": r2["category"]
            }
            item["url"] = get_url(item)
            collection.insert_one(item)
            return jsonify(item)
        else:
            return jsonify({"error": "File name not allowed!"})