code stringlengths 1 18.2k |
|---|
except Exception as e: log.error("please use -i <job_id with an integer>") valid = False if not valid: log.error(usage) sys.exit(1) if verbose: log.info(( "creating client user={} url={} job_id={} " "ca_dir={} cert_file={} key_file={}").format( user, url, job_id, ca_dir, cert_file, key_file)) client = AIClient( user=us... |
SUCCESS: if debug: log.info(("got a job response={}") .format( response["data"])) elif response["status"] == FAILED: log.error(("job failed with error='{}' with response={}") .format( response["error"], response["data"])) sys.exit(1) elif response["status"] == ERROR: if "missing " in response["error"]: log.error(("Did ... |
able to log in " "with an error='{}' with response={}") .format( response["error"], response["data"])) sys.exit(1) job_data = response["data"] if len(job_data) == 0: log.error(("Did not find a job with id={} for user={}") .format( job_id, user)) sys.exit(1) job_id = job_data.get("id", None) job_status = job_data.get("s... |
def get_molo_comments(parser, token): """ Get a limited set of comments for a given object. Defaults to a limit of 5. Setting the limit to -1 disables limiting. Set the amount of comments to usage: {% get_molo_comments for object as variable_name %} {% get_molo_comments for object as variable_name limit amount %} {% ge... |
keywords = token.contents.split() if len(keywords) != 5 and len(keywords) != 7 and len(keywords) != 9: raise template.TemplateSyntaxError( "'%s' tag takes exactly 2,4 or 6 arguments" % (keywords[0],)) if keywords[1] != 'for': raise template.TemplateSyntaxError( "first argument to '%s' tag must be 'for'" % (keywords[0],... |
keywords[5] != 'limit': raise template.TemplateSyntaxError( "third argument to '%s' tag must be 'limit'" % (keywords[0],)) if len(keywords) == 7: return GetMoloCommentsNode(keywords[2], keywords[4], keywords[6]) if len(keywords) > 7 and keywords[7] != 'child_limit': raise template.TemplateSyntaxError( "third argument t... |
def get_comments_content_object(parser, token): """ Get a limited set of comments for a given object. Defaults to a limit of 5. Setting the limit to -1 disables limiting. usage: {% get_comments_content_object for form_object as variable_name %} """ keywords = token.contents.split() if len(keywords) != 5: raise template... |
must be 'for'" % (keywords[0],)) if keywords[3] != 'as': raise template.TemplateSyntaxError( "first argument to '%s' tag must be 'as'" % (keywords[0],)) return GetCommentsContentObject(keywords[2], keywords[4]) |
def report(request, comment_id): """ Flags a comment on GET. Redirects to whatever is provided in request.REQUEST['next']. """ comment = get_object_or_404( django_comments.get_model(), pk=comment_id, site__pk=settings.SITE_ID) if comment.parent is not None: messages.info(request, _('Reporting comment replies is not all... |
def post_molo_comment(request, next=None, using=None): """ Allows for posting of a Molo Comment, this allows comments to be set with the "user_name" as "Anonymous" """ data = request.POST.copy() if 'submit_anonymously' in data: data['name'] = 'Anonymous' # replace with our changed POST data # ensure we always set an em... |
def build_ai_client_from_env( verbose=ANTINEX_CLIENT_VERBOSE, debug=ANTINEX_CLIENT_DEBUG, ca_dir=None, cert_file=None, key_file=None): """build_ai_client_from_env Use environment variables to build a client :param verbose: verbose logging :param debug: debug internal client calls :param ca_dir: optional path to CA bund... |
ca_dir use_cert_file = cert_file use_key_file = key_file if ANTINEX_CA_FILE or ANTINEX_KEY_FILE or ANTINEX_CERT_FILE: use_ca_dir = ANTINEX_CA_FILE use_cert_file = ANTINEX_CERT_FILE use_key_file = ANTINEX_KEY_FILE log.info(( "creating env client user={} url={} " "ca={} cert={} key={}").format( ANTINEX_USER, ANTINEX_URL,... |
cert_file=use_cert_file, key_file=use_key_file, verbose=verbose, debug=debug) |
def train_new_deep_neural_network(): """train_new_deep_neural_network Train a new deep neural network and store the results as a new: ``MLJob`` and ``MLJobResult`` database records. """ parser = argparse.ArgumentParser( description=( "Python client to Train a Deep Neural Network " "with AntiNex Django Rest Framework"))... |
required=False, dest="url") parser.add_argument( "-f", help="file to use default ./examples/test-keras-dnn.json", required=False, dest="datafile") parser.add_argument( "-b", help=( "optional - path to CA bundle directory for " "client encryption over HTTP"), required=False, dest="ca_dir") parser.add_argument( "-c", hel... |
parser.add_argument( "-s", help="silent", required=False, dest="silent", action="store_true") parser.add_argument( "-d", help="debug", required=False, dest="debug", action="store_true") args = parser.parse_args() user = ev( "API_USER", "user-not-set") password = ev( "API_PASSWORD", "password-not-set") email = ev( "API_... |
bool(str(ev( "API_DEBUG", "false")).lower() == "true") if args.user: user = args.user if args.password: password = args.password if args.email: email = args.email if args.url: url = args.url if args.datafile: datafile = args.datafile if args.ca_dir: ca_dir = args.ca_dir if args.cert_file: cert_file = args.cert_file if ... |
" "-p <password> " "-a <AntiNex URL http://localhost:8010> " "-f <path to json file> " "-b <optional - path to CA bundle directory> " "-c <optional - path to x509 ssl certificate file> " "-k <optional - path to x509 ssl key file>") valid = True if not user or user == "user-not-set": log.error("missing user") valid = Fa... |
"password-not-set": log.error("missing password") valid = False if not datafile or datafile == "datafile-not-set": log.error("missing datafile") valid = False else: if not os.path.exists(datafile): log.error(("did not find datafile={} on disk") .format( datafile)) valid = False if not valid: log.error(usage) sys.exit(1... |
cert_file=cert_file, key_file=key_file, verbose=verbose, debug=debug) if verbose: log.info(("loading request in datafile={}") .format( datafile)) req_body = None with open(datafile, "r") as f: req_body = json.loads(f.read()) if verbose: log.info("running job") job_was_started = False response = client.run_job( body=req... |
log.error(("job had an error='{}' with response={}") .format( response["error"], response["data"])) elif response["status"] == LOGIN_FAILED: log.error(("job reported user was not able to log in " "with an error='{}' with response={}") .format( response["error"], response["data"])) if not job_was_started: sys.exit(1) if... |
job dictionary in response data={}") .format( response["data"])) sys.exit(1) if not result_data: log.error(("missing results dictionary in response data={}") .format( response["data"])) sys.exit(1) job_id = job_data.get("id", None) job_status = job_data.get("status", None) result_id = result_data.get("id", None) result... |
.format( job_id, job_results["error"], job_results["data"])) sys.exit(1) final_job = job_results["data"]["job"] final_result = job_results["data"]["result"] if verbose: log.info(("job={}") .format( ppj(final_job))) else: log.info(("job={}") .format( str(final_job)[0:10])) if verbose: log.info(("result={}") .format( ppj... |
def prepare_new_dataset(): """prepare_new_dataset Prepare a new ``MLPrepare`` record and dataset files on disk. """ parser = argparse.ArgumentParser( description=( "Python client to Prepare a dataset")) parser.add_argument( "-u", help="username", required=False, dest="user") parser.add_argument( "-p", help="user passwo... |
path to CA bundle directory for " "client encryption over HTTP"), required=False, dest="ca_dir") parser.add_argument( "-c", help=( "optional - path to x509 certificate for " "client encryption over HTTP"), required=False, dest="cert_file") parser.add_argument( "-k", help=( "optional - path to x509 key file for " "clien... |
= ev( "API_USER", "user-not-set") password = ev( "API_PASSWORD", "password-not-set") email = ev( "API_EMAIL", "email-not-set") url = ev( "API_URL", "http://localhost:8010") prepare_file = ev( "DATAFILE", "prepare_file-not-set") ca_dir = os.getenv( "API_CA_BUNDLE_DIR", None) cert_file = os.getenv( "API_CERT_FILE", None)... |
args.email: email = args.email if args.url: url = args.url if args.prepare_file: prepare_file = args.prepare_file if args.ca_dir: ca_dir = args.ca_dir if args.cert_file: cert_file = args.cert_file if args.key_file: key_file = args.key_file if args.silent: verbose = False if args.debug: debug = True usage = ( "Please ru... |
<optional - path to CA bundle directory> " "-c <optional - path to x509 ssl certificate file> " "-k <optional - path to x509 ssl key file>") valid = True if not user or user == "user-not-set": log.error("missing user") valid = False if not password or password == "password-not-set": log.error("missing password") valid ... |
= False else: if not os.path.exists(prepare_file): log.error(("did not find prepare_file={} on disk") .format( prepare_file)) valid = False if not valid: log.error(usage) sys.exit(1) if verbose: log.info(("creating client user={} url={} file={}") .format( user, url, prepare_file)) client = AIClient( user=user, email=em... |
if verbose: log.info("running prepare") prepare_was_started = False response = client.run_prepare( body=req_body) if response["status"] == SUCCESS: log.info(("prepare started with response={}") .format( response["data"])) prepare_was_started = True elif response["status"] == FAILED: log.error(("prepare failed with erro... |
"with an error='{}' with response={}") .format( response["error"], response["data"])) if not prepare_was_started: sys.exit(1) if debug: log.info(("parsing response data={}") .format( response["data"])) else: if verbose: log.info("parsing data") prepare_data = response["data"] if not prepare_data: log.error(("missing pr... |
prepare.id={} to finish " "error={} data={}") .format( prepare_id, prepare_results["error"], prepare_results["data"])) sys.exit(1) final_prepare = prepare_results["data"] log.info(("prepare={}") .format( ppj(final_prepare))) log.info(("prepare.id={} is done") .format( prepare_id)) |
def drape(raster, feature): """Convert a 2D feature to a 3D feature by sampling a raster Parameters: raster (rasterio): raster to provide the z coordinate feature (dict): fiona feature record to convert Returns: result (Point or Linestring): shapely Point or LineString of xyz coordinate triples """ coords = feature['ge... |
== 'LineString': xyz = sample(raster, coords) points = [Point(x, y, z) for x, y, z in xyz] result = LineString(points) else: logging.error('drape not implemented for {}'.format(geom_type)) return result |
def sample(raster, coords): """Sample a raster at given coordinates Given a list of coordinates, return a list of x,y,z triples with z coordinates sampled from an input raster Parameters: raster (rasterio): raster dataset to sample coords: array of tuples containing coordinate pairs (x,y) or triples (x,y,z) Returns: re... |
geometry, z coordinate will be updated.') z = raster.sample([(x, y) for x, y, z in coords], indexes=raster.indexes) else: z = raster.sample(coords, indexes=raster.indexes) result = [(vert[0], vert[1], vert_z) for vert, vert_z in zip(coords, z)] return result |
def setup_logging( default_level=logging.INFO, default_path="{}/logging.json".format( os.getenv( "LOG_DIR", os.path.dirname(os.path.realpath(__file__)))), env_key="LOG_CFG", config_name=None): """setup_logging Setup logging configuration :param default_level: level to log :param default_path: path to config (optional) ... |
if os.path.exists(path): with open(path, "rt") as f: config = json.load(f) logging.config.dictConfig(config) return else: cwd_path = os.getcwd() + "/antinex_client/log/{}".format( file_name) if os.path.exists(cwd_path): with open(cwd_path, "rt") as f: config = json.load(f) logging.config.dictConfig(config) return rels_... |
def build_logger( name=os.getenv( "LOG_NAME", "client"), config="logging.json", log_level=logging.INFO, log_config_path="{}/logging.json".format( os.getenv( "LOG_CFG", os.path.dirname(os.path.realpath(__file__))))): """build_logger :param name: name that shows in the logger :param config: name of the config file :param... |
default_level=log_level, default_path=use_config) return logging.getLogger(name) |
def build_colorized_logger( name=os.getenv( "LOG_NAME", "client"), config="colors-logging.json", log_level=logging.INFO, log_config_path="{}/logging.json".format( os.getenv( "LOG_CFG", os.path.dirname(os.path.realpath(__file__))))): """build_colorized_logger :param name: name that shows in the logger :param config: nam... |
override_config))) if os.path.exists(override_config): setup_logging( default_level=log_level, default_path=override_config) return logging.getLogger(name) if debug_log_config: print(( "Failed to find log config using env var: " "SHARED_LOG_CFG={}".format( override_config))) else: if debug_log_config: print(( "Not usin... |
use_config = ("./log/{}").format( config) if not os.path.exists(use_config): use_config = ("./antinex_client/log/{}").format( "logging.json") # find the last log config backup from the base of the repo # find the log config from the defaults with the env LOG_CFG # find the log config from the base of the repo # find th... |
def authenticate(self, request: HttpRequest, auth_route: str, actual_params: dict) -> bool: """ Your AuhtService should override this method for request authentication, otherwise means no authentication. :param request: HttpRequest Django's HttpRequest object :param auth_route: str User's resqueted route :param actual_... |
def cli(source_f, raster_f, output, verbose): """ Converts 2D geometries to 3D using GEOS sample through fiona. \b Example: drape point.shp elevation.tif -o point_z.shp """ with fiona.open(source_f, 'r') as source: source_driver = source.driver source_crs = source.crs sink_schema = source.schema.copy() source_geom = so... |
== '3D LineString': pass else: click.BadParameter("Source geometry type {} not implemented".format(source_geom)) with rasterio.open(raster_f) as raster: if source_crs != raster.crs: click.BadParameter("Features and raster have different CRS.") if raster.count > 1: warnings.warn("Found {0} bands in {1}, expected a singl... |
output, 'w', driver=source_driver, crs=source_crs, schema=sink_schema) as sink: for feature in source: try: feature_z = drapery.drape(raster, feature) sink.write({ 'geometry': mapping(feature_z), 'properties': feature['properties'], }) except Exception: logging.exception("Error processing feature %s:", feature['id']) |
def for_model(self, model): """ QuerySet for all comments for a particular model (either an instance or a class). """ ct = ContentType.objects.get_for_model(model) qs = self.get_queryset().filter(content_type=ct) if isinstance(model, models.Model): qs = qs.filter(object_pk=force_text(model._get_pk_val())) return qs |
def eval(self, command): 'Blocking call, returns the value of the execution in JS' event = threading.Event() # TODO: Add event to server #job_id = str(id(command)) import random job_id = str(random.random()) server.EVALUATIONS[job_id] = event message = '?' + job_id + '=' + command logging.info(('message:', [message])) ... |
return value_parser() else: del server.EVALUATIONS[job_id] if job_id in server.RESULTS: del server.RESULTS[job_id] raise IOError('Evaluation failed.') |
def register(self, callback, name): 'Register a callback on server and on connected clients.' server.CALLBACKS[name] = callback self.run(''' window.skink.%s = function(args=[]) { window.skink.call("%s", args); }''' % (name, name)) |
def launch_exception(message): """ Launch a Python exception from an error that took place in the browser. messsage format: - name: str - description: str """ error_name = message['name'] error_descr = message['description'] mapping = { 'ReferenceError': NameError, } if message['name'] in mapping: raise mapping[error_n... |
def start_predictions(): """start_predictions Using environment variables, create an AntiNex AI Client. You can also use command line args if you want. This can train a new deep neural network if it does not exist or it can use an existing pre-trained deep neural network within the AntiNex Core to make new predictions.... |
a Pre-trained Deep Neural Network " "with AntiNex Django Rest Framework")) parser.add_argument( "-f", help=( "file to use default ./examples/" "predict-rows-scaler-full-django.json"), required=False, dest="datafile") parser.add_argument( "-m", help="send mock data", required=False, dest="use_fake_rows", action="store_t... |
dest="cert_file") parser.add_argument( "-k", help=( "optional - path to x509 key file for " "client encryption over HTTP"), required=False, dest="key_file") parser.add_argument( "-s", help="silent", required=False, dest="silent", action="store_true") parser.add_argument( "-d", help="debug", required=False, dest="debug"... |
"API_CLIENT_DEBUG", "0")).lower() == "1") use_fake_rows = False if args.use_fake_rows: use_fake_rows = True if args.datafile: datafile = args.datafile if args.ca_dir: ca_dir = args.ca_dir if args.cert_file: cert_file = args.cert_file if args.key_file: key_file = args.key_file if args.silent: verbose = False if args.deb... |
in full or partial prediction record dictionaries # the generate_ai_request will fill in gaps with defaults fake_rows_for_predicting = [ { "tcp_seq": 1 }, { "tcp_seq": 2 }, { "tcp_seq": 3 }, { "tcp_seq": 4 } ] res_gen = None if use_fake_rows: res_gen = generate_ai_request( predict_rows=fake_rows_for_predicting) else: r... |
sending mock data from this file or a file on disk if res_gen["status"] != SUCCESS: log.error(("failed generate_ai_request with error={}") .format( res_gen["error"])) sys.exit(1) req_body = res_gen["data"] if verbose: log.info("running job") job_was_started = False response = client.run_job( body=req_body) if response[... |
== ERROR: log.error(("job had an error='{}' with response={}") .format( response["error"], response["data"])) elif response["status"] == LOGIN_FAILED: log.error(("job reported user was not able to log in " "with an error='{}' with response={}") .format( response["error"], response["data"])) if not job_was_started: sys.... |
job_data: log.error(("missing job dictionary in response data={}") .format( response["data"])) sys.exit(1) if not result_data: log.error(("missing results dictionary in response data={}") .format( response["data"])) sys.exit(1) job_id = job_data.get("id", None) job_status = job_data.get("status", None) result_id = resu... |
error={} data={}") .format( job_id, job_results["error"], job_results["data"])) sys.exit(1) final_job = job_results["data"]["job"] final_result = job_results["data"]["result"] log.info(("job={}") .format( ppj(final_job))) log.info(("result={}") .format( ppj(final_result))) log.info(("job.id={} is done") .format( job_id... |
def login( self): """login""" auth_url = self.api_urls["login"] if self.verbose: log.info(("log in user={} url={} ca_dir={} cert={}") .format( self.user, auth_url, self.ca_dir, self.cert)) use_headers = { "Content-type": "application/json" } login_data = { "username": self.user, "password": self.password } if self.debu... |
reason={}") .format( response.status_code, response.text, response.reason)) user_token = "" if response.status_code == 200: user_token = json.loads(response.text)["token"] if user_token != "": self.token = user_token self.login_status = LOGIN_SUCCESS if self.verbose: log.debug("login success") else: log.error(("failed ... |
def build_response( self, status=NOT_SET, error="", data=None): """build_response :param status: status code :param error: error message :param data: dictionary to send back """ res_node = { "status": status, "error": error, "data": data } return res_node |
def retry_login( self): """retry_login""" if not self.user or not self.password: return self.build_response( status=ERROR, error="please set the user and password") retry = 0 not_done = True while not_done: if self.is_logged_in(): return self.build_response( status=SUCCESS) else: if self.verbose: log.debug(("login atte... |
self.max_retries: return self.build_response( status=ERROR, error="failed logging in user={} retries={}".format( self.user, self.max_retries)) # if login worked or not return self.build_response( status=FAILED, error="user={} not able to login attempts={}".format( self.user, retry)) |
def get_prepare_by_id( self, prepare_id=None): """get_prepare_by_id :param prepare_id: MLJob.id in the database """ if not prepare_id: log.error("missing prepare_id for get_prepare_by_id") return self.build_response( status=ERROR, error="missing prepare_id for get_prepare_by_id") if self.debug: log.info(("user={} getti... |
verify=self.use_verify, cert=self.cert, headers=self.get_auth_header()) if self.debug: log.info(("JOB response status_code={} text={} reason={}") .format( response.status_code, response.text, response.reason)) if response.status_code == 401: login_res = self.retry_login() if login_res["status"] != SUCCESS: if self.verb... |
not prepare_id: return self.build_response( status=ERROR, error="missing prepare.id", data="text={} reason={}".format( response.reason, response.text)) self.all_prepares[str(prepare_id)] = prepare_data if self.debug: log.info(("added prepare={} all_prepares={}") .format( prepare_id, len(self.all_prepares))) return self... |
def wait_for_job_to_finish( self, job_id, sec_to_sleep=5.0, max_retries=100000): """wait_for_job_to_finish :param job_id: MLJob.id to wait on :param sec_to_sleep: seconds to sleep during polling :param max_retries: max retires until stopping """ not_done = True retry_attempt = 1 while not_done: if self.debug: log.info(... |
with error={}") .format( job_id, response["error"])) return self.build_response( status=ERROR, error=response["error"], data=response["data"]) # stop if this failed getting the job details job_data = response.get( "data", None) if not job_data: return self.build_response( status=ERROR, error="failed to find job diction... |
job_status)) result_id = job_data["predict_manifest"]["result_id"] if self.debug: log.info(("JOBRESULT getting result.id={} details") .format( result_id)) response = self.get_result_by_id(result_id) if self.debug: log.info(("JOBRESULT got result.id={} response={}") .format( result_id, response)) if response["status"] !... |
{ "job": job_data, "result": result_data } not_done = False return self.build_response( status=SUCCESS, error="", data=full_response) else: if retry_attempt % 100 == 0: if self.verbose: log.info(("result_id={} are not done retry={}") .format( result_id, retry_attempt)) retry_attempt += 1 if retry_attempt > max_retries:... |
to the db else: retry_attempt += 1 if retry_attempt > max_retries: err_msg = ("failed waiting " "for job.id={} to finish").format( job_id) log.error(err_msg) return self.build_response( status=ERROR, error=err_msg) else: if self.verbose: if retry_attempt % 100 == 0: log.info(("waiting on job.id={} retry={}") .format( j... |
def wait_for_prepare_to_finish( self, prepare_id, sec_to_sleep=5.0, max_retries=100000): """wait_for_prepare_to_finish :param prepare_id: MLPrepare.id to wait on :param sec_to_sleep: seconds to sleep during polling :param max_retries: max retires until stopping """ not_done = True retry_attempt = 1 while not_done: if s... |
" "with error={}") .format( prepare_id, response["error"])) return self.build_response( status=ERROR, error=response["error"], data=response["data"]) # stop if this failed getting the prepare details prepare_data = response.get( "data", None) if not prepare_data: return self.build_response( status=ERROR, error="failed ... |
retry_attempt > max_retries: err_msg = ("failed waiting " "for prepare.id={} to finish").format( prepare_id) log.error(err_msg) return self.build_response( status=ERROR, error=err_msg) else: if self.verbose: if retry_attempt % 100 == 0: log.info(("waiting on prepare.id={} retry={}") .format( prepare_id, retry_attempt))... |
def get_comment_object(self): """ NB: Overridden to remove dupe comment check for admins (necessary for canned responses) Return a new (unsaved) comment object based on the information in this form. Assumes that the form is already validated and will throw a ValueError if not. Does not set any of the fields that would ... |
self.is_valid(): raise ValueError( "get_comment_object may only be called on valid forms") CommentModel = self.get_comment_model() new = CommentModel(**self.get_comment_create_data()) user_model = get_user_model() try: user = user_model.objects.get(username=new.user_name) if not user.is_staff: new = self.check_for_dupl... |
def boot(app_name) -> Rinzler: """ Start Rinzler App :param app_name: str Application's identifier :return: dict """ app = Rinzler(app_name) app.log.info("App booted =)") return app |
def mount(self, route: str, controller: callable) -> url: """ Maps a route namespace with the given params and point it's requests to the especified controller. :param route: str Namespace route to be mapped :param controller: callback Controller callable to map end-points :rtype: url """ if issubclass(controller, Temp... |
subclass of %s" % ( controller, TemplateView ) ) |
def set_auth_service(self, auth_service: BaseAuthService): """ Sets the authentication service :param auth_service: BaseAuthService Authentication service :raises: TypeError If the auth_service object is not a subclass of rinzler.auth.BaseAuthService :rtype: Rinzler """ if issubclass(auth_service.__class__, BaseAuthSer... |
def handle(self, request: HttpRequest) -> HttpResponse: """ Prepares for the CallBackResolver and handles the response and exceptions :param request HttpRequest :rtype: HttpResponse """ self.__request_start = datetime.now() self.__request = request self.__uri = request.path[1:] self.__method = request.method # Initiali... |
return self.set_response_headers(self.no_route_found(self.__request).render(indent)) response = HttpResponse(None) try: response = self.exec_route_callback() except RinzlerHttpException as e: client.captureException() self.app.log.error(f"< {e.status_code}", exc_info=True) response = Response(None, status=e.status_code... |
def exec_route_callback(self) -> Response or object: """ Executes the resolved end-point callback, or its fallback :rtype: Response or object """ if self.__method.lower() in self.__end_points: for bound in self.__end_points[self.__method.lower()]: route = list(bound)[0] expected_params = self.get_url_params(route) actu... |
d: int((d.days * 24 * 60 * 60 * 1000) + (d.seconds * 1000) + (d.microseconds / 1000)) )(datetime.now() - self.__request_start) return bound[route](self.__request, self.app, **pattern_params) else: raise AuthException("Authentication failed.") if self.__method == "OPTIONS": self.app.log.info("Route matched: {0} {1}".for... |
def request_matches_route(self, actual_route: str, expected_route: str): """ Determines whether a route matches the actual requested route or not :param actual_route str :param expected_route :rtype: Boolean """ expected_params = self.get_url_params(expected_route) actual_params = self.get_url_params(actual_route) i = ... |
def authenticate(self, bound_route, actual_params) -> bool: """ Runs the pre-defined authenticaton service :param bound_route str route matched :param actual_params dict actual url parameters :rtype: bool """ if self.__auth_service is not None: auth_route = "{0}_{1}{2}".format(self.__method, self.__route, bound_route) ... |
def get_callback_pattern(expected_params, actual_params): """ Assembles a dictionary whith the parameters schema defined for this route :param expected_params dict parameters schema defined for this route :param actual_params dict actual url parameters :rtype: dict """ pattern = dict() key = 0 for exp_param in expected... |
def get_url_params(end_point: str) -> list: """ Gets route parameters as dictionary :param end_point str target route :rtype: list """ var_params = end_point.split('/') if len(var_params) == 1 and var_params[0] == '': return [] elif len(var_params) == 1 and var_params[0] != '': return [var_params[0]] else: params = lis... |
def set_end_point_uri(self) -> bool: """ Extracts the route from the accessed URL and sets it to __end_point_uri :rtype: bool """ expected_parts = self.__route.split("/") actual_parts = self.__uri.split("/") i = 0 for part in expected_parts: if part != actual_parts[i]: return False i = i + 1 uri_prefix = len(self.__rou... |
def no_route_found(self, request): """ Default callback for route not found :param request HttpRequest :rtype: Response """ response_obj = OrderedDict() response_obj["status"] = False response_obj["exceptions"] = { "message": "No route found for {0} {1}".format(self.__method, self.__uri), } response_obj["request"] = { ... |
def welcome_page(self): """ Defaulf welcome page when the route / is note mapped yet :rtype: HttpResponse """ message = "HTTP/1.1 200 OK RINZLER FRAMEWORK" return HttpResponse( "<center><h1>{0}({1})</h1></center>".format(message, self.app.app_name), content_type="text/html", charset="utf-8" ) |
def default_route_options(): """ Default callback for OPTIONS request :rtype: Response """ response_obj = OrderedDict() response_obj["status"] = True response_obj["data"] = "Ok" return Response(response_obj, content_type="application/json", charset="utf-8") |
def set_response_headers(self, response: HttpResponse) -> HttpResponse: """ Appends default headers to every response returned by the API :param response HttpResponse :rtype: HttpResponse """ public_name = os.environ.get('SERVER_PUBLIC_NAME') response_headers = { 'access-control-allow-headers': self.app.allowed_headers... |
!= 404: self.app.log.info("< {0}".format(status)) return response |
def get_json_ident(request_headers: dict) -> int: """ Defines whether the JSON response will be indented or not :param request_headers: dict :return: self """ if 'HTTP_USER_AGENT' in request_headers: indent = 2 if re.match("[Mozilla]{7}", request_headers['HTTP_USER_AGENT']) else 0 else: indent = 0 return indent |
def prop(key, dct_or_obj): """ Implementation of prop (get_item) that also supports object attributes :param key: :param dct_or_obj: :return: """ # Note that hasattr is a builtin and getattr is a ramda function, hence the different arg position if isinstance(dict, dct_or_obj): if has(key, dct_or_obj): return dct_or_obj... |
else: raise Exception("Key %s not expected for list type: %s" % (key, dct_or_obj)) elif isinstance(object, dct_or_obj): if hasattr(dct_or_obj, key): return getattr(key, dct_or_obj) else: raise Exception("No key %s found for objects %s" % (key, dct_or_obj)) else: raise Exception("%s is neither a dict nor objects" % dct_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.