code
stringlengths
12
2.05k
label_name
stringlengths
6
8
label
int64
0
95
def __init__(self, text, book): self.text = text self.book = book
CWE-918
16
def modify_identifiers(input_identifiers, db_identifiers, db_session): """Modify Identifiers to match input information. input_identifiers is a list of read-to-persist Identifiers objects. db_identifiers is a list of already persisted list of Identifiers objects.""" changed = False error = Fal...
CWE-918
16
def test_underscore_traversal(self): # Prevent traversal to names starting with an underscore (_) ec = self._makeContext() with self.assertRaises(NotFound): ec.evaluate("context/__class__") with self.assertRaises(NotFound): ec.evaluate("nocall: random/_itert...
CWE-22
2
def jstree_data(node, selected_node): result = [] result.append('{') result.append('"text": "{}",'.format(node.label)) result.append( '"state": {{ "opened": true, "selected": {} }},'.format( 'true' if node == selected_node else 'false' ) ) result.append( '"dat...
CWE-79
1
def get_info_for_package(pkg, channel_id, org_id): log_debug(3, pkg) pkg = map(str, pkg) params = {'name': pkg[0], 'ver': pkg[1], 'rel': pkg[2], 'epoch': pkg[3], 'arch': pkg[4], 'channel_id': channel_id, 'org_id': org_id} ...
CWE-79
1
def test_process_request__multiple_files(self, rf): storage.save("tmp/s3file/s3_file.txt", ContentFile(b"s3file")) storage.save("tmp/s3file/s3_other_file.txt", ContentFile(b"other s3file")) request = rf.post( "/", data={ "file": [ "...
CWE-22
2
def __init__(self, expression, delimiter, **extra): super().__init__(expression, delimiter=delimiter, **extra)
CWE-89
0
def authenticate(self, request, username=None, code=None, **kwargs): if username is None: username = kwargs.get(get_user_model().USERNAME_FIELD) if not username or not code: return try: user = get_user_model()._default_manager.get_by_natural_key(username...
CWE-312
71
def is_whitelisted(self, method): fn = getattr(self, method, None) if not fn: raise NotFound("Method {0} not found".format(method)) elif not getattr(fn, "whitelisted", False): raise Forbidden("Method {0} not whitelisted".format(method))
CWE-79
1
def make_homeserver(self, reactor, clock): self.http_client = Mock() return self.setup_test_homeserver(http_client=self.http_client)
CWE-601
11
async def ignore_global(self, ctx, command: str.lower): """ Globally ignore or unignore the specified action. The bot will no longer respond to these actions. """ try: await self.config.get_raw("custom", command) except KeyError: awai...
CWE-502
15
def close_or_open(request, pk, close=True): # todo: moderators should be able to close it poll = get_object_or_404( CommentPoll, pk=pk, comment__user=request.user ) if close: close_at = timezone.now() else: close_at = None (CommentPoll.objects .filt...
CWE-601
11
def show_book(book_id): entries = calibre_db.get_book_read_archived(book_id, config.config_read_column, allow_show_archived=True) if entries: read_book = entries[1] archived_book = entries[2] entry = entries[0] entry.read_status = read_book == ub.ReadBook.STATUS_FINISHED ...
CWE-918
16
def test_received_headers_finished_expect_continue_true_sent_true(self): inst, sock, map = self._makeOneWithMap() inst.server = DummyServer() preq = DummyParser() inst.request = preq preq.expect_continue = True preq.headers_finished = True preq.completed = Fal...
CWE-444
41
def test_remote_cors(app): """Test endpoint that serves as a proxy to the actual remote track on the cloud""" cloud_track_url = "http://google.com" # GIVEN an initialized app # GIVEN a valid user and institute with app.test_client() as client: # GIVEN that the user could be logged in ...
CWE-918
16
def test_credits_view_html(self): response = self.get_credits("html") self.assertEqual(response.status_code, 200) self.assertHTMLEqual( response.content.decode(), "<table>\n" "<tr>\n<th>Czech</th>\n" '<td><ul><li><a href="mailto:weblate@example...
CWE-79
1
def read_fixed_bytes(self, num_bytes: int) -> bytes: """Reads a fixed number of bytes from the underlying bytestream. Args: num_bytes The number of bytes to read. Returns: The read bytes. Raises: EOFError: Fewer than ``num_bytes`...
CWE-209
31
def __new__(cls, sourceName: str): """Dispatches to the right subclass.""" if cls != InputSource: # Only take control of calls to InputSource(...) itself. return super().__new__(cls) if sourceName == "-": return StdinInputSource(sourceName) if sou...
CWE-22
2
def category_list(): if current_user.check_visibility(constants.SIDEBAR_CATEGORY): if current_user.get_view_property('category', 'dir') == 'desc': order = db.Tags.name.desc() order_no = 0 else: order = db.Tags.name.asc() order_no = 1 entries = ...
CWE-918
16
def setUp(self): self.mock_resource = MockHttpResource(prefix=PATH_PREFIX) self.mock_handler = Mock( spec=[ "get_displayname", "set_displayname", "get_avatar_url", "set_avatar_url", "check_profile_query_allow...
CWE-601
11
def testComplexGET(self): data = b"""\ GET /foo/a+%2B%2F%C3%A4%3D%26a%3Aint?d=b+%2B%2F%3D%26b%3Aint&c+%2B%2F%3D%26c%3Aint=6 HTTP/8.4 FirstName: mickey lastname: Mouse content-length: 10 Hello mickey. """ parser = self.parser self.feed(data) self.assertEqual(parser.command, "GET") ...
CWE-444
41
def is_valid_client_secret(client_secret): """Validate that a given string matches the client_secret regex defined by the spec :param client_secret: The client_secret to validate :type client_secret: unicode :return: Whether the client_secret is valid :rtype: bool """ return client_secret_...
CWE-918
16
def add_security_headers(resp): resp.headers['Content-Security-Policy'] = "default-src 'self'" + ''.join([' '+host for host in config.config_trustedhosts.strip().split(',')]) + " 'unsafe-inline' 'unsafe-eval'; font-src 'self' data:; img-src 'self' data:" if request.endpoint == "editbook.edit_book" or config.con...
CWE-918
16
def setUp(self): self.mock_federation = Mock() self.mock_registry = Mock() self.query_handlers = {} def register_query_handler(query_type, handler): self.query_handlers[query_type] = handler self.mock_registry.register_query_handler = register_query_handler ...
CWE-601
11
def check_valid_read_column(column): if column != "0": if not calibre_db.session.query(db.Custom_Columns).filter(db.Custom_Columns.id == column) \ .filter(and_(db.Custom_Columns.datatype == 'bool', db.Custom_Columns.mark_for_delete == 0)).all(): return False return True
CWE-918
16
def feed_unread_books(): off = request.args.get("offset") or 0 result, pagination = render_read_books(int(off) / (int(config.config_books_per_page)) + 1, False, True) return render_xml_template('feed.xml', entries=result, pagination=pagination)
CWE-918
16
def screenshotcommentcounts(context, screenshot): """ Returns a JSON array of current comments for a screenshot. Each entry in the array has a dictionary containing the following keys: =========== ================================================== Key Description =========== ====...
CWE-79
1
def parse_soap_enveloped_saml(text, body_class, header_class=None): """Parses a SOAP enveloped SAML thing and returns header parts and body :param text: The SOAP object as XML :return: header parts and body as saml.samlbase instances """ envelope = ElementTree.fromstring(text) assert envelope.t...
CWE-611
13
def connect(self, port=None): ''' connect to the chroot; nothing to do here ''' vvv("THIS IS A LOCAL CHROOT DIR", host=self.jail) return self
CWE-59
36
def test_filelike_http10(self): to_send = "GET /filelike HTTP/1.0\n\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1....
CWE-444
41
def test_value_from_datadict(self, client, upload_file): print(storage.location) with open(upload_file) as f: uploaded_file = storage.save("test.jpg", f) response = client.post( reverse("upload"), { "file": json.dumps([uploaded_file]), ...
CWE-22
2
def recovery_parser(xml): parser = XMLParser(recover=True) return parse(BytesIO(xml), parser)
CWE-611
13
def emit(self, s, depth, reflow=True): # XXX reflow long lines? if reflow: lines = reflow_lines(s, depth) else: lines = [s] for line in lines: line = (" " * TABSIZE * depth) + line + "\n" self.file.write(line)
CWE-125
47
def MD5(self,data:str): sha = hashlib.md5(bytes(data.encode())) hash = str(sha.digest()) return self.__Salt(hash,salt=self.salt)
CWE-328
75
def mysql_insensitive_contains(field: Field, value: str) -> Criterion: return functions.Upper(functions.Cast(field, SqlTypes.CHAR)).like(functions.Upper(f"%{value}%"))
CWE-89
0
def formatType(self): format_type = self.type.lower() if format_type == 'amazon': return u"Amazon" elif format_type.startswith("amazon_"): return u"Amazon.{0}".format(format_type[7:]) elif format_type == "isbn": return u"ISBN" elif format_t...
CWE-918
16
async def customize_global(self, ctx, command: str.lower, *, response: str = None): """ Globally customize the response to an action. You can use {0} or {user} to dynamically replace with the specified target of the action. Formats like {0.name} or {0.mention} can also be used....
CWE-502
15
def get_current_phase(self, requested_phase_identifier): found = False for phase in self.phases: if phase.is_valid(): phase.process() if found or not requested_phase_identifier or requested_phase_identifier == phase.identifier: found = True # ...
CWE-79
1
def make_sydent(test_config={}): """Create a new sydent Args: test_config (dict): any configuration variables for overriding the default sydent config """ # Use an in-memory SQLite database. Note that the database isn't cleaned up between # tests, so by default the same database...
CWE-918
16
def whitelist(allow_guest=False, xss_safe=False, methods=None): """ Decorator for whitelisting a function and making it accessible via HTTP. Standard request will be `/api/method/[path.to.method]` :param allow_guest: Allow non logged-in user to access this method. :param methods: Allowed http method to access the...
CWE-79
1
def test_without_crlf(self): data = "Echo\nthis\r\nplease" s = tobytes( "GET / HTTP/1.0\n" "Connection: close\n" "Content-Length: %d\n" "\n" "%s" % (len(data), data) ) self.connect() self.sock.send(s) fp = se...
CWE-444
41
def edit(request, user_id): user = get_object_or_404(User, pk=user_id) uform = UserForm(data=post_data(request), instance=user) form = UserProfileForm(data=post_data(request), instance=user.st) if is_post(request) and all([uform.is_valid(), form.is_valid()]): uform.save() form.save() ...
CWE-601
11
def test_received_control_line_finished_all_chunks_not_received(self): buf = DummyBuffer() inst = self._makeOne(buf) result = inst.received(b"a;discard\n") self.assertEqual(inst.control_line, b"") self.assertEqual(inst.chunk_remainder, 10) self.assertEqual(inst.all_ch...
CWE-444
41
def check_read_formats(entry): EXTENSIONS_READER = {'TXT', 'PDF', 'EPUB', 'CBZ', 'CBT', 'CBR', 'DJVU'} bookformats = list() if len(entry.data): for ele in iter(entry.data): if ele.format.upper() in EXTENSIONS_READER: bookformats.append(ele.format.lower()) return bookf...
CWE-918
16
def run_query(self, query, user): query = parse_query(query) if not isinstance(query, dict): raise QueryParseError( "Query should be a YAML object describing the URL to query." ) if "url" not in query: raise QueryParseError("Query must in...
CWE-918
16
def mark_all_as_read(request): (TopicNotification.objects .for_access(request.user) .filter(is_read=False) .update(is_read=True)) return redirect(request.POST.get( 'next', reverse('spirit:topic:notification:index')))
CWE-601
11
def generate_config_section(self, config_dir_path, server_name, **kwargs): return """\ ## Federation ## # Restrict federation to the following whitelist of domains. # N.B. we recommend also firewalling your federation listener to limit # inbound federation traffic as early a...
CWE-601
11
def count(cls, **kwargs): """Return a count of server side resources given filtering arguments in kwargs. """ url = urljoin(recurly.base_uri(), cls.collection_path) if kwargs: url = '%s?%s' % (url, urlencode(kwargs)) return Page.count_for_url(url)
CWE-918
16
def check_prereg_key_and_redirect( request: HttpRequest, confirmation_key: str, full_name: Optional[str] = REQ(default=None)
CWE-613
7
def test_filename(self): tmpname = mktemp('', 'mmap') fp = memmap(tmpname, dtype=self.dtype, mode='w+', shape=self.shape) abspath = os.path.abspath(tmpname) fp[:] = self.data[:] self.assertEqual(abspath, fp.filename) b = fp[:1] self.asse...
CWE-59
36
async def customize(self, ctx, command: str.lower, *, response: str = None): """ Customize the response to an action. You can use {0} or {user} to dynamically replace with the specified target of the action. Formats like {0.name} or {0.mention} can also be used. """ ...
CWE-502
15
def test_notfilelike_nocl_http10(self): to_send = "GET /notfilelike_nocl HTTP/1.0\n\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response_body = read_http(fp) self.assertline(line, "200"...
CWE-444
41
def test_get_files_from_storage(self): content = b"test_get_files_from_storage" name = storage.save( "tmp/s3file/test_get_files_from_storage", ContentFile(content) ) files = S3FileMiddleware.get_files_from_storage( [os.path.join(storage.aws_location, name)] ...
CWE-22
2
def test_unicorn_render_context_variable(): token = Token( TokenType.TEXT, "unicorn 'tests.templatetags.test_unicorn_render.FakeComponentKwargs' test_kwarg=test_var.nested", ) unicorn_node = unicorn(None, token) context = {"test_var": {"nested": "variable!"}} actual = unicorn_node.re...
CWE-79
1
def _parse_a_camel_date_time(data: Dict[str, Any]) -> Union[datetime, date]: a_camel_date_time: Union[datetime, date] try: a_camel_date_time = datetime.fromisoformat(d["aCamelDateTime"]) return a_camel_date_time except: pass ...
CWE-94
14
def __init__(self, expire_on_commit=True): """ Initialize a new CalibreDB session """ self.session = None if self._init: self.initSession(expire_on_commit) self.instances.add(self)
CWE-918
16
def save_cover_from_url(url, book_path): try: if not cli.allow_localhost: # 127.0.x.x, localhost, [::1], [::ffff:7f00:1] ip = socket.getaddrinfo(urlparse(url).hostname, 0)[0][4][0] if ip.startswith("127.") or ip.startswith('::ffff:7f') or ip == "::1" or ip == "0.0.0.0" or...
CWE-918
16
def test_big_arrays(self): L = (1 << 31) + 100000 tmp = mktemp(suffix='.npz') a = np.empty(L, dtype=np.uint8) np.savez(tmp, a=a) del a npfile = np.load(tmp) a = npfile['a'] npfile.close() os.remove(tmp)
CWE-59
36
def org_login(org_slug): session["org_slug"] = current_org.slug return redirect(url_for(".authorize", next=request.args.get("next", None)))
CWE-601
11
def test_received_chunked_completed_sets_content_length(self): data = b"""\ GET /foobar HTTP/1.1 Transfer-Encoding: chunked X-Foo: 1 20;\r\n This string has 32 characters\r\n 0\r\n\r\n""" result = self.parser.received(data) self.assertEqual(result, 58) data = data[result:] r...
CWE-444
41
def list_users(): off = int(request.args.get("offset") or 0) limit = int(request.args.get("limit") or 10) search = request.args.get("search") sort = request.args.get("sort", "id") state = None if sort == "state": state = json.loads(request.args.get("state", "[]")) else: if so...
CWE-918
16
def insensitive_contains(field: Term, value: str) -> Criterion: return Upper(field).like(Upper(f"%{value}%"))
CWE-89
0
def get_paths(base_path: pathlib.Path): data_file = pathlib.Path(str(base_path) + ".data") metadata_file = pathlib.Path(str(base_path) + ".meta") return data_file, metadata_file
CWE-22
2
def set_bookmark(book_id, book_format): bookmark_key = request.form["bookmark"] ub.session.query(ub.Bookmark).filter(and_(ub.Bookmark.user_id == int(current_user.id), ub.Bookmark.book_id == book_id, ub.Bookmark.format ==...
CWE-918
16
def save_cover_from_url(url, book_path): try: if not cli.allow_localhost: # 127.0.x.x, localhost, [::1], [::ffff:7f00:1] ip = socket.getaddrinfo(urlparse(url).hostname, 0)[0][4][0] if ip.startswith("127.") or ip.startswith('::ffff:7f') or ip == "::1": log....
CWE-918
16
def test_received_nonsense_with_double_cr(self): data = b"""\ HTTP/1.0 GET /foobar """ result = self.parser.received(data) self.assertEqual(result, 22) self.assertTrue(self.parser.completed) self.assertEqual(self.parser.headers, {})
CWE-444
41
def test_scatter_ops_even_partition(self, op): v = variables_lib.Variable(array_ops.zeros((30, 1))) sparse_delta = ops.IndexedSlices( values=constant_op.constant([[0.], [1.], [2.], [3.], [4.]]), indices=constant_op.constant([0, 10, 12, 21, 22])) v0 = variables_lib.Variable(array_ops.zeros...
CWE-369
60
def test_underscore_traversal(self): t = self.folder.t t.write('<p tal:define="p context/__class__" />') with self.assertRaises(NotFound): t() t.write('<p tal:define="p nocall: random/_itertools/repeat"/>') with self.assertRaises(NotFound): t() ...
CWE-22
2
def _inject_net_into_fs(net, fs, execute=None): """Inject /etc/network/interfaces into the filesystem rooted at fs. net is the contents of /etc/network/interfaces. """ netdir = os.path.join(os.path.join(fs, 'etc'), 'network') utils.execute('mkdir', '-p', netdir, run_as_root=True) utils.execute(...
CWE-22
2
def test_process_request__no_location(self, rf, settings): settings.AWS_LOCATION = "" uploaded_file = SimpleUploadedFile("uploaded_file.txt", b"uploaded") request = rf.post("/", data={"file": uploaded_file}) S3FileMiddleware(lambda x: None)(request) assert request.FILES.getli...
CWE-22
2
def publisher_list(): if current_user.get_view_property('publisher', 'dir') == 'desc': order = db.Publishers.name.desc() order_no = 0 else: order = db.Publishers.name.asc() order_no = 1 if current_user.check_visibility(constants.SIDEBAR_PUBLISHER): entries = calibre_d...
CWE-918
16
def test_can_read_token_from_headers(self): """Tests that Sydent correct extracts an auth token from request headers""" self.sydent.run() request, _ = make_request( self.sydent.reactor, "GET", "/_matrix/identity/v2/hash_details" ) request.requestHeaders.addRawHea...
CWE-918
16
def config_basic(request): form = BasicConfigForm(data=post_data(request)) if is_post(request) and form.is_valid(): form.save() messages.info(request, _("Settings updated!")) return redirect(request.GET.get("next", request.get_full_path())) return render( request=request, ...
CWE-601
11
def add_security_headers(resp): resp.headers['Content-Security-Policy'] = "default-src 'self'" + ''.join([' '+host for host in config.config_trustedhosts.strip().split(',')]) + " 'unsafe-inline' 'unsafe-eval'; font-src 'self' data:; img-src 'self' data:" if request.endpoint == "editbook.edit_book" or config.con...
CWE-918
16
def parse(source, filename='<unknown>', mode='exec'): """ Parse the source into an AST node. Equivalent to compile(source, filename, mode, PyCF_ONLY_AST). """ return compile(source, filename, mode, PyCF_ONLY_AST)
CWE-125
47
def contains(field: Term, value: str) -> Criterion: return field.like(f"%{value}%")
CWE-89
0
def make_homeserver(self, reactor, clock): self.push_attempts = [] m = Mock() def post_json_get_json(url, body): d = Deferred() self.push_attempts.append((d, url, body)) return make_deferred_yieldable(d) m.post_json_get_json = post_json_get_json...
CWE-601
11
def update(self, **kwargs): consumer_id = load_consumer_id(self.context) if not consumer_id: self.prompt.render_failure_message("This consumer is not registered to the Pulp server.") return delta = dict([(k, v) for k, v in kwargs.items() if v is not None]) if...
CWE-295
52
async def check_credentials(username, password): return password == "iloveyou"
CWE-203
38
def edit_book_languages(languages, book, upload=False, invalid=None): input_languages = languages.split(',') unknown_languages = [] if not upload: input_l = isoLanguages.get_language_codes(get_locale(), input_languages, unknown_languages) else: input_l = isoLanguages.get_valid_language_c...
CWE-918
16
def check_valid_restricted_column(column): if column != "0": if not calibre_db.session.query(db.Custom_Columns).filter(db.Custom_Columns.id == column) \ .filter(and_(db.Custom_Columns.datatype == 'text', db.Custom_Columns.mark_for_delete == 0)).all(): return False return True
CWE-918
16
def get(cls, uuid): """Return a `Resource` instance of this class identified by the given code or UUID. Only `Resource` classes with specified `member_path` attributes can be directly requested with this method. """ url = urljoin(recurly.base_uri(), cls.member_path ...
CWE-918
16
def parse_soap_enveloped_saml_thingy(text, expected_tags): """Parses a SOAP enveloped SAML thing and returns the thing as a string. :param text: The SOAP object as XML string :param expected_tags: What the tag of the SAML thingy is expected to be. :return: SAML thingy as a string """ envelo...
CWE-611
13
def get_json(self, uri): """Make a GET request to an endpoint returning JSON and parse result :param uri: The URI to make a GET request to. :type uri: unicode :return: A deferred containing JSON parsed into a Python object. :rtype: twisted.internet.defer.Deferred[dict[any, ...
CWE-770
37
def test_received_preq_not_completed(self): inst, sock, map = self._makeOneWithMap() inst.server = DummyServer() preq = DummyParser() inst.request = preq preq.completed = False preq.empty = True inst.received(b"GET / HTTP/1.1\n\n") self.assertEqual(ins...
CWE-444
41
def _inject_key_into_fs(key, fs, execute=None): """Add the given public ssh key to root's authorized_keys. key is an ssh key string. fs is the path to the base of the filesystem into which to inject the key. """ sshdir = os.path.join(fs, 'root', '.ssh') utils.execute('mkdir', '-p', sshdir, run_...
CWE-22
2
def test_proxy_headers(self): to_send = ( "GET / HTTP/1.0\n" "Content-Length: 0\n" "Host: www.google.com:8080\n" "X-Forwarded-For: 192.168.1.1\n" "X-Forwarded-Proto: https\n" "X-Forwarded-Port: 5000\n\n" ) to_send = toby...
CWE-444
41
def create_class_from_xml_string(target_class, xml_string): """Creates an instance of the target class from a string. :param target_class: The class which will be instantiated and populated with the contents of the XML. This class must have a c_tag and a c_namespace class variable. :param x...
CWE-611
13
def is_valid_hostname(string: str) -> bool: """Validate that a given string is a valid hostname or domain name, with an optional port number. For domain names, this only validates that the form is right (for instance, it doesn't check that the TLD is valid). If a port is specified, it has to be a v...
CWE-918
16
def __init__(self, hs): self.hs = hs self.auth = hs.get_auth() self.client = hs.get_http_client() self.clock = hs.get_clock() self.server_name = hs.hostname self.store = hs.get_datastore() self.max_upload_size = hs.config.max_upload_size self.max_image...
CWE-601
11
def feed_ratingindex(): off = request.args.get("offset") or 0 entries = calibre_db.session.query(db.Ratings, func.count('books_ratings_link.book').label('count'), (db.Ratings.rating / 2).label('name')) \ .join(db.books_ratings_link)\ .join(db.Books)\ .filte...
CWE-918
16
def test_notfilelike_longcl_http11(self): to_send = "GET /notfilelike_longcl HTTP/1.1\n\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response_body = read_http(fp) self.assertline(line, "...
CWE-444
41
def gravatar(context, user, size=None): """ Outputs the HTML for displaying a user's gravatar. This can take an optional size of the image (defaults to 80 if not specified). This is also influenced by the following settings: GRAVATAR_SIZE - Default size for gravatars GRAVATAR_R...
CWE-79
1
def get(self, path: str) -> None: parts = path.split("/") component_name = parts[0] component_root = self._registry.get_component_path(component_name) if component_root is None: self.write("not found") self.set_status(404) return filename ...
CWE-22
2
def json_dumps(value, indent=None): if isinstance(value, QuerySet): result = serialize('json', value, indent=indent) else: result = json.dumps(value, indent=indent, cls=DjbletsJSONEncoder) return mark_safe(result)
CWE-79
1
def del_version(request, client_id, project, version): if request.method == 'GET': client = Client.objects.get(id=client_id) try: scrapyd = get_scrapyd(client) result = scrapyd.delete_version(project=project, version=version) return JsonResponse(result) ex...
CWE-78
6
def get_response(self, url, auth=None, http_method="get", **kwargs): if is_private_address(url) and settings.ENFORCE_PRIVATE_ADDRESS_BLOCK: raise Exception("Can't query private addresses.") # Get authentication values if not given if auth is None: auth = self.get_aut...
CWE-918
16
def edit_single_cc_data(book_id, book, column_id, to_save): cc = (calibre_db.session.query(db.Custom_Columns) .filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)) .filter(db.Custom_Columns.id == column_id) .all()) return edit_cc_data(book_id, book, to_save, cc)
CWE-918
16
def testStringNGramsBadDataSplits(self, splits): data = ["aa", "bb", "cc", "dd", "ee", "ff"] with self.assertRaisesRegex(errors.InvalidArgumentError, "Invalid split value"): self.evaluate( gen_string_ops.string_n_grams( data=data, dat...
CWE-190
19
def feed_categoryindex(): shift = 0 off = int(request.args.get("offset") or 0) entries = calibre_db.session.query(func.upper(func.substr(db.Tags.name, 1, 1)).label('id'))\ .join(db.books_tags_link).join(db.Books).filter(calibre_db.common_filters())\ .group_by(func.upper(func.substr(db.Tags.n...
CWE-918
16