Python typing.Dict() Examples

The following are 30 code examples of typing.Dict(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module typing , or try the search function .
Example #1
Source File: conftest.py    From mutatest with MIT License 8 votes vote down vote up
def write_cov_file(line_data: Dict[str, List[int]], fname: str) -> None:
    """Write a coverage file supporting both Coverage v4 and v5.

    Args:
        line_data: Dictionary of line data for the coverage file.
        fname: string filename for output location (absolute path)

    Returns:
        None
    """
    if coverage.version_info[0] == 4:
        covdata = coverage.CoverageData()
        covdata.add_lines(line_data)
        covdata.write_file(fname)

    else:
        # assume coverage v 5
        covdata = coverage.CoverageData(basename=fname)
        covdata.add_lines(line_data)
        covdata.write()


####################################################################################################
# CLI: MOCK ARGS
#################################################################################################### 
Example #2
Source File: crud_helpers.py    From hydrus with MIT License 7 votes vote down vote up
def apply_filter(object_id: str, search_props: Dict[str, Any],
                 triples: Graph, session: scoped_session) -> bool:
    """Check whether objects has properties with query values or not.
    :param object_id: Id of the instance.
    :param search_props: Dictionary of query parameters with property id and values.
    :param triples: All triples.
    :param session: sqlalchemy scoped session.
    :return: True if the instance has properties with given values, False otherwise.
    """
    for prop in search_props:
        # For nested properties
        if isinstance(search_props[prop], dict):
            data = session.query(triples).filter(
                triples.GraphIII.subject == object_id, triples.GraphIII.predicate == prop).one()
            if apply_filter(data.object_, search_props[prop], triples, session) is False:
                return False
        else:
            data = session.query(triples).filter(
                triples.GraphIIT.subject == object_id, triples.GraphIIT.predicate == prop).one()
            terminal = session.query(Terminal).filter(
                Terminal.id == data.object_).one()
            if terminal.value != search_props[prop]:
                return False
    return True 
Example #3
Source File: event_dispatcher.py    From clikit with MIT License 7 votes vote down vote up
def get_listeners(
        self, event_name=None
    ):  # type: (str) -> Union[List[Callable], Dict[str, Callable]]
        if event_name is not None:
            if event_name not in self._listeners:
                return []

            if event_name not in self._sorted:
                self._sort_listeners(event_name)

            return self._sorted[event_name]

        for event_name, event_listeners in self._listeners.items():
            if event_name not in self._sorted:
                self._sort_listeners(event_name)

        return self._sorted 
Example #4
Source File: helpers.py    From hydrus with MIT License 6 votes vote down vote up
def add_iri_template(path: str, API_NAME: str) -> Dict[str, Any]:
    """
    Creates an IriTemplate.
    :param path: Path of the collection or the non-collection class.
    :param API_NAME: Name of API.
    :return: Hydra IriTemplate .
    """
    template_mappings = list()
    template = "/{}/{}(".format(API_NAME, path)
    first = True
    template, template_mappings = generate_iri_mappings(path, template,
                                                        template_mapping=template_mappings,)

    template, template_mappings = add_pagination_iri_mappings(template=template,
                                                              template_mapping=template_mappings)
    return HydraIriTemplate(template=template, iri_mapping=template_mappings).generate() 
Example #5
Source File: invoice.py    From wechatpy with MIT License 6 votes vote down vote up
def get_info_batch(self, item_list: List[Dict[str, str]]) -> dict:
        """批量查询电子发票

        参考:https://work.weixin.qq.com/api/doc/90000/90135/90287

        报销方在获得用户选择的电子发票标识参数后,可以通过该接口批量查询电子发票的结构化信息。

        **权限说明**:
        仅认证的企业微信账号并且企业激活人数超过200的企业才有接口权限,如果认证的企业
        激活人数不超过200人请联系企业微信客服咨询。

        返回结果参数说明请查看官方文档。

        :param item_list: 发票列表,示例:
            [{'card_id': 'id', 'encrypt_code': 'code'}...]
        :return: 电子发票信息
        """
        if not item_list:
            raise ValueError("the item_list cannot be empty")

        url = "card/invoice/reimburse/getinvoiceinfobatch"
        data = {"item_list": item_list}
        return self._post(url, data=data) 
Example #6
Source File: views.py    From everyclass-server with Mozilla Public License 2.0 6 votes vote down vote up
def is_taking(cotc: Dict) -> bool:
    """检查当前用户是否选了这门课"""
    user_is_taking = False

    if session.get(SESSION_CURRENT_USER, None):
        # 检查当前用户是否选了这门课
        student = entity_service.get_student(session[SESSION_CURRENT_USER].identifier)
        for semester in sorted(student.semesters, reverse=True):  # 新学期可能性大,学期从新到旧查找
            timetable = entity_service.get_student_timetable(session[SESSION_CURRENT_USER].identifier, semester)
            for card in timetable.cards:
                if card.course_id == cotc["course_id"] and cotc["teacher_id_str"] == teacher_list_to_tid_str(
                        card.teachers):
                    user_is_taking = True
                    break
            if user_is_taking:
                break
    return user_is_taking 
Example #7
Source File: client.py    From gql with MIT License 6 votes vote down vote up
def subscribe(
        self, document: DocumentNode, *args, **kwargs
    ) -> Generator[Dict, None, None]:
        """Execute a GraphQL subscription with a python generator.

        We need an async transport for this functionality.
        """

        async_generator = self.subscribe_async(document, *args, **kwargs)

        loop = asyncio.get_event_loop()

        assert not loop.is_running(), (
            "Cannot run client.subscribe if an asyncio loop is running."
            " Use subscribe_async instead."
        )

        try:
            while True:
                result = loop.run_until_complete(async_generator.__anext__())
                yield result

        except StopAsyncIteration:
            pass 
Example #8
Source File: helpers.py    From hydrus with MIT License 6 votes vote down vote up
def get_link_props_for_multiple_objects(path: str,
                                        object_list: List[Dict[str, Any]]
                                        ) -> Tuple[List[Dict[str, Any]], bool]:
    """
    Get link_props of multiple objects.
    :param path: Path of the collection or non-collection class.
    :param object_list: List of objects being inserted.
    :return: List of link properties processed with the help of get_link_props.
    """
    link_prop_list = list()
    for object_ in object_list:
        link_props, type_check = get_link_props(path, object_)
        if type_check is True:
            link_prop_list.append(link_props)
        else:
            return [], False
    return link_prop_list, True 
Example #9
Source File: test_aiohttp_online.py    From gql with MIT License 5 votes vote down vote up
def test_aiohttp_simple_query(event_loop, protocol):

    # Create http or https url
    url = f"{protocol}://countries.trevorblades.com/graphql"

    # Get transport
    sample_transport = AIOHTTPTransport(url=url)

    # Instanciate client
    async with Client(transport=sample_transport) as session:

        query = gql(
            """
            query getContinents {
              continents {
                code
                name
              }
            }
        """
        )

        # Fetch schema
        await session.fetch_schema()

        # Execute query
        result = await session.execute(query)

        # Verify result
        assert isinstance(result, Dict)

        print(result)

        continents = result["continents"]

        africa = continents[0]

        assert africa["code"] == "AF" 
Example #10
Source File: test_websocket_query.py    From gql with MIT License 5 votes vote down vote up
def test_websocket_connect_success_with_authentication_in_connection_init(
    event_loop, server, query_str
):

    url = f"ws://{server.hostname}:{server.port}/graphql"
    print(f"url = {url}")

    init_payload = {"Authorization": 12345}

    sample_transport = WebsocketsTransport(url=url, init_payload=init_payload)

    async with Client(transport=sample_transport) as session:

        query1 = gql(query_str)

        result = await session.execute(query1)

        print("Client received:", result)

        # Verify result
        assert isinstance(result, Dict)

        continents = result["continents"]
        africa = continents[0]

        assert africa["code"] == "AF" 
Example #11
Source File: dao.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def get_review(cls, cotc_id: int) -> Dict:
        """
        获得一个教学班集合的评价
        {
            "avg_rate": 4.3,
            "count"   : 1,
            "reviews": [
                {
                    "review"  : "老师讲得好",
                    "rate"    : 5,
                    "stu_name": "16级软件工程专业学生"
                },
            ]
        }

        :param cotc_id: 教学班集合 ID
        :return:
        """
        db = get_mongodb()
        result = db.get_collection(cls.collection_name).aggregate([
            {"$match": {"cotc_id": int(cotc_id)}},
            {"$project": {
                "_id": 0,
                "student_id": 0,
                "cotc_id": 0}},
            {"$group": {"_id": None,
                        "avg_rate": {"$avg": "$rate"},
                        "reviews": {"$push": "$$ROOT"},
                        "count": {"$sum": 1}}}
        ])
        result = list(result)

        if result:
            result = result[0]
        else:
            result = {"avg_rate": 0,
                      "reviews": [],
                      "count": 0}
        return result 
Example #12
Source File: dao.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def get_my_review(cls, cotc_id: int, student_id: str) -> Dict:
        db = get_mongodb()
        doc = db.get_collection(cls.collection_name).find_one({"cotc_id": cotc_id,
                                                               "student_id": student_id})
        return doc 
Example #13
Source File: jsonable.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def __json_encode__(self) -> Dict:
        pass 
Example #14
Source File: calendar_token.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def find_calendar_token(token: str) -> Union[Dict, None]:
    ... 
Example #15
Source File: calendar_token.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def find_calendar_token(tid: str, semester: str) -> Union[Dict, None]:
    ... 
Example #16
Source File: service.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def find_calendar_token(token: str) -> Optional[Dict]:
    """查找一个token,如果存在,返回token信息,如果不存在,返回None"""
    return find_token(token=token) 
Example #17
Source File: service.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def generate_ics_file(type_: str, identifier: str, semester: str) -> str:
    """生成ics文件并返回文件名"""
    from everyclass.server import statsd  # 需要在这里导入,否则导入的结果是None

    cal_filename = f"{type_}_{identifier}_{semester}.ics"
    cal_full_path = os.path.join(calendar_dir(), cal_filename)
    # 有缓存、且缓存时间小于一天,且不用强刷缓存
    if os.path.exists(cal_full_path) \
            and use_cache(cal_filename):
        logger.info("ics cache hit")
        statsd.increment("calendar.ics.cache.hit")
        return cal_filename
    statsd.increment("calendar.ics.cache.miss")

    # 无缓存、或需要强刷缓存
    with tracer.trace('rpc'):
        # 获得原始学号或教工号
        if type_ == 'student':
            rpc_result = entity_service.get_student_timetable(identifier, semester)
        else:
            # teacher
            rpc_result = entity_service.get_teacher_timetable(identifier, semester)

        semester = Semester(semester)

        cards: Dict[Tuple[int, int], List[Dict]] = defaultdict(list)
        for card in rpc_result.cards:
            cards[lesson_string_to_tuple(card.lesson)].append(dict(name=card.name,
                                                                   teacher=teacher_list_to_name_str(card.teachers),
                                                                   week=card.weeks,
                                                                   week_string=card.week_string,
                                                                   classroom=card.room,
                                                                   cid=card.card_id_encoded))

    ics_generator.generate(name=rpc_result.name,
                           cards=cards,
                           semester=semester,
                           filename=cal_filename)

    return cal_filename 
Example #18
Source File: rooms.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def make(cls, dct: Dict) -> "AllRooms":
        dct_new = {"campuses": {}}
        for k, v in dct.items():
            dct_new["campuses"][k] = Campus.make(k, v)
        return cls(**ensure_slots(cls, dct_new)) 
Example #19
Source File: test_websocket_query.py    From gql with MIT License 5 votes vote down vote up
def test_websocket_starting_client_in_context_manager(event_loop, server):

    url = f"ws://{server.hostname}:{server.port}/graphql"
    print(f"url = {url}")

    sample_transport = WebsocketsTransport(url=url)

    async with Client(transport=sample_transport) as session:

        assert isinstance(
            sample_transport.websocket, websockets.client.WebSocketClientProtocol
        )

        query1 = gql(query1_str)

        result = await session.execute(query1)

        print("Client received:", result)

        # Verify result
        assert isinstance(result, Dict)

        continents = result["continents"]
        africa = continents[0]

        assert africa["code"] == "AF"

    # Check client is disconnect here
    assert sample_transport.websocket is None 
Example #20
Source File: test_websocket_online.py    From gql with MIT License 5 votes vote down vote up
def test_websocket_simple_query():

    # Get Websockets transport
    sample_transport = WebsocketsTransport(
        url="wss://countries.trevorblades.com/graphql"
    )

    # Instanciate client
    async with Client(transport=sample_transport) as session:

        query = gql(
            """
            query getContinents {
              continents {
                code
                name
              }
            }
        """
        )

        # Fetch schema
        await session.fetch_schema()

        # Execute query
        result = await session.execute(query)

        # Verify result
        assert isinstance(result, Dict)

        continents = result["continents"]

        africa = continents[0]

        assert africa["code"] == "AF" 
Example #21
Source File: client.py    From gql with MIT License 5 votes vote down vote up
def execute(self, document: DocumentNode, *args, **kwargs) -> Dict:
        """Execute the provided document AST against the configured remote server.

        This function WILL BLOCK until the result is received from the server.

        Either the transport is sync and we execute the query synchronously directly
        OR the transport is async and we execute the query in the asyncio loop
        (blocking here until answer).
        """

        if isinstance(self.transport, AsyncTransport):

            loop = asyncio.get_event_loop()

            assert not loop.is_running(), (
                "Cannot run client.execute if an asyncio loop is running."
                " Use execute_async instead."
            )

            data: Dict[Any, Any] = loop.run_until_complete(
                self.execute_async(document, *args, **kwargs)
            )

            return data

        else:  # Sync transports
            return self.execute_sync(document, *args, **kwargs) 
Example #22
Source File: websockets.py    From gql with MIT License 5 votes vote down vote up
def execute(
        self,
        document: DocumentNode,
        variable_values: Optional[Dict[str, str]] = None,
        operation_name: Optional[str] = None,
    ) -> ExecutionResult:
        """Execute a GrqphQLQuery.

        Send a query but close the async generator as soon as we have the first answer.

        The result is sent as an ExecutionResult object.
        """
        first_result = None

        generator = self.subscribe(
            document, variable_values, operation_name, send_stop=False
        )

        async for result in generator:
            first_result = result

            # Note: we need to run generator.aclose() here or the finally block in
            # the subscribe will not be reached in pypy3 (python version 3.6.1)
            await generator.aclose()

            break

        if first_result is None:
            raise TransportQueryError(
                "Query completed without any answer received from the server"
            )

        return first_result 
Example #23
Source File: test_websocket_query.py    From gql with MIT License 5 votes vote down vote up
def test_websocket_execute_sync(server):

    url = f"ws://{server.hostname}:{server.port}/graphql"
    print(f"url = {url}")

    sample_transport = WebsocketsTransport(url=url)

    client = Client(transport=sample_transport)

    query1 = gql(query1_str)

    result = client.execute(query1)

    print("Client received:", result)

    # Verify result
    assert isinstance(result, Dict)

    continents = result["continents"]
    africa = continents[0]

    assert africa["code"] == "AF"

    # Execute sync a second time
    result = client.execute(query1)

    print("Client received:", result)

    # Verify result
    assert isinstance(result, Dict)

    continents = result["continents"]
    africa = continents[0]

    assert africa["code"] == "AF"

    # Check client is disconnect here
    assert sample_transport.websocket is None 
Example #24
Source File: helpers.py    From hydrus with MIT License 5 votes vote down vote up
def get_link_props(path: str, object_) -> Tuple[Dict[str, Any], bool]:
    """
    Get dict of all hydra_link properties of a class.
    :param path: Path of the collection or non-collection class.
    :param object_: Object being inserted/updated.
    :return: Tuple with one elements as Dict with property_title as key and
             instance_id(for collection class) or class_name(for non-collection class) as value,
             second element represents boolean representing validity of the link.
    """
    link_props = {}
    for supportedProp in get_doc().parsed_classes[path]['class'].supportedProperty:
        if isinstance(supportedProp.prop, HydraLink) and supportedProp.title in object_:
            prop_range = supportedProp.prop.range
            range_class_name = prop_range.replace("vocab:", "")
            for collection_path in get_doc().collections:
                if collection_path in object_[supportedProp.title]:
                    class_title = get_doc().collections[collection_path]['collection'].class_.title
                    if range_class_name != class_title:
                        return {}, False
                    link_props[supportedProp.title] = object_[supportedProp.title].split('/')[-1]
                    break
            if supportedProp.title not in link_props:
                for class_path in get_doc().parsed_classes:
                    if class_path in object_[supportedProp.title]:
                        class_title = get_doc().parsed_classes[class_path]['class'].title
                        if range_class_name != class_title:
                            return {}, False
                        link_props[supportedProp.title] = class_title
                        break
    return link_props, True 
Example #25
Source File: websockets.py    From gql with MIT License 5 votes vote down vote up
def _send_query(
        self,
        document: DocumentNode,
        variable_values: Optional[Dict[str, str]] = None,
        operation_name: Optional[str] = None,
    ) -> int:
        """Send a query to the provided websocket connection.

        We use an incremented id to reference the query.

        Returns the used id for this query.
        """

        query_id = self.next_query_id
        self.next_query_id += 1

        query_str = json.dumps(
            {
                "id": str(query_id),
                "type": "start",
                "payload": {
                    "variables": variable_values or {},
                    "operationName": operation_name or "",
                    "query": print_ast(document),
                },
            }
        )

        await self._send(query_str)

        return query_id 
Example #26
Source File: aiohttp.py    From gql with MIT License 5 votes vote down vote up
def subscribe(
        self,
        document: DocumentNode,
        variable_values: Optional[Dict[str, str]] = None,
        operation_name: Optional[str] = None,
    ) -> AsyncGenerator[ExecutionResult, None]:
        raise NotImplementedError(" The HTTP transport does not support subscriptions") 
Example #27
Source File: async_transport.py    From gql with MIT License 5 votes vote down vote up
def execute(
        self,
        document: DocumentNode,
        variable_values: Optional[Dict[str, str]] = None,
        operation_name: Optional[str] = None,
    ) -> ExecutionResult:
        """Execute the provided document AST for either a remote or local GraphQL Schema.
        """
        raise NotImplementedError(
            "Any AsyncTransport subclass must implement execute method"
        )  # pragma: no cover 
Example #28
Source File: client.py    From gql with MIT License 5 votes vote down vote up
def execute(self, document: DocumentNode, *args, **kwargs) -> Dict:

        # Validate and execute on the transport
        result = await self._execute(document, *args, **kwargs)

        # Raise an error if an error is returned in the ExecutionResult object
        if result.errors:
            raise TransportQueryError(str(result.errors[0]), errors=result.errors)

        assert (
            result.data is not None
        ), "Transport returned an ExecutionResult without data or errors"

        return result.data 
Example #29
Source File: client.py    From gql with MIT License 5 votes vote down vote up
def execute_sync(self, document: DocumentNode, *args, **kwargs) -> Dict:
        with self as session:
            return session.execute(document, *args, **kwargs) 
Example #30
Source File: client.py    From gql with MIT License 5 votes vote down vote up
def execute_async(self, document: DocumentNode, *args, **kwargs) -> Dict:
        async with self as session:
            return await session.execute(document, *args, **kwargs)