示例#1
0
文件: base.py 项目: datduyng/ccapi
    def _build_url(self, *args, **kwargs):
        prefix = kwargs.get("prefix", True)
        parts = []

        if prefix:
            parts.append(self.base_url)

        url = "/".join(map(str, sequencify(parts) + sequencify(args)))

        return url
示例#2
0
def render_template(template, dirs = [ ], context = None, **kwargs):
    """
    Renders a template. The template must be of the string format. For more 
    details, see 
    https://docs.python.org/3.4/library/string.html#string-formatting.

    :param template: Path to template file.
    :param context: The context passed to the template.
    :param dirs: Path/List of Directory Paths to search for templates.

    :return: Returns the rendered template.
    :rtype: str

    Usage::

        >>> from ccapi.template import render_template
        >>> render_template("test.html", context = dict(name = "Test"))
        'Hello, Test!'
        >>> render_template("test.html", name = "Test")
        'Hello, Test!'
        >>> render_template("foobar.html", dirs = "templates", bar = "baz")
        'foobaz'
    """
    dirs = sequencify(dirs)
    if PATH["TEMPLATES"] not in dirs:
        dirs.append(PATH["TEMPLATES"])

    dirs = [osp.abspath(dir_) for dir_ in dirs]

    logger.info("Searching for templates within directories: %s" % dirs)

    path = None
    for dir_ in dirs:
        temp = osp.join(dir_, template)
        if osp.exists(temp):
            path = temp
            break
    
    if not path:
        raise TemplateNotFoundError("Template %s not found." % template)
    
    html     = read(path)
    rendered = html

    if not context:
        context  = kwargs

    if context:
        for name, item in iteritems(context):
            item = str(item)
            item = cgi.escape(item)
            
            context[name] = item

        rendered = html.format(**context)
    
    return rendered
示例#3
0
文件: helper.py 项目: datduyng/ccapi
def _model_response_to_model(client, response):
    data = response["model"]

    model = Model(id=int(data["id"]),
                  name=data["name"],
                  domain=data["type"],
                  client=client)

    # HACK: remove default version provided.
    model.versions.pop()

    model.description = data["description"]
    model.author = data["author"]
    model.tags = data["tags"] and data["tags"].split(", ")

    model.citations = data["cited"]

    model.created = cc_datetime_to_datetime(data.get("creationDate")) or now()

    model.updated = dict(
        biologic=cc_datetime_to_datetime(data.get("biologicUpdateDate")),
        knowledge=cc_datetime_to_datetime(data.get("knowledgeBaseUpdateDate")))

    model.public = data["published"]

    model.user = client.get("user", id=data["userId"])

    model.hash = data.get("hash")

    model.permissions = response["modelPermissions"]

    versions = list(data["modelVersionMap"].keys())
    versions_content = sequencify(
        client.get("model", id=model.id, version=versions,
                   raw=True))  #raw must be true here.

    for content in versions_content:
        version, meta = _model_version_response_to_boolean_model(
            client, content)

        model = _merge_metadata_to_model(model, meta)

        model.add_version(version)

    if response["uploadMap"]:
        for _, upload_data in iteritems(response["uploadMap"]):
            document = Document(name=upload_data["uploadName"], client=client)

            document.user = client.get("user", id=upload_data["userId"])
            document.created = cc_datetime_to_datetime(
                upload_data["uploadDate"])
            document._token = upload_data["token"]

            model.documents.append(document)

    return model
示例#4
0
    def get(self, resource, *args, **kwargs):
        """
        Get resources.

        :param resource: Resource name.
        """
        _resource = resource.lower()
        resources = []

        id_ = kwargs.get("id")
        query = kwargs.get("query")
        raw = kwargs.get("raw", False)

        filters = kwargs.get("filters", {})

        size = kwargs.get("size", config.max_api_resource_fetch)
        since = kwargs.get("since", 1)
        since = since if since > 0 else 1

        if id_:
            if isinstance(id_, string_types) and id_.isdigit():
                id_ = int(id_)
            id_ = sequencify(id_)

        if _resource == "model":
            url = self._build_url("_api", "model", "get", prefix=False)
            urls = None
            params = None

            version = kwargs.get("version")
            hash_ = kwargs.get("hash")

            if version:
                if isinstance(version, string_types) and version.isdigit():
                    version = int(version)
                version = sequencify(version)

            if id_:
                urls = [
                    self._build_url(url, str(id), prefix=False) for id in id_
                ]

                if version:
                    params = dict({
                        "version": str(version) + \
                            ("&%s" % hash_ if hash_ else "")
                    })

            if query:
                url = self._build_url(url, prefix=False)
                params = [("search", "species"), ("search", "knowledge"),
                          ("name", query)]

            if urls:
                req_map = None
                if version:
                    assert len(urls) == 1
                    req_map = (self.request("GET", urls[0],  params = dict({
                        "version": str(v) + \
                            ("&%s" % hash_ if hash_ else "")
                    }), async_request=True) for v in version)
                else:
                    req_map = (self.request("GET",
                                            u,
                                            params=params,
                                            async_request=True) for u in urls)

                response = grequests.map(
                    req_map,
                    exception_handler=lambda req, ex: print("request failed"))
                content = []
                for r in response:
                    try:
                        content.append(r.json())
                        if r.json().get(
                                'status') and r.json()['status'] is 400:
                            raise ValueError(r.message)
                    except:
                        raise ValueError(r._content)
            else:
                response = self.request("GET", url, params=params)
                content = response.json()

            if id_:
                models = self.get("model", size=sys.maxsize, raw=True)
                filtered_model = [
                    model for model in models if model["model"]["id"] in id_
                ]
                resources = content if raw else [
                    _model_response_to_model(self, m) for m in filtered_model
                ]
            else:
                if filters:
                    if "user" in filters:
                        user = filters["user"]

                        if isinstance(user, int):
                            user = self.get("user", id=user)

                        if not isinstance(user, User):
                            raise TypeError(
                                "Expected type for user is User or ID, type %s found."
                                % type(user))

                        content = list(
                            filter(lambda x: x["model"]["userId"] == user.id,
                                   content))

                    if "domain" in filters:
                        domain = filters["domain"]

                        if domain not in _ACCEPTED_MODEL_DOMAIN_TYPES:
                            raise TypeError("Not a valid domain type: %s" %
                                            domain)
                        else:
                            content = list(
                                filter(lambda x: x["model"]["type"] == domain,
                                       content))

                from_, to = since - 1, min(len(content), size)
                content = content[from_:from_ + to]

                resources = content if raw else \
                    QueryList([
                        _model_response_to_model(self, obj)
                            for obj in content
                    ])
        elif _resource == "user":
            if not id_:
                raise ValueError("id required.")

            response = self.request("GET",
                                    "_api/user/lookupUsers",
                                    params=[("id", i) for i in id_])
            content = response.json()

            for user_id, user_data in iteritems(content):
                user = _user_response_to_user(
                    self, merge_dict({"id": user_id}, user_data))
                resources.append(user)

        return squash(resources)