code
stringlengths
31
2.05k
label_name
stringclasses
5 values
label
int64
0
4
def on_header_value(self, data: bytes, start: int, end: int) -> None: message = (MultiPartMessage.HEADER_VALUE, data[start:end]) self.messages.append(message)
Class
2
def __init__( self, headers: Headers, stream: typing.AsyncGenerator[bytes, None] ) -> None: assert ( multipart is not None ), "The `python-multipart` library must be installed to use form parsing." self.headers = headers self.stream = stream self.messages: typing.List[typing.Tuple[MultiPartMessage, bytes]] = []
Class
2
def on_end(self) -> None: message = (MultiPartMessage.END, b"") self.messages.append(message)
Class
2
def on_headers_finished(self) -> None: message = (MultiPartMessage.HEADERS_FINISHED, b"") self.messages.append(message)
Class
2
def on_header_end(self) -> None: message = (MultiPartMessage.HEADER_END, b"") self.messages.append(message)
Class
2
def form(self) -> AwaitableOrContextManager[FormData]: return AwaitableOrContextManagerWrapper(self._get_form())
Class
2
async def _get_form(self) -> FormData: if self._form is None: assert ( parse_options_header is not None ), "The `python-multipart` library must be installed to use form parsing." content_type_header = self.headers.get("Content-Type") content_type: bytes content_type, _ = parse_options_header(content_type_header) if content_type == b"multipart/form-data": try: multipart_parser = MultiPartParser(self.headers, self.stream()) self._form = await multipart_parser.parse() except MultiPartException as exc: if "app" in self.scope: raise HTTPException(status_code=400, detail=exc.message) raise exc elif content_type == b"application/x-www-form-urlencoded": form_parser = FormParser(self.headers, self.stream()) self._form = await form_parser.parse() else: self._form = FormData() return self._form
Class
2
def execute(self): # clean up tmp extraction folder if os.path.exists(TEMP_EXTRACTION_PATH) and not CleanupDir(TEMP_EXTRACTION_PATH).run(): logger.error('Could not clean temp folder') raise IOError # untar the package into tmp folder with closing(tarfile.open(self.gppkg.abspath)) as tarinfo: tarinfo.extractall(TEMP_EXTRACTION_PATH) # move all the deps into same folder as the main rpm path = os.path.join(TEMP_EXTRACTION_PATH, DEPS_DIR) if os.path.exists(path): for cur_file in os.listdir(path): shutil.move(os.path.join(TEMP_EXTRACTION_PATH, DEPS_DIR, cur_file), TEMP_EXTRACTION_PATH)
Base
1
def open(self, *args, **kwargs): """Websocket connection opened. Call our terminal manager to get a terminal, and connect to it as a client. """ # Jupyter has a mixin to ping websockets and keep connections through # proxies alive. Call super() to allow that to set up: tornado.websocket.WebSocketHandler.open(self, *args, **kwargs) api_key = self.get_argument('api_key', None, True) token = self.get_argument('token', None, True) cwd = self.get_argument('cwd', None, True) term_name = self.get_argument('term_name', None, True) user = None if REQUIRE_USER_AUTHENTICATION and api_key and token: oauth_client = Oauth2Application.query.filter( Oauth2Application.client_id == api_key, ).first() if oauth_client: oauth_token, valid = authenticate_client_and_token(oauth_client.id, token) valid = valid and \ oauth_token and \ oauth_token.user if valid: user = oauth_token.user else: raise Exception('Invalid token') self.term_name = term_name if term_name else 'tty' if user: self.term_name = f'{self.term_name}_{user.id}' self._logger.info("TermSocket.open: %s", self.term_name) self.terminal = self.term_manager.get_terminal(self.term_name, cwd=cwd) self.terminal.clients.append(self) self.__initiate_terminal(self.terminal)
Base
1
def __init__(self, path): self.path = path
Class
2
def _write(self, contents: dict): LOGGER.debug(f'Writing to {self.path}') with open(self.path, 'w') as fp: fp.write(json.dumps(contents))
Class
2
def secret_path(monkeypatch, tmp_path): secret_path = str(tmp_path / '.test') monkeypatch.setattr(auth, 'SECRET_FILE_PATH', secret_path) yield secret_path
Class
2
def __init__(self, config, md): """Initialize.""" base = config.get('base_path') if isinstance(base, str): base = [base] self.base_path = base self.encoding = config.get('encoding') self.check_paths = config.get('check_paths') self.auto_append = config.get('auto_append') self.url_download = config['url_download'] self.url_max_size = config['url_max_size'] self.url_timeout = config['url_timeout'] self.url_request_headers = config['url_request_headers'] self.dedent_subsections = config['dedent_subsections'] self.tab_length = md.tab_length super(SnippetPreprocessor, self).__init__()
Base
1
def get_snippet_path(self, path): """Get snippet path.""" snippet = None for base in self.base_path: if os.path.exists(base): if os.path.isdir(base): filename = os.path.join(base, path) if os.path.exists(filename): snippet = filename break else: basename = os.path.basename(base) dirname = os.path.dirname(base) if basename.lower() == path.lower(): filename = os.path.join(dirname, path) if os.path.exists(filename): snippet = filename break return snippet
Base
1
def rebuild_proxies(self, prepared_request, proxies): """This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect). This method also replaces the Proxy-Authorization header where necessary. :rtype: dict """ headers = prepared_request.headers scheme = urlparse(prepared_request.url).scheme new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env) if "Proxy-Authorization" in headers: del headers["Proxy-Authorization"] try: username, password = get_auth_from_url(new_proxies[scheme]) except KeyError: username, password = None, None if username and password: headers["Proxy-Authorization"] = _basic_auth_str(username, password) return new_proxies
Class
2
def confirm_sns_subscription(notification): logger.info( 'Received subscription confirmation: TopicArn: %s', notification.get('TopicArn'), extra={ 'notification': notification, }, ) # Get the subscribe url and hit the url to confirm the subscription. subscribe_url = notification.get('SubscribeURL') try: urlopen(subscribe_url).read() except URLError as e: # Some kind of error occurred when confirming the request. logger.error( 'Could not confirm subscription: "%s"', e, extra={ 'notification': notification, }, exc_info=True, )
Base
1
def _get_bytes_to_sign(self): """ Creates the message used for signing SNS notifications. This is used to verify the bounce message when it is received. """ # Depending on the message type the fields to add to the message # differ so we handle that here. msg_type = self._data.get('Type') if msg_type == 'Notification': fields_to_sign = [ 'Message', 'MessageId', 'Subject', 'Timestamp', 'TopicArn', 'Type', ] elif (msg_type == 'SubscriptionConfirmation' or msg_type == 'UnsubscribeConfirmation'): fields_to_sign = [ 'Message', 'MessageId', 'SubscribeURL', 'Timestamp', 'Token', 'TopicArn', 'Type', ] else: # Unrecognized type logger.warning('Unrecognized SNS message Type: "%s"', msg_type) return None bytes_to_sign = [] for field in fields_to_sign: field_value = self._data.get(field) if not field_value: continue # Some notification types do not have all fields. Only add fields # with values. bytes_to_sign.append(f"{field}\n{field_value}\n") return "".join(bytes_to_sign).encode()
Base
1
def BounceMessageVerifier(*args, **kwargs): warnings.warn( 'utils.BounceMessageVerifier is deprecated. It is renamed to EventMessageVerifier.', RemovedInDjangoSES20Warning, ) # parameter name is renamed from bounce_dict to notification. if 'bounce_dict' in kwargs: kwargs['notification'] = kwargs['bounce_dict'] del kwargs['bounce_dict'] return EventMessageVerifier(*args, **kwargs)
Base
1
def verify_bounce_message(msg): """ Verify an SES/SNS bounce(event) notification message. """ warnings.warn( 'utils.verify_bounce_message is deprecated. It is renamed to verify_event_message.', RemovedInDjangoSES20Warning, ) return verify_event_message(msg)
Base
1
def get_keys(self, lst): """ return a list of pk values from object list """ pk_name = self.get_pk_name() if self.is_pk_composite(): return [[getattr(item, pk) for pk in pk_name] for item in lst] else: return [getattr(item, pk_name) for item in lst]
Base
1
def get_user_columns_list(self): """ Returns a list of user viewable columns names """ return self.get_columns_list()
Base
1
def get_columns_list(self): """ Returns a list of all the columns names """ return []
Base
1
def get(self, pk, filter=None): """ return the record from key, you can optionally pass filters if pk exits on the db but filters exclude it it will return none. """ pass
Base
1
def get_values_json(self, lst, list_columns): """ Converts list of objects from query to JSON """ result = [] for item in self.get_values(lst, list_columns): for key, value in list(item.items()): if isinstance(value, datetime.datetime) or isinstance( value, datetime.date ): value = value.isoformat() item[key] = value if isinstance(value, list): item[key] = [str(v) for v in value] result.append(item) return result
Base
1
def add(self, item): """ Adds object """ raise NotImplementedError
Base
1
def get_search_columns_list(self): """ Returns a list of searchable columns names """ return []
Base
1
def get_order_columns_list(self, list_columns=None): """ Returns a list of order columns names """ return []
Base
1
def edit(self, item): """ Edit (change) object """ raise NotImplementedError
Base
1
def get_pk_name(self): """ Returns the primary key name """ raise NotImplementedError
Base
1
def get_values(self, lst, list_columns): """ Get Values: formats values for list template. returns [{'col_name':'col_value',....},{'col_name':'col_value',....}] :param lst: The list of item objects from query :param list_columns: The list of columns to include """ for item in lst: retdict = {} for col in list_columns: retdict[col] = self._get_attr_value(item, col) yield retdict
Base
1
def get_related_interface(self, col_name): """ Returns a BaseInterface for the related model of column name. :param col_name: Column name with relation :return: BaseInterface """ raise NotImplementedError
Base
1
def _get_values(self, lst, list_columns): """ Get Values: formats values for list template. returns [{'col_name':'col_value',....},{'col_name':'col_value',....}] :param lst: The list of item objects from query :param list_columns: The list of columns to include """ retlst = [] for item in lst: retdict = {} for col in list_columns: retdict[col] = self._get_attr_value(item, col) retlst.append(retdict) return retlst
Base
1
def delete(self, item): """ Deletes object """ raise NotImplementedError
Base
1
def delete(self, item: Model, raise_exception: bool = False) -> bool: try: self._delete_files(item) self.session.delete(item) self.session.commit() self.message = (as_unicode(self.delete_row_message), "success") return True except IntegrityError as e: self.message = (as_unicode(self.delete_integrity_error_message), "warning") log.warning(LOGMSG_WAR_DBI_DEL_INTEGRITY.format(str(e))) self.session.rollback() if raise_exception: raise e return False except Exception as e: self.message = ( as_unicode(self.general_error_message + " " + str(sys.exc_info()[0])), "danger", ) log.exception(LOGMSG_ERR_DBI_DEL_GENERIC.format(str(e))) self.session.rollback() if raise_exception: raise e return False
Base
1
def delete_all(self, items: List[Model]) -> bool: try: for item in items: self._delete_files(item) self.session.delete(item) self.session.commit() self.message = (as_unicode(self.delete_row_message), "success") return True except IntegrityError as e: self.message = (as_unicode(self.delete_integrity_error_message), "warning") log.warning(LOGMSG_WAR_DBI_DEL_INTEGRITY.format(str(e))) self.session.rollback() return False except Exception as e: self.message = ( as_unicode(self.general_error_message + " " + str(sys.exc_info()[0])), "danger", ) log.exception(LOGMSG_ERR_DBI_DEL_GENERIC.format(str(e))) self.session.rollback() return False
Base
1
def add(self, item: Model, raise_exception: bool = False) -> bool: try: self.session.add(item) self.session.commit() self.message = (as_unicode(self.add_row_message), "success") return True except IntegrityError as e: self.message = (as_unicode(self.add_integrity_error_message), "warning") log.warning(LOGMSG_WAR_DBI_ADD_INTEGRITY.format(str(e))) self.session.rollback() if raise_exception: raise e return False except Exception as e: self.message = ( as_unicode(self.general_error_message + " " + str(sys.exc_info()[0])), "danger", ) log.exception(LOGMSG_ERR_DBI_ADD_GENERIC.format(str(e))) self.session.rollback() if raise_exception: raise e return False
Base
1
def edit(self, item: Model, raise_exception: bool = False) -> bool: try: self.session.merge(item) self.session.commit() self.message = (as_unicode(self.edit_row_message), "success") return True except IntegrityError as e: self.message = (as_unicode(self.edit_integrity_error_message), "warning") log.warning(LOGMSG_WAR_DBI_EDIT_INTEGRITY.format(str(e))) self.session.rollback() if raise_exception: raise e return False except Exception as e: self.message = ( as_unicode(self.general_error_message + " " + str(sys.exc_info()[0])), "danger", ) log.exception(LOGMSG_ERR_DBI_EDIT_GENERIC.format(str(e))) self.session.rollback() if raise_exception: raise e return False
Base
1
def warn( # type: ignore[override] self, msg: str, path_name: str | None = None, func_name: str | None = None, *args: Any, **kwargs: Any, ) -> None: warnings.warn( "The 'warn' method is deprecated, " "use 'warning' instead", DeprecationWarning, 2, ) self.warning(msg, path_name, func_name, *args, **kwargs)
Class
2
def write_log(self, log_message, ipaddress): # Make entry. db = self.connect_logdb() c = db.cursor() # Insert a row of data. c.execute( f"""insert into log values ({datetime.utcnow().strftime('%Y%m%d')}, {datetime.utcnow().strftime('%H%M%S')}, ?, ?)""", log_message, ipaddress, ) # Save (commit) the changes. db.commit() # Close cursor. c.close() # Close connection. db.close()
Base
1
def home(): # Get the boards from the database: boards = Database.get_boards() # Write to the log: Database.write_log(f"Request to home page from {request.environ['REMOTE_ADDR']}.", request.environ['REMOTE_ADDR']) # Render the home page, with the boards: return render_template( "home.html", title=Config.get_config()["title"], description=Config.get_config()["short_description"], boards=boards, )
Base
1
def about(): # Write to the log: Database.write_log(f"Request to about page from {request.environ['REMOTE_ADDR']}.", f"{request.environ['REMOTE_ADDR']}") return render_template( "about.html", description=Config.get_config()["long_description"].split("<br>"), )
Base
1
def date_filter(s): return datetime.utcnow().strftime('%Y')
Base
1
def boardView(): boardID = request.args.get("board", default=1, type=int) pageID = request.args.get("page", default=1, type=int) # Get the board information: boardInfo = Database.get_board_info(boardID) # Get the posts from the board: posts = Database.get_posts_from_board(boardID) # Reduce the list to 15 items (starting from the index specified by pageID). posts = posts[(pageID - 1) * 15 : pageID * 15] # Get the number of pages: numberOfPages = len(Database.get_posts_from_board(boardID)) // 15 + 1 # Write to the log: Database.write_log(f"Request to board page with id {boardID} and page with ID {pageID} from {request.environ['REMOTE_ADDR']}.", f"{request.environ['REMOTE_ADDR']}") return render_template( "board.html", title=boardInfo[0][1], description=boardInfo[0][2], posts=posts, numberOfPages=numberOfPages, boardID=boardID, pageID=pageID, )
Base
1
def postView(): # Get the post ID from the URL: postID = request.args.get("postid", default=1, type=int) # Get the post information: postInfo = Database.get_post_info(postID) # Get the comments from the post: comments = Database.get_comments_from_post(postID) # Get the user information: userInfo = Database.get_user_info(postInfo[4]) # We need to turn postInfo from a tuple to a list. postInfo = list(postInfo) # We also need to turn each comment in the array to a list from a tuple. comments = [list(comment) for comment in comments] # We can handle turning the date from &Y&M&d in the postInfo[5] into a &d &M &Y format here. # We can also handle turning the date from &Y&M&d in the comments[5] into a &d &M &Y format here. postInfo[5] = datetime.strptime(str(postInfo[5]), "%Y%m%d").strftime("%d %B %Y") for comment in comments: comment[5] = datetime.strptime(str(comment[5]), "%Y%m%d").strftime("%d %B %Y") # We can also handle times here. Turn postInfo[6] and comments[6] into a 24 hour clock. postInfo[6] = datetime.strptime(str(postInfo[6]), "%H%M%S").strftime("%H:%M UTC") for comment in comments: comment[6] = datetime.strptime(str(comment[6]), "%H%M%S").strftime("%H:%M UTC") # We want to add a new index, 7, which will be the comment author's author profile. # To do this, we can use get_user_info() from the database module, feeding in index 3 of the comment. for comment in comments: commentAuthorInfo = Database.get_user_info(comment[3]) commentAuthorInfo = list(commentAuthorInfo) comment.append(commentAuthorInfo) # Write to the log: Database.write_log(f"Request to post page with id {postID} from {request.environ['REMOTE_ADDR']}.", f"{request.environ['REMOTE_ADDR']}") return render_template("post.html", user=userInfo, post=postInfo, comments=comments)
Base
1
def set(self, name, value, force=False): """Set a form element identified by ``name`` to a specified ``value``. The type of element (input, textarea, select, ...) does not need to be given; it is inferred by the following methods: :func:`~Form.set_checkbox`, :func:`~Form.set_radio`, :func:`~Form.set_input`, :func:`~Form.set_textarea`, :func:`~Form.set_select`. If none of these methods find a matching element, then if ``force`` is True, a new element (``<input type="text" ...>``) will be added using :func:`~Form.new_control`. Example: filling-in a login/password form with EULA checkbox .. code-block:: python form.set("login", username) form.set("password", password) form.set("eula-checkbox", True) Example: uploading a file through a ``<input type="file" name="tagname">`` field (provide the path to the local file, and its content will be uploaded): .. code-block:: python form.set("tagname", path_to_local_file) """ for func in ("checkbox", "radio", "input", "textarea", "select"): try: getattr(self, "set_" + func)({name: value}) return except InvalidFormMethod: pass if force: self.new_control('text', name, value=value) return raise LinkNotFoundError("No valid element named " + name)
Class
2
def test_upload_file(httpbin): browser = mechanicalsoup.StatefulBrowser() browser.open(httpbin + "/forms/post") # Create two temporary files to upload def make_file(content): path = tempfile.mkstemp()[1] with open(path, "w") as fd: fd.write(content) return path path1, path2 = (make_file(content) for content in ("first file content", "second file content")) # The form doesn't have a type=file field, but the target action # does show it => add the fields ourselves, and add enctype too. browser.select_form() browser._StatefulBrowser__state.form.form[ "enctype"] = "multipart/form-data" browser.new_control("file", "first", path1) browser.new_control("file", "second", "") browser["second"] = path2 browser.form.print_summary() response = browser.submit_selected() files = response.json()["files"] assert files["first"] == "first file content" assert files["second"] == "second file content"
Class
2
def _make_cmd(self, tmpfilename, info_dict): cmd = [self.exe, '-O', tmpfilename, '-nv', '--no-cookies', '--compression=auto'] if info_dict.get('http_headers') is not None: for key, val in info_dict['http_headers'].items(): cmd += ['--header', f'{key}: {val}'] cmd += self._option('--limit-rate', 'ratelimit') retry = self._option('--tries', 'retries') if len(retry) == 2: if retry[1] in ('inf', 'infinite'): retry[1] = '0' cmd += retry cmd += self._option('--bind-address', 'source_address') proxy = self.params.get('proxy') if proxy: for var in ('http_proxy', 'https_proxy'): cmd += ['--execute', f'{var}={proxy}'] cmd += self._valueless_option('--no-check-certificate', 'nocheckcertificate') cmd += self._configuration_args() cmd += ['--', info_dict['url']] return cmd
Class
2
def redirect_request(self, req, fp, code, msg, headers, newurl): if code not in (301, 302, 303, 307, 308): raise urllib.error.HTTPError(req.full_url, code, msg, headers, fp) new_method = req.get_method() new_data = req.data remove_headers = [] # A 303 must either use GET or HEAD for subsequent request # https://datatracker.ietf.org/doc/html/rfc7231#section-6.4.4 if code == 303 and req.get_method() != 'HEAD': new_method = 'GET' # 301 and 302 redirects are commonly turned into a GET from a POST # for subsequent requests by browsers, so we'll do the same. # https://datatracker.ietf.org/doc/html/rfc7231#section-6.4.2 # https://datatracker.ietf.org/doc/html/rfc7231#section-6.4.3 elif code in (301, 302) and req.get_method() == 'POST': new_method = 'GET' # only remove payload if method changed (e.g. POST to GET) if new_method != req.get_method(): new_data = None remove_headers.extend(['Content-Length', 'Content-Type']) new_headers = {k: v for k, v in req.headers.items() if k.lower() not in remove_headers} return urllib.request.Request( newurl, headers=new_headers, origin_req_host=req.origin_req_host, unverifiable=True, method=new_method, data=new_data)
Class
2
def _calc_headers(self, info_dict): res = merge_headers(self.params['http_headers'], info_dict.get('http_headers') or {}) if 'Youtubedl-No-Compression' in res: # deprecated res.pop('Youtubedl-No-Compression', None) res['Accept-Encoding'] = 'identity' cookies = self.cookiejar.get_cookie_header(info_dict['url']) if cookies: res['Cookie'] = cookies if 'X-Forwarded-For' not in res: x_forwarded_for_ip = info_dict.get('__x_forwarded_for_ip') if x_forwarded_for_ip: res['X-Forwarded-For'] = x_forwarded_for_ip return res
Class
2
def download(self, filename, info_dict, subtitle=False): """Download to a filename using the info from info_dict Return True on success and False otherwise """ nooverwrites_and_exists = ( not self.params.get('overwrites', True) and os.path.exists(encodeFilename(filename)) ) if not hasattr(filename, 'write'): continuedl_and_exists = ( self.params.get('continuedl', True) and os.path.isfile(encodeFilename(filename)) and not self.params.get('nopart', False) ) # Check file already present if filename != '-' and (nooverwrites_and_exists or continuedl_and_exists): self.report_file_already_downloaded(filename) self._hook_progress({ 'filename': filename, 'status': 'finished', 'total_bytes': os.path.getsize(encodeFilename(filename)), }, info_dict) self._finish_multiline_status() return True, False if subtitle: sleep_interval = self.params.get('sleep_interval_subtitles') or 0 else: min_sleep_interval = self.params.get('sleep_interval') or 0 sleep_interval = random.uniform( min_sleep_interval, self.params.get('max_sleep_interval') or min_sleep_interval) if sleep_interval > 0: self.to_screen(f'[download] Sleeping {sleep_interval:.2f} seconds ...') time.sleep(sleep_interval) ret = self.real_download(filename, info_dict) self._finish_multiline_status() return ret, True
Class
2
def compat_shlex_quote(s): import re return s if re.match(r'^[-_\w./]+$', s) else '"%s"' % s.replace('"', '\\"')
Base
1
def run(self, info): for tmpl in self.exec_cmd: cmd = self.parse_cmd(tmpl, info) self.to_screen('Executing command: %s' % cmd) retCode = subprocess.call(encodeArgument(cmd), shell=True) if retCode != 0: raise PostProcessingError('Command returned error code %d' % retCode) return [], info
Base
1
def __init__(self, *args, env=None, text=False, **kwargs): if env is None: env = os.environ.copy() self._fix_pyinstaller_ld_path(env) self.__text_mode = kwargs.get('encoding') or kwargs.get('errors') or text or kwargs.get('universal_newlines') if text is True: kwargs['universal_newlines'] = True # For 3.6 compatibility kwargs.setdefault('encoding', 'utf-8') kwargs.setdefault('errors', 'replace') super().__init__(*args, env=env, **kwargs, startupinfo=self._startupinfo)
Base
1
def _real_extract(self, url): activity_id, enrollment_id = self._match_valid_url(url).group('id', 'enrollment') course = self._call_api('enrollment', enrollment_id)['content'] activity = traverse_obj(course, ('learning_modules', ..., 'activities', lambda _, v: int(activity_id) == v['id']), get_all=False) if activity.get('type') not in ['Video Activity', 'Lesson Activity']: raise ExtractorError('The activity is not a video', expected=True) module = next((m for m in course.get('learning_modules') or [] if int(activity_id) in traverse_obj(m, ('activities', ..., 'id') or [])), None) vimeo_id = self._get_vimeo_id(activity_id) return { '_type': 'url_transparent', 'series': traverse_obj(course, ('content_description', 'title')), 'series_id': str_or_none(traverse_obj(course, ('content_description', 'id'))), 'id': vimeo_id, 'chapter': module.get('title'), 'chapter_id': str_or_none(module.get('id')), 'title': activity.get('title'), 'url': smuggle_url(f'https://player.vimeo.com/video/{vimeo_id}', {'http_headers': {'Referer': 'https://api.cybrary.it'}}) }
Base
1
def _real_extract(self, url): qs = parse_qs(url) src = urllib.parse.unquote(traverse_obj(qs, ('url', 0)) or '') if src and YoutubeTabIE.suitable(src): return self.url_result(src, YoutubeTabIE) return self.url_result(smuggle_url( urllib.parse.unquote(traverse_obj(qs, ('src', 0), ('url', 0))), {'http_headers': {'Referer': url}}))
Base
1
def _parse_video(self, video): title = video['title'] vimeo_id = self._search_regex( r'https?://player\.vimeo\.com/external/(\d+)', video['vimeoVideoURL'], 'vimeo id') uploader_id = video.get('hostID') return { '_type': 'url_transparent', 'id': vimeo_id, 'title': title, 'description': video.get('description'), 'url': smuggle_url( 'https://player.vimeo.com/video/' + vimeo_id, { 'http_headers': { 'Referer': 'https://storyfire.com/', } }), 'thumbnail': video.get('storyImage'), 'view_count': int_or_none(video.get('views')), 'like_count': int_or_none(video.get('likesCount')), 'comment_count': int_or_none(video.get('commentsCount')), 'duration': int_or_none(video.get('videoDuration')), 'timestamp': int_or_none(video.get('publishDate')), 'uploader': video.get('username'), 'uploader_id': uploader_id, 'uploader_url': format_field(uploader_id, None, 'https://storyfire.com/user/%s/video'), 'episode_number': int_or_none(video.get('episodeNumber') or video.get('episode_number')), }
Base
1
def _unsmuggle_headers(self, url): """@returns (url, smuggled_data, headers)""" url, data = unsmuggle_url(url, {}) headers = self.get_param('http_headers').copy() if 'http_headers' in data: headers.update(data['http_headers']) return url, data, headers
Base
1
def _smuggle_referrer(url, referrer_url): return smuggle_url(url, {'http_headers': {'Referer': referrer_url}})
Base
1
def test_recovery_flow(self): """Test that recovery flow is linked correctly""" flow = create_test_flow() self.stage.recovery_flow = flow self.stage.save() FlowStageBinding.objects.create( target=flow, stage=self.stage, order=0, ) response = self.client.get( reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}), ) self.assertStageResponse( response, self.flow, component="ak-stage-identification", user_fields=["email"], password_fields=False, recovery_url=reverse( "authentik_core:if-flow", kwargs={"flow_slug": flow.slug}, ), show_source_labels=False, primary_action="Log in", sources=[ { "challenge": { "component": "xak-flow-redirect", "to": "/source/oauth/login/test/", "type": ChallengeTypes.REDIRECT.value, }, "icon_url": "/static/authentik/sources/default.svg", "name": "test", } ], )
Base
1
def update_bundles(inner_bundles: Set[Tuple[int, datetime, int]]): for (bundle_id, date_added, file_id) in inner_bundles: used_artifact_bundles[bundle_id] = date_added bundle_file_ids.add(file_id)
Class
2
def get_legacy_release_bundles(release: Release, dist: Optional[Distribution]): return set( ReleaseFile.objects.select_related("file") .filter( release_id=release.id, dist_id=dist.id if dist else None, # a `ReleaseFile` with `0` artifacts represents a release archive, # see the comment above the definition of `artifact_count`. artifact_count=0, # similarly the special `type` is also used for release archives. file__type=RELEASE_BUNDLE_TYPE, ) .values_list("file_id", flat=True) # TODO: this `order_by` might be incredibly slow # we want to have a hard limit on the returned bundles here. and we would # want to pick the most recently uploaded ones. that should mostly be # relevant for customers that upload multiple bundles, or are uploading # newer files for existing releases. In that case the symbolication is # already degraded, so meh... # .order_by("-file__timestamp") [:MAX_BUNDLES_QUERY] )
Class
2
def download_file(self, file_id, project: Project): rate_limited = ratelimits.is_limited( project=project, key=f"rl:ArtifactLookupEndpoint:download:{file_id}:{project.id}", limit=10, ) if rate_limited: logger.info( "notification.rate_limited", extra={"project_id": project.id, "file_id": file_id}, ) return HttpResponse({"Too many download requests"}, status=429) file = File.objects.filter(id=file_id).first() if file is None: raise Http404 try: fp = file.getfile() response = StreamingHttpResponse( iter(lambda: fp.read(4096), b""), content_type="application/octet-stream" ) response["Content-Length"] = file.size response["Content-Disposition"] = f'attachment; filename="{file.name}"' return response except OSError: raise Http404
Class
2
def url_for_file_id(self, file_id: int) -> str: # NOTE: Returning a self-route that requires authentication (via Bearer token) # is not really forward compatible with a pre-signed URL that does not # require any authentication or headers whatsoever. # This also requires a workaround in Symbolicator, as its generic http # downloader blocks "internal" IPs, whereas the internal Sentry downloader # is explicitly exempt. return f"{self.base_url}?download={file_id}"
Class
2
def download(self, debug_file_id, project): rate_limited = ratelimits.is_limited( project=project, key=f"rl:DSymFilesEndpoint:download:{debug_file_id}:{project.id}", limit=10, ) if rate_limited: logger.info( "notification.rate_limited", extra={"project_id": project.id, "project_debug_file_id": debug_file_id}, ) return HttpResponse({"Too many download requests"}, status=403) debug_file = ProjectDebugFile.objects.filter(id=debug_file_id).first() if debug_file is None: raise Http404 try: fp = debug_file.file.getfile() response = StreamingHttpResponse( iter(lambda: fp.read(4096), b""), content_type="application/octet-stream" ) response["Content-Length"] = debug_file.file.size response["Content-Disposition"] = 'attachment; filename="{}{}"'.format( posixpath.basename(debug_file.debug_id), debug_file.file_extension, ) return response except OSError: raise Http404
Class
2
def allow_cors_options_wrapper(self, request: Request, *args, **kwargs): if request.method == "OPTIONS": response = HttpResponse(status=200) response["Access-Control-Max-Age"] = "3600" # don't ask for options again for 1 hour else: response = func(self, request, *args, **kwargs) allow = ", ".join(self._allowed_methods()) response["Allow"] = allow response["Access-Control-Allow-Methods"] = allow response["Access-Control-Allow-Headers"] = ( "X-Sentry-Auth, X-Requested-With, Origin, Accept, " "Content-Type, Authentication, Authorization, Content-Encoding, " "sentry-trace, baggage, X-CSRFToken" ) response["Access-Control-Expose-Headers"] = "X-Sentry-Error, Retry-After" if request.META.get("HTTP_ORIGIN") == "null": origin = "null" # if ORIGIN header is explicitly specified as 'null' leave it alone else: origin = origin_from_request(request) if origin is None or origin == "null": response["Access-Control-Allow-Origin"] = "*" else: response["Access-Control-Allow-Origin"] = origin # If the requesting origin is a subdomain of # the application's base-hostname we should allow cookies # to be sent. basehost = options.get("system.base-hostname") if basehost and origin: if origin.endswith(basehost): response["Access-Control-Allow-Credentials"] = "true" return response
Pillar
3
def test_allow_credentials_incorrect(self): org = self.create_organization() apikey = ApiKey.objects.create(organization_id=org.id, allowed_origins="*") request = self.make_request(method="GET") request.META["HTTP_ORIGIN"] = "http://acme.example.com" request.META["HTTP_AUTHORIZATION"] = b"Basic " + base64.b64encode( apikey.key.encode("utf-8") ) response = _dummy_endpoint(request) response.render() assert "Access-Control-Allow-Credentials" not in response
Pillar
3
def _register_template( cls, template: CustomConnectorTemplate, ) -> None: """ Registers a custom connector template by converting it to a ConnectorTemplate, registering any custom functions, and adding it to the loader's template dictionary. """ connector_template = ConnectorTemplate( config=template.config, dataset=template.dataset, icon=template.icon, functions=template.functions, human_readable=template.name, ) # register custom functions if available if template.functions: register_custom_functions(template.functions) logger.info( f"Loaded functions from the custom connector template '{template.key}'" ) # register the template in the loader's template dictionary CustomConnectorTemplateLoader.get_connector_templates()[ template.key ] = connector_template
Pillar
3
def _register_template( cls, template: CustomConnectorTemplate, ) -> None: """ Registers a custom connector template by converting it to a ConnectorTemplate, registering any custom functions, and adding it to the loader's template dictionary. """ connector_template = ConnectorTemplate( config=template.config, dataset=template.dataset, icon=template.icon, functions=template.functions, human_readable=template.name, ) # register custom functions if available if template.functions: register_custom_functions(template.functions) logger.info( f"Loaded functions from the custom connector template '{template.key}'" ) # register the template in the loader's template dictionary CustomConnectorTemplateLoader.get_connector_templates()[ template.key ] = connector_template
Base
1
def register_custom_functions(script: str) -> None: """ Registers custom functions by executing the given script in a restricted environment. The script is compiled and executed with RestrictedPython, which is designed to reduce the risk of executing untrusted code. It provides a set of safe builtins to prevent malicious or unintended behavior. Args: script (str): The Python script containing the custom functions to be registered. Raises: FidesopsException: If allow_custom_connector_functions is disabled. SyntaxError: If the script contains a syntax error or uses restricted language features. Exception: If an exception occurs during the execution of the script. """ if CONFIG.security.allow_custom_connector_functions: restricted_code = compile_restricted( script, "<string>", "exec", policy=CustomRestrictingNodeTransformer ) safe_builtins["__import__"] = custom_guarded_import safe_builtins["_getitem_"] = getitem safe_builtins["staticmethod"] = staticmethod # pylint: disable=exec-used exec( restricted_code, { "__metaclass__": type, "__name__": "restricted_module", "__builtins__": safe_builtins, }, ) else: raise FidesopsException( message="The import of connector templates with custom functions is disabled by the 'security.allow_custom_connector_functions' setting." )
Pillar
3
def register_custom_functions(script: str) -> None: """ Registers custom functions by executing the given script in a restricted environment. The script is compiled and executed with RestrictedPython, which is designed to reduce the risk of executing untrusted code. It provides a set of safe builtins to prevent malicious or unintended behavior. Args: script (str): The Python script containing the custom functions to be registered. Raises: FidesopsException: If allow_custom_connector_functions is disabled. SyntaxError: If the script contains a syntax error or uses restricted language features. Exception: If an exception occurs during the execution of the script. """ if CONFIG.security.allow_custom_connector_functions: restricted_code = compile_restricted( script, "<string>", "exec", policy=CustomRestrictingNodeTransformer ) safe_builtins["__import__"] = custom_guarded_import safe_builtins["_getitem_"] = getitem safe_builtins["staticmethod"] = staticmethod # pylint: disable=exec-used exec( restricted_code, { "__metaclass__": type, "__name__": "restricted_module", "__builtins__": safe_builtins, }, ) else: raise FidesopsException( message="The import of connector templates with custom functions is disabled by the 'security.allow_custom_connector_functions' setting." )
Base
1
def visit_AnnAssign(self, node: AnnAssign) -> AST: return self.node_contents_visit(node)
Pillar
3
def visit_AnnAssign(self, node: AnnAssign) -> AST: return self.node_contents_visit(node)
Base
1
def custom_guarded_import( name: str, _globals: Optional[dict] = None, _locals: Optional[dict] = None, fromlist: Optional[Tuple[str, ...]] = None, level: int = 0, ) -> Any: """ A custom import function that prevents the import of certain potentially unsafe modules. """ if name in [ "os", "sys", "subprocess", "shutil", "socket", "importlib", "tempfile", "glob", ]: # raising SyntaxError to be consistent with exceptions thrown from other guarded functions raise SyntaxError(f"Import of '{name}' module is not allowed.") if fromlist is None: fromlist = () return __import__(name, _globals, _locals, fromlist, level)
Pillar
3
def custom_guarded_import( name: str, _globals: Optional[dict] = None, _locals: Optional[dict] = None, fromlist: Optional[Tuple[str, ...]] = None, level: int = 0, ) -> Any: """ A custom import function that prevents the import of certain potentially unsafe modules. """ if name in [ "os", "sys", "subprocess", "shutil", "socket", "importlib", "tempfile", "glob", ]: # raising SyntaxError to be consistent with exceptions thrown from other guarded functions raise SyntaxError(f"Import of '{name}' module is not allowed.") if fromlist is None: fromlist = () return __import__(name, _globals, _locals, fromlist, level)
Base
1
def _load_connector_templates(self) -> None: logger.info("Loading connectors templates from the data/saas directory") for file in os.listdir("data/saas/config"): if file.endswith(".yml"): config_file = os.path.join("data/saas/config", file) config_dict = load_config(config_file) connector_type = config_dict["type"] human_readable = config_dict["name"] try: icon = encode_file_contents(f"data/saas/icon/{connector_type}.svg") except FileNotFoundError: logger.debug( f"Could not find the expected {connector_type}.svg in the data/saas/icon/ directory, using default icon" ) icon = encode_file_contents("data/saas/icon/default.svg") # store connector template for retrieval try: FileConnectorTemplateLoader.get_connector_templates()[ connector_type ] = ConnectorTemplate( config=load_yaml_as_string(config_file), dataset=load_yaml_as_string( f"data/saas/dataset/{connector_type}_dataset.yml" ), icon=icon, functions=None, human_readable=human_readable, ) except Exception: logger.exception("Unable to load {} connector", connector_type)
Pillar
3
def _load_connector_templates(self) -> None: logger.info("Loading connectors templates from the data/saas directory") for file in os.listdir("data/saas/config"): if file.endswith(".yml"): config_file = os.path.join("data/saas/config", file) config_dict = load_config(config_file) connector_type = config_dict["type"] human_readable = config_dict["name"] try: icon = encode_file_contents(f"data/saas/icon/{connector_type}.svg") except FileNotFoundError: logger.debug( f"Could not find the expected {connector_type}.svg in the data/saas/icon/ directory, using default icon" ) icon = encode_file_contents("data/saas/icon/default.svg") # store connector template for retrieval try: FileConnectorTemplateLoader.get_connector_templates()[ connector_type ] = ConnectorTemplate( config=load_yaml_as_string(config_file), dataset=load_yaml_as_string( f"data/saas/dataset/{connector_type}_dataset.yml" ), icon=icon, functions=None, human_readable=human_readable, ) except Exception: logger.exception("Unable to load {} connector", connector_type)
Base
1
def connector_template_invalid_dataset( self, planet_express_config, planet_express_invalid_dataset, planet_express_functions, planet_express_icon, ): return create_zip_file( { "config.yml": planet_express_config, "dataset.yml": planet_express_invalid_dataset, "functions.py": planet_express_functions, "icon.svg": planet_express_icon, } )
Pillar
3
def connector_template_invalid_dataset( self, planet_express_config, planet_express_invalid_dataset, planet_express_functions, planet_express_icon, ): return create_zip_file( { "config.yml": planet_express_config, "dataset.yml": planet_express_invalid_dataset, "functions.py": planet_express_functions, "icon.svg": planet_express_icon, } )
Base
1
def connector_template_no_icon( self, planet_express_config, planet_express_dataset, planet_express_functions, ): return create_zip_file( { "config.yml": planet_express_config, "dataset.yml": planet_express_dataset, "functions.py": planet_express_functions, } )
Pillar
3
def connector_template_no_icon( self, planet_express_config, planet_express_dataset, planet_express_functions, ): return create_zip_file( { "config.yml": planet_express_config, "dataset.yml": planet_express_dataset, "functions.py": planet_express_functions, } )
Base
1
def connector_template_duplicate_icons( self, planet_express_config, planet_express_dataset, planet_express_functions, planet_express_icon, ): return create_zip_file( { "config.yml": planet_express_config, "dataset.yml": planet_express_dataset, "functions.py": planet_express_functions, "1_icon.svg": planet_express_icon, "2_icon.svg": planet_express_icon, } )
Pillar
3
def connector_template_duplicate_icons( self, planet_express_config, planet_express_dataset, planet_express_functions, planet_express_icon, ): return create_zip_file( { "config.yml": planet_express_config, "dataset.yml": planet_express_dataset, "functions.py": planet_express_functions, "1_icon.svg": planet_express_icon, "2_icon.svg": planet_express_icon, } )
Base
1
def connector_template_no_functions( self, planet_express_config, planet_express_dataset, planet_express_icon, ): return create_zip_file( { "config.yml": planet_express_config, "dataset.yml": planet_express_dataset, "icon.svg": planet_express_icon, } )
Pillar
3
def connector_template_no_functions( self, planet_express_config, planet_express_dataset, planet_express_icon, ): return create_zip_file( { "config.yml": planet_express_config, "dataset.yml": planet_express_dataset, "icon.svg": planet_express_icon, } )
Base
1
def test_register_connector_template_wrong_scope( self, api_client: TestClient, register_connector_template_url, generate_auth_header, complete_connector_template, ): CONFIG.security.allow_custom_connector_functions = True auth_header = generate_auth_header(scopes=[CLIENT_READ]) response = api_client.post( register_connector_template_url, headers=auth_header, files={ "file": ( "template.zip", complete_connector_template, "application/zip", ) }, ) assert response.status_code == 403
Pillar
3
def test_register_connector_template_wrong_scope( self, api_client: TestClient, register_connector_template_url, generate_auth_header, complete_connector_template, ): CONFIG.security.allow_custom_connector_functions = True auth_header = generate_auth_header(scopes=[CLIENT_READ]) response = api_client.post( register_connector_template_url, headers=auth_header, files={ "file": ( "template.zip", complete_connector_template, "application/zip", ) }, ) assert response.status_code == 403
Base
1
def connector_template_missing_dataset( self, planet_express_config, planet_express_functions, planet_express_icon, ): return create_zip_file( { "config.yml": planet_express_config, "functions.py": planet_express_functions, "icon.svg": planet_express_icon, } )
Pillar
3
def connector_template_missing_dataset( self, planet_express_config, planet_express_functions, planet_express_icon, ): return create_zip_file( { "config.yml": planet_express_config, "functions.py": planet_express_functions, "icon.svg": planet_express_icon, } )
Base
1
def complete_connector_template( self, planet_express_config, planet_express_dataset, planet_express_functions, planet_express_icon, ): return create_zip_file( { "config.yml": planet_express_config, "dataset.yml": planet_express_dataset, "functions.py": planet_express_functions, "icon.svg": planet_express_icon, } )
Pillar
3
def complete_connector_template( self, planet_express_config, planet_express_dataset, planet_express_functions, planet_express_icon, ): return create_zip_file( { "config.yml": planet_express_config, "dataset.yml": planet_express_dataset, "functions.py": planet_express_functions, "icon.svg": planet_express_icon, } )
Base
1
def connector_template_duplicate_configs( self, planet_express_config, planet_express_dataset, planet_express_functions, planet_express_icon, ): return create_zip_file( { "1_config.yml": planet_express_config, "2_config.yml": planet_express_config, "dataset.yml": planet_express_dataset, "functions.py": planet_express_functions, "icon.svg": planet_express_icon, } )
Pillar
3
def connector_template_duplicate_configs( self, planet_express_config, planet_express_dataset, planet_express_functions, planet_express_icon, ): return create_zip_file( { "1_config.yml": planet_express_config, "2_config.yml": planet_express_config, "dataset.yml": planet_express_dataset, "functions.py": planet_express_functions, "icon.svg": planet_express_icon, } )
Base
1
def connector_template_wrong_contents_config( self, planet_express_dataset, planet_express_functions, planet_express_icon, ): return create_zip_file( { "config.yml": "planet_express_config", "dataset.yml": planet_express_dataset, "functions.py": planet_express_functions, "icon.svg": planet_express_icon, } )
Pillar
3
def connector_template_wrong_contents_config( self, planet_express_dataset, planet_express_functions, planet_express_icon, ): return create_zip_file( { "config.yml": "planet_express_config", "dataset.yml": planet_express_dataset, "functions.py": planet_express_functions, "icon.svg": planet_express_icon, } )
Base
1
def connector_template_duplicate_datasets( self, planet_express_config, planet_express_dataset, planet_express_functions, planet_express_icon, ): return create_zip_file( { "config.yml": planet_express_config, "1_dataset.yml": planet_express_dataset, "2_dataset.yml": planet_express_dataset, "functions.py": planet_express_functions, "icon.svg": planet_express_icon, } )
Pillar
3
def connector_template_duplicate_datasets( self, planet_express_config, planet_express_dataset, planet_express_functions, planet_express_icon, ): return create_zip_file( { "config.yml": planet_express_config, "1_dataset.yml": planet_express_dataset, "2_dataset.yml": planet_express_dataset, "functions.py": planet_express_functions, "icon.svg": planet_express_icon, } )
Base
1
def connector_template_invalid_config( self, planet_express_invalid_config, planet_express_dataset, planet_express_functions, planet_express_icon, ): return create_zip_file( { "config.yml": planet_express_invalid_config, "dataset.yml": planet_express_dataset, "functions.py": planet_express_functions, "icon.svg": planet_express_icon, } )
Pillar
3
def connector_template_invalid_config( self, planet_express_invalid_config, planet_express_dataset, planet_express_functions, planet_express_icon, ): return create_zip_file( { "config.yml": planet_express_invalid_config, "dataset.yml": planet_express_dataset, "functions.py": planet_express_functions, "icon.svg": planet_express_icon, } )
Base
1
def test_register_connector_template_allow_custom_connector_functions( self, mock_register_custom_functions: MagicMock, api_client: TestClient, register_connector_template_url, generate_auth_header, zip_file, status_code, details, request, ): CONFIG.security.allow_custom_connector_functions = True auth_header = generate_auth_header(scopes=[CONNECTOR_TEMPLATE_REGISTER]) response = api_client.post( register_connector_template_url, headers=auth_header, files={ "file": ( "template.zip", request.getfixturevalue(zip_file).read(), "application/zip", ) }, ) assert response.status_code == status_code assert response.json() == details
Pillar
3
def test_register_connector_template_allow_custom_connector_functions( self, mock_register_custom_functions: MagicMock, api_client: TestClient, register_connector_template_url, generate_auth_header, zip_file, status_code, details, request, ): CONFIG.security.allow_custom_connector_functions = True auth_header = generate_auth_header(scopes=[CONNECTOR_TEMPLATE_REGISTER]) response = api_client.post( register_connector_template_url, headers=auth_header, files={ "file": ( "template.zip", request.getfixturevalue(zip_file).read(), "application/zip", ) }, ) assert response.status_code == status_code assert response.json() == details
Base
1