def test_get_place_2(self): response = self.client.get(self.get_url(self.place2.id)) self.assertEqual(response.status_code, status.HTTP_200_OK) payload_dict = PlaceOutSerializer(**response.json()).dict() self.assertEqual(PlaceOutSerializer(**jsonable_encoder(self.place2)).dict(), payload_dict)
async def add_new_car(car: CarSchema = Body(...)): car = jsonable_encoder(car) new_car = await car_add(car) return ResponseModel(new_car, "Car created successfully.")
def test_bytes_encoder(): data_before = {"inp": {"nest": b"bytes"}} data_after = {"inp": {"nest": "bytes"}} assert json.loads(json.dumps(jsonable_encoder(data_before))) == data_after
def encode(self) -> str: dic = jsonable_encoder(self) return dumps(dic, ensure_ascii=False)
def create_user_data(user: UserIn): user = jsonable_encoder(user) new_user = create_user(user) return new_user
async def add_reading(readings: FullReading = Body(...)): reading = jsonable_encoder(readings) new_reading = await add_mood(reading) return ResponseModel(new_reading, "Reading Added successfully")
async def autogenerate_search(word: str): """Function to generate a set of extracts from a single user-entered term using the Wikipedia API""" data = autogenerate(word) data_json = jsonable_encoder(data) return data_json
async def station_live_data(): wx = weather.get_wx_latest(sid) data = {} data["wx"] = wx json_compatible_item_data = jsonable_encoder(data) return JSONResponse(content=json_compatible_item_data)
async def weather_soundings_images(sid: str): img = weather.get_image(sid) json_compatible_item_data = jsonable_encoder(img.decode("unicode_escape")) return JSONResponse(content=json_compatible_item_data)
async def aprs_igate_range(time_int: str): range_aprs = aprs.create_range_aprs(time_int) data = {} data["range_aprs"] = json.loads(range_aprs) json_compatible_item_data = jsonable_encoder(data) return JSONResponse(content=json_compatible_item_data)
async def photos_galleries(): rows = flickr.get_gal_rows(5) data = {} data["rows"] = rows json_compatible_item_data = jsonable_encoder(data) return JSONResponse(content=json_compatible_item_data)
def update_item(id: str, item: Item): json_compatible_item_data = jsonable_encoder(item) return JSONResponse(content=json_compatible_item_data)
async def root(): json_compatible_item_data = jsonable_encoder(lamp_state) return JSONResponse(content=json_compatible_item_data)
async def post_rate(b: rate = Body(...)): b = jsonable_encoder(b) await db["count"].insert_one(b) return JSONResponse(status_code=status.HTTP_201_CREATED)
async def admin_signup(admin: AdminModel = Body(...)): # TODO: Perform validation to check if user exists. admin.password = hash_helper.encrypt(admin.password) new_admin = await add_admin(jsonable_encoder(admin)) return new_admin
async def aprs_latest(): last = aprs.get_aprs_latest() data = {} data["last"] = last json_compatible_item_data = jsonable_encoder(data) return JSONResponse(content=json_compatible_item_data)
def obj_in_to_db_obj(self, obj_in: Any): obj_in_data = jsonable_encoder(obj_in) user_id = obj_in_data.pop("current_user_id") return self.model(**obj_in_data, created_by_id=user_id, updated_by_id=user_id)
async def _open_connection(websocket: WebSocket, object_id: int): await websocket.accept() alerts = await _alerts_belonging_to_object(object_id) return await websocket.send_json(jsonable_encoder(alerts))
def test_cli_user_create_with_debug_and_json_output( self, request, monkeypatch) -> None: # reset global config singleton config._CONFIG = None fixture_path = fixtures_path / "isolated_config_dir" print(fixture_path) runner = CliRunner() with runner.isolated_filesystem() as isolated_dir: # Populate filesystem folders isolated_base_dir = isolated_dir isolated_xdg_config_home_dir = os.path.join( isolated_dir, ".config") isolated_ultron_config_dir = os.path.join( isolated_xdg_config_home_dir, "ultron8") isolated_ultron_config_path = os.path.join( isolated_ultron_config_dir, "smart.yaml") # create base dirs os.makedirs(isolated_xdg_config_home_dir) # request.cls.home = isolated_base_dir # request.cls.xdg_config_home = isolated_xdg_config_home_dir # request.cls.ultron_config_dir = isolated_ultron_config_dir # request.cls.ultron_config_path = isolated_ultron_config_path # monkeypatch env vars to trick intgr tests into running only in isolated file system monkeypatch.setenv("HOME", isolated_base_dir) monkeypatch.setenv("XDG_CONFIG_HOME", isolated_xdg_config_home_dir) monkeypatch.setenv("ULTRON8DIR", isolated_ultron_config_dir) # Copy the project fixture into the isolated filesystem dir. shutil.copytree(fixture_path, isolated_ultron_config_dir) # Grab access token r = get_superuser_jwt_request() tokens = r.json() a_token = tokens["access_token"] # create factory user factory_user = _MakeRandomNormalUserFactory() example_payload_json = jsonable_encoder(factory_user) path_to_payload = os.path.join(isolated_base_dir, "test_payload.json") # write factory user data to disk with open(path_to_payload, "w") as outfile: json.dump(example_payload_json, outfile) example_data = """ clusters_path: clusters/ cache_path: cache/ workspace_path: workspace/ templates_path: templates/ flags: debug: 0 verbose: 0 keep: 0 stderr: 0 repeat: 1 clusters: instances: local: url: http://localhost:11267 token: '{}' """.format(a_token) # overwrite smart.yaml w/ config that has auth token in it. helper_write_yaml_to_disk(example_data, isolated_ultron_config_path) # Monkeypatch a helper method onto the runner to make running commands # easier. runner.run = lambda command: runner.invoke(cli, command.split()) # And another for checkout the text output by the command. runner.output_of = lambda command: runner.run(command).output # Run click test client result = runner.invoke( cli, [ "--debug", "user", "--cluster", "local", "create", "--payload", path_to_payload, ], ) # verify results assert result.exit_code == 0
def cancel(): return JSONResponse(status_code=200, content=jsonable_encoder(SignProcessHandler.init()))
def add_book(book: Book = Body(...)) -> Dict[str, Union[UUID4, Any]]: # Might later change it to form input when the frontend is ready. return insert_book(jsonable_encoder(book))
def handle_common_error(request: Request, exc: CommonError): """ Handles a `CommonError` raised """ return JSONResponse(status_code=exc.status, content=jsonable_encoder(exc.content()))
async def add_student_data(student:StudentSchema=Body(...)): student = jsonable_encoder(student) new_student = await add_student(student) return ResponseModel(new_student,"success")
async def mock(): return jsonable_encoder(dict(code=200, msg="success", data=Mock.data()))
async def create(self, obj_in: CreateSchemaType) -> ModelType: obj_in_data = jsonable_encoder(obj_in) db_obj = await self.model.create(**obj_in_data) return db_obj
async def fetchTreeModel(epic: str = Query(default="", description="当前自动化史诗唯一标识,如KXHNEW")): if epic == "": return jsonable_encoder(dict(code=100, msg="非法请求参数", data="请指定非空的当前自动化史诗唯一标识epic!")) else: result = mongo.find(tbname="testcase", filter_json={"Epic": str(epic).strip()}, projection_json={"_id": 1, "Pid": 1, "Project": 1, "Sid": 1, "Scenario": 1, "Tid": 1, "Title": 1}, sort_json={"Pid": 1, "Sid": 1, "Tid": 1, "CreateTime": 1}) origin = [] df = pd.DataFrame(data=result).drop_duplicates(keep="last").fillna("") if df.shape[0] == 0: return jsonable_encoder(dict(code=201, msg=f"当前史诗{epic}无任何数据,请先进行初始化!")) df["_id"] = df["_id"].astype(str) df["Pid"] = df["Pid"].astype(object) df["Sid"] = df["Sid"].astype(object) df["Tid"] = df["Tid"].astype(object) projects_df = df[['Pid', 'Project']].drop_duplicates().reset_index(drop=True).set_index(keys=["Pid"], drop=True) projects_index = projects_df.index.values.tolist() projects_values = projects_df['Project'].values.tolist() projects_dict = dict(zip(projects_index, projects_values)) for index, project in projects_dict.items(): origin.append(dict(id=index, label=project, showInput=False, layer=1, children=[])) tree_data_list = [] for origin_dict in origin: if origin_dict.get('id') < 0: return jsonable_encoder( dict(code=201, msg="检测到非法的一级节点序号(其必须为自然数)", data=dict(pid=origin_dict.get('id'), pname=origin_dict.get('label')))) pid_df = df[df["Pid"] == origin_dict.get('id')] pid_count = pid_df.shape[0] if pid_count == 1: tree_data_list.append(dict(layer1_id=int(origin_dict.get('id')), layer1_label=origin_dict.get('label'), layer2_id=-1, layer2_label="", layer3_data=[])) else: filter_pid_df = pid_df[pid_df['Sid'] != -1] for key1, value1 in filter_pid_df.groupby(by=["Pid", "Project", "Sid", "Scenario"], sort=True): sid_count = value1.shape[0] if sid_count == 1: tree_data_list.append(dict(layer1_id=int(origin_dict.get('id')), layer1_label=origin_dict.get('label'), layer2_id=int(key1[2]), layer2_label=key1[3], layer3_data=[])) else: filter_sid_df = value1[value1["Tid"] != -1] tid_df = filter_sid_df.loc[:, ['_id', 'Tid', "Title"]] tid_df['showInput'] = False tid_df['layer'] = 3 tid_df = tid_df.reindex(columns=["Tid", "Title", "showInput", "layer", "_id"]).sort_values( by=["Tid"], ascending=True).reset_index(drop=True) tid_data = tid_df.rename(columns={"Tid": "id", "Title": "label", "_id": "case"}).to_dict( orient='records') tree_data_list.append(dict(layer1_id=int(origin_dict.get('id')), layer1_label=origin_dict.get('label'), layer2_id=int(key1[2]), layer2_label=key1[3], layer3_data=tid_data)) for origin_index, origin_dict in enumerate(origin): layer2_list = [] for tree_data in tree_data_list: if tree_data['layer1_id'] == origin_dict['id'] and tree_data['layer1_label'] == origin_dict['label']: if tree_data['layer2_id'] < 0: layer2_list = [] break else: layer2_list.append( dict(id=int(tree_data['layer2_id']), label=tree_data['layer2_label'], showInput=False, layer=2, children=tree_data['layer3_data'])) origin.pop(origin_index) origin_dict['children'] = layer2_list origin.insert(origin_index, origin_dict) return jsonable_encoder(dict(code=200, msg="测试用例层级渲染数据获取成功", data=origin))
async def get_job(id: int): json_out = {} job_orm = cur_session.query(JobsOrm).filter(JobsOrm.id==id).first() jobMod = JobsModel.from_orm(job_orm) json_out['data'] = jobMod return jsonable_encoder(json_out)
async def saveCaseData(testcases: List[TestCaseModel], epic: str = Query(default="", description="当前自动化史诗唯一标识,如KXHNEW"), opt: int = Query(default=None, description="用例数据操作标识(1-新增,2-修改)")): if epic == "": return jsonable_encoder(dict(code=100, msg="非法请求参数", data="请指定非空的当前自动化史诗唯一标识epic!")) if opt not in [1, 2]: return jsonable_encoder(dict(code=100, msg="非法请求参数", data="请指定合法的用例数据操作标识,当前仅支持(1-新增,2-修改)!")) if opt == 1: for testcase in testcases: testcase_dict = testcase.dict() testcase_dict["Epic"] = str(epic).strip().upper() testcase_dict["CreateTime"] = str(datetime.datetime.now()) testcase_dict["UpdateTime"] = "" pid = testcase_dict['Pid'] pname = testcase_dict['Project'] sid = testcase_dict['Sid'] sname = testcase_dict['Scenario'] tid = testcase_dict['Tid'] if pid >= 0 and sid == -1 and tid == -1: exist = mongo.find_one(tbname="testcase", filter_json={"Epic": str(epic).strip(), "Pid": pid, "Sid": -1, "Tid": -1}) if exist is not None: return jsonable_encoder( dict(code=201, msg="当前一级节点已存在,不允许重复新增当前一级节点!", data=dict(pid=pid, pname=pname))) else: mongo.update_many(tbname="testcase", filter_json={"Epic": str(epic).strip(), "Pid": pid}, update_json={"$set": testcase_dict}, upsert=True) elif pid >= 0 and sid >= 0 and tid == -1: exist = mongo.find_one(tbname="testcase", filter_json={"Epic": str(epic).strip(), "Pid": pid, "Sid": sid, "Tid": -1}) if exist is not None: return jsonable_encoder( dict(code=201, msg="当前二级节点已存在,不允许重复新增当前二级节点!", data=dict(pid=pid, pname=pname, sid=sid, sname=sname))) else: mongo.update_many(tbname="testcase", filter_json={"Epic": str(epic).strip(), "Pid": pid, "Sid": sid}, update_json={"$set": testcase_dict}, upsert=True) # mongo.delete_many(tbname="testcase", delete_json={"Epic": str(epic).strip(), # "Pid": pid, "Sid": -1}) elif pid >= 0 and sid >= 0 and tid >= 0: mongo.update_many(tbname="testcase", filter_json={"Epic": str(epic).strip(), "Pid": pid, "Sid": sid, "Tid": tid}, update_json={"$set": testcase_dict}, upsert=True) # mongo.delete_many(tbname="testcase", delete_json={"Epic": str(epic).strip(), # "Pid": pid, "Sid": sid, "Tid": -1}) else: return jsonable_encoder(dict(code=101, msg="非法测试用例层级序号", data=dict(pid=pid, sid=sid, tid=tid))) return jsonable_encoder( dict(code=200, msg="测试用例数据保存成功")) else: for testcase in testcases: testcase_dict = testcase.dict() testcase_dict["Epic"] = str(epic).strip().upper() testcase_dict["UpdateTime"] = str(datetime.datetime.now()) pid = testcase_dict['Pid'] pname = testcase_dict['Project'] sid = testcase_dict['Sid'] sname = testcase_dict['Scenario'] tid = testcase_dict['Tid'] tname = testcase_dict['Title'] if pid >= 0 and sid == -1 and tid == -1: modify_flag = mongo.update_many(tbname="testcase", filter_json={"Epic": str(epic).strip(), "Pid": pid, "Sid": -1, "Tid": -1}, update_json={"$set": testcase_dict}, upsert=False) if modify_flag == 0: return jsonable_encoder( dict(code=201, msg="当前一级节点并不存在,修改操作无效!", data=dict(pid=pid, pname=pname))) elif pid >= 0 and sid >= 0 and tid == -1: modify_flag = mongo.update_many(tbname="testcase", filter_json={"Epic": str(epic).strip(), "Pid": pid, "Sid": sid, "Tid": -1}, update_json={"$set": testcase_dict}, upsert=False) if modify_flag == 0: return jsonable_encoder( dict(code=201, msg="当前二级节点并不存在,修改操作无效!", data=dict(pid=pid, pname=pname, sid=sid, sname=sname))) # mongo.delete_many(tbname="testcase", delete_json={"Epic": str(epic).strip(), # "Pid": pid, "Sid": -1}) elif pid >= 0 and sid >= 0 and tid >= 0: modify_flag = mongo.update_many(tbname="testcase", filter_json={"Epic": str(epic).strip(), "Pid": pid, "Sid": sid, "Tid": tid}, update_json={"$set": testcase_dict}, upsert=False) if modify_flag == 0: return jsonable_encoder( dict(code=201, msg="当前三级节点并不存在,修改操作无效!", data=dict(pid=pid, pname=pname, sid=sid, sname=sname, tid=tid, tname=tname))) # mongo.delete_many(tbname="testcase", delete_json={"Epic": str(epic).strip(), # "Pid": pid, "Sid": sid, "Tid": -1}) else: return jsonable_encoder(dict(code=101, msg="非法测试用例层级序号", data=dict(pid=pid, sid=sid, tid=tid))) return jsonable_encoder( dict(code=200, msg="测试用例数据修改成功"))
def _render_single_output(self, streamlit: st, output_data: BaseModel) -> None: try: if has_output_ui_renderer(output_data): if function_has_named_arg(output_data.render_output_ui, "input"): # type: ignore # render method also requests the input data output_data.render_output_ui( streamlit, input=self._input_data) # type: ignore else: output_data.render_output_ui(streamlit) # type: ignore return except Exception: # Use default auto-generation methods if the custom rendering throws an exception logger.exception( "Failed to execute custom render_output_ui function. Using auto-generation instead" ) model_schema = output_data.schema(by_alias=False) model_properties = model_schema.get("properties") definitions = model_schema.get("definitions") if model_properties: for property_key in output_data.__dict__: property_schema = model_properties.get(property_key) if not property_schema.get("title"): # Set property key as fallback title property_schema["title"] = property_key output_property_value = output_data.__dict__[property_key] if has_output_ui_renderer(output_property_value): output_property_value.render_output_ui( streamlit) # type: ignore continue if isinstance(output_property_value, BaseModel): # Render output recursivly streamlit.subheader(property_schema.get("title")) if property_schema.get("description"): streamlit.markdown(property_schema.get("description")) self._render_single_output(streamlit, output_property_value) continue if property_schema: if schema_utils.is_single_file_property(property_schema): self._render_single_file_property( streamlit, property_schema, output_property_value) continue if (schema_utils.is_single_string_property(property_schema) or schema_utils.is_single_number_property( property_schema) or schema_utils.is_single_datetime_property( property_schema) or schema_utils.is_single_boolean_property( property_schema)): self._render_single_text_property( streamlit, property_schema, output_property_value) continue if definitions and schema_utils.is_single_enum_property( property_schema, definitions): self._render_single_text_property( streamlit, property_schema, output_property_value.value) continue # TODO: render dict as table self._render_single_complex_property( streamlit, property_schema, output_property_value) return # Display single field in code block: # if len(output_data.__dict__) == 1: # value = next(iter(output_data.__dict__.values())) # if type(value) in (int, float, str): # # Should not be a complex object (with __dict__) -> should be a primitive # # hasattr(output_data.__dict__[0], '__dict__') # streamlit.subheader("This is a test:") # streamlit.code(value, language="plain") # return # Fallback to json output streamlit.json(jsonable_encoder(output_data))
async def add_comment_post_data(comment_details: CommentSchema = Body(...), current_user=Depends( auth_handler.auth_wrapper)): comment_details = jsonable_encoder(comment_details) new_comment = await add_comment(current_user, comment_details) return ResponseModel(new_comment, "Comment added successfully.")