async def delete(self, request: Request, petition_id: str = None): headers = request.headers if not petition_id: return sanic_json("No id provided", 404) if not headers.get("X-User", None): return sanic_json("No user in headers", 401) if request.app.TOKEN_CACHE.get(headers.get("X-User"), None): user_id = headers.get("X-User") else: return sanic_json("No active user found", 401) try: async with create_engine(dsn) as engine: async with engine.acquire() as conn: await Petition.delete(conn, petition_id) return sanic_json("Petition deleted or not found", 200) except Exception: return sanic_json("Something went wrong", 500)
async def update_user(request, id, user): """ Updates an already existing user """ if user.id != int(id): raise Unauthorized('Unauthorized access.') with scoped_session() as session: ret_user = session.query(User).filter(User.id == int(id)).first() data = request.json or {} if 'username' in data and data['username'] != ret_user.username and session.query(User).filter( User.username == data['username']).first(): return sanic_json(Response('Please use a different username.').__dict__) if 'email' in data and data['email'] != ret_user.email and session.query(User).filter( User.email == data['email']).first(): return sanic_json(Response('Please use a different email address.').__dict__) if 'password' in data: user.set_password(data['password']) session.query(User).filter(User.id == int(id)).update( {User.username: data['username'], User.email: data['email'], User.password: user.password, User.modified_at: datetime.utcnow()}) session.commit() return sanic_json(Response('User successfully updated.').__dict__) else: session.query(User).filter(User.id == int(id)).update( {User.username: data['username'], User.email: data['email'], User.modified_at: datetime.utcnow()}) session.commit() return sanic_json(Response('User successfully updated.').__dict__)
async def get(self, request: Request, petition_id: str = None): if petition_id: async with create_engine(dsn) as engine: async with engine.acquire() as conn: result = await Petition.select(conn, petition_id) # User logged in if result: return sanic_json(result, 200) else: return sanic_json(None, 400) else: async with create_engine(dsn) as engine: async with engine.acquire() as conn: result = await Petition.select(conn) # User logged in if result: return sanic_json(result, 200) else: return sanic_json(None, 400)
def add_post(self, thread, content, api=False): """Add a post to a thread""" thread = self.get_thread(thread) if thread is None: return sanic_json({"reason": "thread_does_not_exist"}, status=404) message = Message(content, self.id_counter) thread.add_message(message) self.id_counter += 1 if api: return sanic_json({"new_post": message.id, "thread": thread.id}) return redirect("/{}".format(thread.id))
async def register_user(request): """ Creates a user in the DB """ data = request.json or {} with scoped_session() as session: if session.query(User).filter(User.username == data['username']).first(): return sanic_json(Response('Please use a different username.').__dict__) if session.query(User).filter(User.email == data['email']).first(): return sanic_json(Response('Please use a different email address.').__dict__) user = User() user.from_dict(data) session.add(user) session.commit() return sanic_json(Response('User {} is successfully created.'.format(user.username)).__dict__)
async def get(self, request): data = handle_rpc(parse.parse_qs(request.query_string)) if "error" not in data: try: result = await self.send_request(self, data["method"], data["params"], data["id"]) return sanic_json(result) except OSError: print('cannot connect - is ElectrumX catching up, not running, or ' f'is {RPC_PORT} the wrong RPC port?') except Exception as e: print(f'error making request: {e}') else: return sanic_json(dead_response())
async def view_thread_api(request, thread): thread = server.get_thread(thread) if thread is None: return html(fail_page.render(reason="thread does not exist"), status=404) return sanic_json(thread.as_dict)
async def predict(q): imageURI = base64.urlsafe_b64decode( re.sub('^data:image/.+;base64,', '', q.json.get('image'))) image = cv2.imdecode(np.fromstring(imageURI, dtype=np.uint8), 0) image = image / 255 print(image.shape) _in = np.reshape(image, (784, 1)) try: if q.json.get('pretrained') > 0: console.log("Using model-v%d.npz" % q.json.get('pretrained')) _this.pretrained.load(file='model-v%d.npz' % q.json.get('pretrained')) prediction, predictions = _this.pretrained.predict(_in) except Exception as e: prediction, predictions = _this.net.predict(_in) d = { 'label': int(prediction), 'predictions': [{ 'label': int(i), 'confidence': float('%02f' % c[0]) } for i, c in enumerate(predictions)] } j = json.dumps(d) print(prediction) print(j) print(d) return sanic_json(d, dumps=json.dumps)
async def index(request): para = request_para(request) up = para.get('up') num = int(para.get('num')) txt = json.load( open(project_path() + '/ui/statics/pages.json', encoding='utf8')).get('pages') # 下一页 if up == '1' and num < len(txt) - 1: one = { 'title': txt[num + 1]['title'], 'text': txt[num + 1]['text'], 'num': str(num + 1) } pass elif up == '1' and num == len(txt) - 1: one = {'title': txt[0]['title'], 'text': txt[0]['text'], 'num': '0'} # 上一页 elif up == '0' and num > 0: one = { 'title': txt[num - 1]['title'], 'text': txt[num - 1]['text'], 'num': str(num - 1) } elif up == '0' and num == 0: one = { 'title': txt[len(txt) - 1]['title'], 'text': txt[len(txt) - 1]['text'], 'num': str(len(txt) - 1) } return sanic_json(one)
async def register(request): try: seed = request.json['seed'] except KeyError as e: return sanic_text('Missing query parameter: seed', status=400) if not 0 <= len(seed) <= 32: return sanic_text('Seed must be between 0 and 32 characters long.', status=400) # Pad with zeroes seed += '0' * (32 - len(seed)) new_agent = BaseAgent(pool, seed, seed + '-wallet', None) await new_agent.open() # Register agent on the network print('\n\nRegister agents\n\n') for ag in (trust_anchor, new_agent): print('\n\nGet Nym: ' + str(ag) + '\n\n') if not json.loads(await trust_anchor.get_nym(ag.did)): print('\n\nSend Nym: ' + str(ag) + '\n\n') await trust_anchor.send_nym(ag.did, ag.verkey) return sanic_json({ 'seed': seed, 'did': new_agent.did, 'verkey': new_agent.verkey })
async def create_corpuser(request): """Create a new CORP user.""" required_fields = ["id", "password"] utils.validate_fields(required_fields, request.json) log_request(request, True) env = Env() username = env("ADAPI_USERNAME") password = env("ADAPI_PASSWORD") auth = aiohttp.BasicAuth(login=username, password=password) url = ADAPI_REST_ENDPOINT + "?command=new-corpuser" data = { "ntid": request.json.get("id"), "userName": request.json.get("id"), "password": request.json.get("password"), } conn = aiohttp.TCPConnector( limit=request.app.config.AIOHTTP_CONN_LIMIT, ttl_dns_cache=request.app.config.AIOHTTP_DNS_TTL, verify_ssl=False, ) async with aiohttp.ClientSession(connector=conn, auth=auth) as session: async with session.post(url=url, json=data) as response: data = await response.read() res = json.loads(data.decode("utf-8")) if res.get("success") == "false": raise ApiBadRequest("Invalid CORP account request.") return sanic_json({"data": {"message": "CORP account request successful."}})
def json(message, content, status_code=200): payload = { 'message': message, 'status_code': status_code, 'content': content } return sanic_json(payload, status=status_code)
async def transcribe_with_http(request) -> HTTPResponse: """ Transcription route using HTTP. """ current_app = request.app # The audio to be transcribed audio = request.files.get('audio') # The hot-words with their boosts to be used for transcribing the audio data = request.form all_hot_words = [] if data: all_hot_words = stt_engine.add_hot_words(data) if not audio: raise InvalidUsage('Audio not provided') inference_start = perf_counter() # Running the transcription text = await current_app.loop.run_in_executor( executor, lambda: stt_engine.run(audio.body)) inference_end = perf_counter() - inference_start # Logging on the prompt the outcome of the transcription process logger.info( '----------------------------------------------------------------------------' ) logger.info(json.dumps(SttResponse(text, inference_end).__dict__)) logger.info( '----------------------------------------------------------------------------' ) # Explicitly erasing a hot-word from the language model (even though they are removed when the request is done) stt_engine.erase_hot_word(all_hot_words) return sanic_json(SttResponse(text, inference_end).__dict__)
async def clear_RequestRedirect(request): try: delete_redirect_table() code = 'ok' except: code = 'error' return sanic_json({'code': code})
async def clear_selected_ResponseRedirect(request): try: clear_config_key("Response", [], selected_Redirect_path) code = 'ok' except: code = 'error' return sanic_json({'code': code})
async def list_users(request): """ Retrieves all users from the DB""" with scoped_session() as session: users = session.query(User).all() users = [user.to_dict() for user in users] return sanic_json(users)
async def endpoint(request): # fetch the url from the request body if request.form.get("url") is None: return sanic_json({"error_message": "url not specified"}) _URL = request.form.get("url") # fetch the html content of the url page_body = requests.get(_URL) if page_body.status_code != 200: return sanic_json({"error_message": "Error fetching URL"}) soup = BeautifulSoup(page_body.content, 'html.parser') [s.extract() for s in soup(['iframe', 'script', 'img', 'style'])] body_part = "\n".join(soup.body.stripped_strings) # Write the cleaned bodypart to a txt file and save to aws S3 # Get the S3 input uri and make a input_config object # Define the S3 output uri and make a output_config object # Detect the topic model, then output the result url_hostname = str(_URL).replace('/', '').replace('.', '-') created_file_name = create_temp_file(url_hostname, body_part) bucket_resource.upload_file(Filename=created_file_name, Key=created_file_name) # Generate the s3 input and output uri now s3_input_uri = "s3://{}/{}".format(bucket_name, created_file_name) s3_output_uri = "s3://{}".format(bucket_name) input_config = {"S3Uri": s3_input_uri} output_config = {"S3Uri": s3_output_uri} response = detect_topic_model(input_config, output_config) if response["status"] == 'FAILED': return sanic_json(json.dumps(response)) output_s3uri = response["output"].replace('\/', '/') # download_key = output_s3uri[31:].replace("\/", "/") # download_local_path = output_s3uri[93:] # download_from_s3(download_key, download_local_path) return sanic_json({"output_uri": output_s3uri})
async def delete_user(request, id, user): """ Deletes an existing user from the DB""" if user.id == int(id): with scoped_session() as session: session.query(User).filter(User.id == int(id)).delete() return sanic_json(Response('User successfully removed.').__dict__) raise Unauthorized('Unauthorized access.')
async def show_all_filter(request): try: db_data = select_filter_all() code = 'ok' except: db_data = [] code = 'error' return sanic_json({'data': db_data, 'code': code})
async def show_all_redirect(request): db_data = select_redirect_all() for i in db_data: temp = '' for key, value in i['parameter'].items(): temp = temp + key + ' : ' + value + '\n' i['parameter'] = temp return sanic_json({"data": db_data})
async def post(self, request: Request): headers = request.headers if headers.get("X-User", None): access_token = headers.get("X-User") if access_token in request.app.TOKEN_CACHE: request.app.TOKEN_CACHE.pop(access_token) return sanic_json("SUCCESS", 200) else: return sanic_json("No user with this token", 201) else: return sanic_json("No user header passed", 201)
async def cancel_filter(request): try: data = config_writer(None, selected_filter_path) code = 'ok' except Exception as e: print(e) code = 'error' return sanic_json({"code": code})
async def clear_filter(request): try: delete_filter_table() code = 'ok' except Exception as e: print(e) code = 'error' return sanic_json({"code": code})
async def cdn_domain_sync_conf(request): """同步域名配置""" mongodb = request.app.M domain_db = mongodb.domain user_db = mongodb.user_profile task_info = request.json domain = task_info.get('domain', '') protocol = task_info.get('protocol', '') user_id = task_info.get('user_id', '') provider = task_info.get('provider', '') user_search_sql = {'user_id': user_id} user_doc = await user_db.find_one(user_search_sql) cdn_opt = user_doc.get('cdn_opt', '') domain_search_sql = {'domain': domain, 'protocol': protocol} domain_doc = await domain_db.find_one(domain_search_sql) create_time = domain_doc.get('create_time') create_time = datetime_to_str(create_time, _format='%Y-%m-%d %H:%M') domain_result = { 'domain': domain, 'protocol': protocol, 'user_id': user_id, 'create_time': create_time } return_code = 1 try: args = {'mongodb': mongodb, 'domain': domain, 'protocol': protocol} result = await ExternalAPI.sync_domain_conf(cdn_opt, args) for opt in cdn_opt: if opt != provider: continue if not result[opt][0]: msg = 'opt %s error %s' % (opt, result[opt][1]) logger.info(msg) assert False domain_conf = result[opt][1] domain_result.update(domain_conf) return_code = 0 except Exception as e: print(e) res = {'return_code': return_code, 'domain_conf': domain_result} return sanic_json(res)
async def add_filter(request): match = request.form['match'][0] try: describe = request.form['describe'][0] except Exception as e: print(e) describe = '' insert_filter_data(match, describe) return sanic_json({"code": "ok"})
async def delete_filter(request): delete_id = int(request.form['id'][0]) try: select_id_delete_filter(delete_id) code = 'ok' except Exception as e: print(e) code = 'error' return sanic_json({"code": code})
async def CalcSummary(request): content = request_para(request) text = content.get('text') title = content.get('title') textsummary = TextSummary() textsummary.SetText(title, text) summary = textsummary.CalcSummary() print(summary) return sanic_json(summary)
async def predict(request): predict_request = input_module.prepare_request(request) payload = predict_request.SerializeToString() res = requests.post(endpoint, headers=request_headers, data=payload) actual_result = predict_pb2.PredictResponse() actual_result.ParseFromString(res.content) outputs = output_module.decode_response(actual_result) return sanic_json({'outputs': outputs})
async def get_user(request, id, user): """ Retrieves from the DB a particular user using his `id` """ if user.id == int(id): with scoped_session() as session: user = session.query(User).filter(User.id == int(id)).first() return sanic_json(user.to_dict()) else: raise Unauthorized('Unauthorized access.')
async def get(self, request: Request, user_id: str = None): if not user_id: return sanic_json("No id specified", 404) async with create_engine(dsn) as engine: async with engine.acquire() as conn: result = await User.select(conn, user_id) # User logged in if result: result.pop("password") result["id"] = str(result["id"]) return sanic_json(result, 200) else: return sanic_json({}, 400)