def put(self, game_id=None): result = {} abort_if_game_doesnt_exist(game_id) if request.headers['Content-Type'] == 'application/json': data = request.get_json() if "guess" not in data: result[ 'error'] = "I can't find your guess -- Have you set your guess?" return Response(json.dumps(result), status=400, mimetype='application/json') guess = data['guess'] result['guess'] = guess result['result'] = games[game_id].make_guess_dict(guess) return Response(json.dumps(result), status=201, mimetype='application/json') result[ 'error'] = "I don't understand the request -- is the Content-Type correct?" return Response(json.dumps(result), status=400, mimetype='application/json')
def get_classification_by_pid(pid): c = Classification.get_by_pid(pid) kinds = [k['kind'] for k in c] if c: return json.dumps(kinds) else: return {"error": "error"}, 400
def get_all_classification(): c = Classification.get_all() kinds = [k['kind'] for k in c] if c: return json.dumps(kinds) else: return {"error": "error"}, 400
def get(self, user_id, image_id, super_id): data = db.session.query(Mask).filter(Mask.user_id == user_id, Mask.image_id == image_id, Mask.super_id == super_id) if len(data.all()) == 0: data = "Mask doesn\'t exist" j_data = jsonify(data) else: data = data.all()[0].to_dict() img = Image.query.get(image_id).to_dict() first_mask = segment_image(img['path'], data['ratio'], data['kernel'], data['dist']) mask = json.dumps(first_mask.tolist()) size = img['size'] boundaries = get_boundaries(first_mask, int(size[0]), int(size[1])) send_data = { 'id': data['id'], 'mask': mask, 'boundaries': boundaries, 'ratio': data['ratio'], 'dist': data['dist'], 'kernel': data['kernel'] } j_data = jsonify(send_data) return j_data pass
def rate(input): global headers inputs = input.split(" ")[1:] payload = { "rating": inputs[4], "professor": inputs[0], "module": inputs[1], "year": inputs[2], "semester": inputs[3] } if headers is not None: res = requests.post(url + rate_url, json.dumps(payload), headers=headers) else: print("Error, you are not logged in") return if res.status_code is not 200: print("Error during rating submission") return else: print("Rating Submitted Correctly")
def get_all_transactions(): results = Transaction.query.all() if results: return json.dumps(Transaction.serialize_list(results), default=datetime_handler) else: return {"error", "no transaction"}, 400
def get_products_byclassification(kind): print(kind) p_list = Product.get_by_classification(kind) for p in p_list: p['kind'] = Classification.get_by_pid_list(p['pid']) if p_list: return json.dumps(p_list) else: return {"error": "error"}, 400
def get_mostgivenproducts(pid): results = Transaction.most_given_products(pid) print(results, len(results), len(results) > 0) if ((len(results)) > 0): print("true") return json.dumps(results, default=decimal_handler) else: print("false") return {"error", "no transaction"}
def get_all_products(): p_list = Product.get_all() print(p_list) for p in p_list: p['kind'] = Classification.get_by_pid_list(p['pid']) if p_list: return json.dumps(p_list) else: return {"error": "error"}, 400
def post(self): game_id = ''.join( random.choices(string.ascii_uppercase + string.digits, k=4)) games[game_id] = Mastermind() result = {'game': game_id} return Response(json.dumps(result), status=201, mimetype='application/json')
def customerinfo_home_business(ckind, cid): c = None if ckind == "home": c = Home.getbycustomerid(cid) elif ckind == "business": c = Business.getbycustomerid(cid) print(c) if c: return json.dumps(c.serialize()) else: return {"error": ckind + " " + cid + " not found"}, 400
def get_recipe_reviews_with_id(): if request.method == 'POST': content = request.get_json() recipe_id = content["recipe_id"] try: result = sqlUtil.GetAllRecipeReviewById(recipe_id) except: return "False" results = {} results["reviews"] = result return json.dumps(results) # all recipe info as json
def get_boundaries(segments_quick, width, height): blank_image = np.zeros((height, width, 3), np.uint8) blank_image[:] = (255, 255, 255) # (B, G, R) marked_bound = mark_boundaries(blank_image, segments_quick, color=(0, 0, 0)).astype(int); # marked_bound = find_boundaries(segments_quick, connectivity=1, mode="thick", background=0).astype(np.uint8) # array_data_type = marked_bound.dtype.name # array_shape = marked_bound.shape # as_bytes = marked_bound.tobytes() serialized = json.dumps(marked_bound.tolist()) return serialized
def get(self, game_id=None): abort_if_game_doesnt_exist(game_id) result = {} for k in games[game_id].history: result[k + 1] = { 'guess': games[game_id].history[k], 'result': games[game_id].check_guess_dict(games[game_id].history[k]), } return Response(json.dumps(result), status=200, mimetype='application/json')
def get(self): parser = parse_get.parse_args() action = parser.get("action") u_token = parser.get("u_token") if action == "active": id = cache.get(u_token) if id: user = UserModel.query.get(id) user.is_active = True user.save() cache.delete(u_token) data = {"msg": "激活成功","my":"gg"} ret = json.dumps(data, ensure_ascii=False) print(ret) return ret else: data ={"msg": "激活失败"} ret = json.dumps(data, ensure_ascii=False) print (ret) return ret else: return {"msg": "功能正在开发中"}
def register(): username = input("Username: "******"Password: "******"Email: ") payload = {"Username": username, "Password": password, "Email": email} res = requests.post(url + register_url, json.dumps(payload)) if res.status_code is not 200: print("Error on registering, try again") return else: print("Registration successful")
def extract_from_json(json_data): image = int(json_data['id']) sup = int(json_data['super']) ratio = float(json_data['ratio']) dist = int(json_data['dist']) kernel = int(json_data['kernel']) img = Image.query.get(image).to_dict() first_mask = segment_image(img['path'], ratio, kernel, dist) mask = json.dumps(first_mask.tolist()) size = img['size'] boundaries = get_boundaries(first_mask, int(size[0]), int(size[1])) return [image, sup, ratio, dist, kernel, mask, boundaries]
def login(): username = input("Username: "******"Password: "******"Username": username, "Password": password} response = requests.post(url + login_url, json.dumps(payload)) content = response.content.decode("utf-8") if response.status_code == 401: print("Login Failed") return global def_prompt def_prompt = username + ": " global headers headers = {'Authorization': content}
def HandleViewRequest(request): is_get, bad_response = GET_req_checker(request) if not is_get: return bad_response if not Token.objects.get(key=request.headers['Authorization']): response = HttpResponse() response['Content-Type'] = 'application/text' response.status_code = 401 response.reason_phrase = 'Not Logged in' return response return_list = [] for i in Professor.objects.all(): total = 0 counter_final = 0 try: for j in Rating.objects.filter(professor_code=i): total += j.rating counter_final += 1 except ObjectDoesNotExist: continue if counter_final == 0: continue item = { "name": i.name, "code": i.professor_code, "rating": total / counter_final } return_list.append(item) payload = {"professors": return_list} response = HttpResponse(json.dumps(payload)) response['Content-Type'] = 'application/json' response.status_code = 200 response.reason_phrase = 'OK' return response
def HandleAverageRequest(request, code): is_get, bad_response = GET_req_checker(request) if not is_get: return bad_response if not Token.objects.get(key=request.headers['Authorization']): response = HttpResponse() response['Content-Type'] = 'application/text' response.status_code = 401 response.reason_phrase = 'Not Logged in' return response response = HttpResponse() try: prof_code = code[0:3] mode_code = code[3:6] professor = Professor.objects.get(professor_code=prof_code) professor_rating = Rating.objects.filter(professor_code=professor) average = 0 total = 0 for i in professor_rating: if i.module.module.module_code == mode_code: average += i.rating total += 1 payload = { "name": professor.name, "code": professor.professor_code, "rating": average / total } response = HttpResponse(json.dumps(payload)) response['Content-Type'] = 'application/json' response.status_code = 200 response.reason_phrase = 'OK' except ObjectDoesNotExist: response['Content-Type'] = 'application/text' response.status_code = 404 response.reason_phrase = 'Professor not found' return response
def encrypt_keystr(self): '''加密licdata''' global aes_key, aes_iv if 'lickey' in self.data: return # 随机字符串, 防止一样的注册码 self.data['random'] = str(uuid.uuid4()) try: obj = AES.new(aes_key, AES.MODE_CBC, aes_iv) lictxt = json.dumps(self.data, ensure_ascii=False) if len(lictxt) % 16: padlen = 16 - len(lictxt) % 16 lictxt = lictxt + ''.zfill(padlen) keydata = obj.encrypt(lictxt) self.data['lickey'] = base64.b64encode(keydata) except Exception as err: print (str(err))
def test_get_matrix_servers(requests_responses: responses.RequestsMock): server_list_content = { "active_servers": ["http://server1", "http://server2"], "all_servers": ["http://server3", "http://server4"], } requests_responses.add(responses.GET, "http://server-list", json.dumps(server_list_content)) active_servers_default = get_matrix_servers("http://server-list") active_servers_explicit = get_matrix_servers( "http://server-list", server_list_type=ServerListType.ACTIVE_SERVERS) assert (active_servers_default == active_servers_explicit == server_list_content["active_servers"]) all_servers = get_matrix_servers( "http://server-list", server_list_type=ServerListType.ALL_SERVERS) assert all_servers == server_list_content["all_servers"]
def get_search_result(): if request.method == 'POST': content = request.get_json() username = content["username"] password = content["password"] keywords = content["keywords"] categories = content["categories"] if str(username).strip(): # Check for Login try: user = sqlUtil.GetUser(username) if user.password == password: pass else: return "False" except: return "False" else: return "False" arr = [] if (categories): catListForSql = [] for val in keywords: catListForSql.append("%" + val + "%") recipeList = sqlUtil.GetRecipeIdForCategory(catListForSql) for recipeId2 in recipeList: recipe = sqlUtil.GetModelWithID("Recipe", recipeId2.get("Recipe_id")) arr.append(recipe.to_json(sqlUtil.GetRecipeIngList(recipe.id), sqlUtil.GetRecipeCatList(recipe.id))) else: ingListForSql = [] for val in keywords: ingListForSql.append("%" + val + "%") recipeList = sqlUtil.GetRecipeId(ingListForSql) for recipeId in recipeList: recipe = sqlUtil.GetModelWithID("Recipe", recipeId.get("Recipe_id")) arr.append(recipe.to_json(sqlUtil.GetRecipeIngList(recipe.id), sqlUtil.GetRecipeCatList(recipe.id))) print(arr) recipes ={} recipes["recipes"] = arr return json.dumps(recipes) # verilen keywordlere bağlı recipeler dönülecek
def HandleListRequest(request): is_get, bad_response = GET_req_checker(request) if not is_get: return bad_response if not Token.objects.get(key=request.headers['Authorization']): response = HttpResponse() response['Content-Type'] = 'application/text' response.status_code = 401 response.reason_phrase = 'Not Logged in' return HttpResponse(response) return_list = [] for i in ModuleInstance.objects.all(): prof_list = [] for prof in i.professor_names.all(): prof_list.append({ "name": prof.name, "professor_code": prof.professor_code }) item = { "module_code": i.module.module_code, "module_name": i.module.module_name, "module_semester": i.module_semester, "professors": prof_list, "academic_year": i.academic_year } return_list.append(item) payload = {"modules": return_list} response = HttpResponse(json.dumps(payload)) response['Content-Type'] = 'application/json' response.status_code = 200 response.reason_phrase = 'OK' return response
def storedata(): # POST request if request.method == 'POST': print('Incoming..') print(request.get_json()) # parse as JSON for data in request.get_json(): title = data['title'] start = data['start'] print(title) response = table.put_item(Item={ 'title': title, 'start': start, }) print("Put item succeeded") print(json.dumps(response, indent=4)) return 'OK', 200 # GET request else: message = {'greeting': 'Hello from Flask!'} return jsonify(message) # serialize and use JSON headers
def res_json(data): return Response(json.dumps(data, default=str), mimetype='application/json')
def get_all_salespersons(): results = Salesperson.get_all() if results and len(results) > 0: return json.dumps(results) else: return {"error", "no transaction"}, 400
def get_all_sales_of_region(): results = Region.get_region_sales() if results: return json.dumps(results, default=decimal_handler) else: return {"error", "no transaction"}, 400
def all_region(): results = Region.query.all() if results: return json.dumps(serialize_list(results)) else: return {"error", "no transaction"}, 400
def region_salesvolume(): results = Region.region_salesvolume() if results: return json.dumps(Region.serialize_list(results)) else: return {"error", "no transaction"}, 400