Skip to content

Files

FilesAPI

Interface for interacting with the /api/v1/files CTFd API endpoint.

Source code in ctfdpy\api\files.py
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
class FilesAPI:
    """
    Interface for interacting with the `/api/v1/files` CTFd API endpoint.
    """

    def __init__(self, client: APIClient):
        self._client = client

    @admin_only
    def list(
        self,
        *,
        type: FileType | None = None,
        location: str | None = None,
        q: str | None = None,
        field: Literal["type", "location"] | None = None,
    ) -> list[StandardFile | ChallengeFile | PageFile]:
        """
        !!! note "This method is only available to admins"

        List all files with optional filtering.

        Parameters
        ----------
        type: FileType | None
            The type of file to filter by, defaults to None.
        location: str | None
            The location of the file to filter by, defaults to None.
        q: str | None
            The query string to search for, defaults to None.
        field: Literal["type", "location"] | None
            The field to search in, defaults to None.

        Returns
        -------
        list[StandardFile | ChallengeFile | PageFile]
            A list of files that match the query.

        Raises
        ------
        ValueError
            If q and field are not provided together.
        BadRequest
            An error occurred processing the provided or stored data.
        AuthenticationRequired
            You must be logged in to access this resource.
        AdminOnly
            You must be an admin to access this resource.

        Examples
        --------
        Get all files:

        ```python
        files = ctfd.files.list()
        ```

        Get all challenge files:

        ```python
        files = ctfd.files.list(type=FileType.CHALLENGE)
        ```
        """
        # Check if q and field are both provided or both not provided
        if q is None != field is None:
            raise ValueError("q and field must be provided together")

        params = {}
        if type is not None:
            params["type"] = type.value
        if location is not None:
            params["location"] = location
        if q is not None:
            params["q"] = q
            params["field"] = field

        return self._client.request(
            "GET",
            "/api/v1/files",
            params=params,
            response_model=list_file_adapter,
            error_models={400: BadRequest, 401: Unauthorized, 403: Forbidden},
        )

    @admin_only
    async def async_list(
        self,
        *,
        type: FileType | None = None,
        location: str | None = None,
        q: str | None = None,
        field: Literal["type", "location"] | None = None,
    ) -> list[StandardFile | ChallengeFile | PageFile]:
        """
        !!! note "This method is only available to admins"

        List all files with optional filtering.

        Parameters
        ----------
        type: FileType | None
            The type of file to filter by, defaults to None.
        location: str | None
            The location of the file to filter by, defaults to None.
        q: str | None
            The query string to search for, defaults to None.
        field: Literal["type", "location"] | None
            The field to search in, defaults to None.

        Returns
        -------
        list[StandardFile | ChallengeFile | PageFile]
            A list of files that match the query.

        Raises
        ------
        ValueError
            If q and field are both provided or both not provided.
        BadRequest
            An error occurred processing the provided or stored data.
        AuthenticationRequired
            You must be logged in to access this resource.
        AdminOnly
            You must be an admin to access this resource.

        Examples
        --------
        Get all files:

        ```python
        files = await ctfd.files.async_list()
        ```

        Get all challenge files:

        ```python
        files = await ctfd.files.async_list(type=FileType.CHALLENGE)
        ```
        """
        # Check if q and field are both provided or both not provided
        if q is None != field is None:
            raise ValueError("q and field must be provided together")

        params = {}
        if type is not None:
            params["type"] = type.value
        if location is not None:
            params["location"] = location
        if q is not None:
            params["q"] = q
            params["field"] = field

        return await self._client.arequest(
            "GET",
            "/api/v1/files",
            params=params,
            response_model=list_file_adapter,
            error_models={400: BadRequest, 401: Unauthorized, 403: Forbidden},
        )

    @overload
    def create(
        self, *, payload: CreateFilePayload
    ) -> list[StandardFile | ChallengeFile | PageFile]: ...

    @overload
    async def async_create(
        self, *, payload: CreateFilePayload
    ) -> list[StandardFile | ChallengeFile | PageFile]: ...

    @overload
    def create(
        self,
        *,
        files: list[MultipartFileTypes] | None = None,
        file_paths: list[str | os.PathLike] | None = None,
        type: FileType = FileType.STANDARD,
        challenge_id: int | None = None,
        challenge: int | None = None,
        page_id: int | None = None,
        page: int | None = None,
        location: str | None = None,
    ) -> list[StandardFile | ChallengeFile | PageFile]: ...

    @overload
    async def async_create(
        self,
        *,
        files: list[MultipartFileTypes] | None = None,
        file_paths: list[str | os.PathLike] | None = None,
        type: FileType = FileType.STANDARD,
        challenge_id: int | None = None,
        challenge: int | None = None,
        page_id: int | None = None,
        page: int | None = None,
        location: str | None = None,
    ) -> list[StandardFile | ChallengeFile | PageFile]: ...

    @admin_only
    def create(
        self,
        *,
        payload: CreateFilePayload = MISSING,
        files: list[MultipartFileTypes] | None = None,
        file_paths: list[str | os.PathLike] | None = None,
        type: FileType | None = None,
        challenge_id: int | None = None,
        challenge: int | None = None,
        page_id: int | None = None,
        page: int | None = None,
        location: str | None = None,
    ) -> list[StandardFile | ChallengeFile | PageFile]:
        """
        !!! note "This method is only available to admins"

        Create a new file.

        Parameters
        ----------
        payload: CreateFilePayload
            The payload to create the file with. If this is provided, no other parameter should be provided.
        files: list[MultipartFileTypes] | None
            The files to upload. This can either be a `#!python FileContent` or a tuple of length between 2 and 4
            in the format `(filename, file, content_type, headers)`. Defaults to None.
        file_paths: list[str | os.PathLike] | None
            The paths to the files to upload. Defaults to None.
        type: FileType | None
            The type of the file, defaults to None.
        challenge_id: int | None
            The ID of the challenge to associate the file with, defaults to None.
        page_id: int | None
            The ID of the page to associate the file with, defaults to None.
        location: str | None
            The location on the server to upload the files to, defaults to None.

        Returns
        -------
        list[StandardFile | ChallengeFile | PageFile]
            The files that were created.

        Raises
        ------
        ValueError
            If no files are provided.
        FileNotFoundError
            If a file path does not exist.
        ModelValidationError
            If the payload is invalid.
        BadRequest
            An error occurred processing the provided or stored data.
        AuthenticationRequired
            You must be logged in to access this resource.
        AdminOnly
            You must be an admin to access this resource.

        Examples
        --------
        Create a file for a challenge:

        ```python
        files = ctfd.files.create(
            files=[("filename.txt", open("/path/to/file.txt", "rb"))],
            type=FileType.CHALLENGE,
            challenge_id=1,
        )
        ```
        """
        if payload is MISSING:
            files = files or []

            if file_paths is not None:
                for file_path in file_paths:
                    file_path = Path(file_path)
                    if not file_path.exists():
                        raise FileNotFoundError(f"File not found: {file_path}")
                    files.append((file_path.name, file_path.open("rb")))

            if len(files) == 0:
                raise ValueError("At least one file must be provided")

            try:
                payload = CreateFilePayload(
                    files=files,
                    type=type,
                    challenge_id=challenge_id or challenge,
                    page_id=page_id or page,
                    location=location,
                )
            except ValidationError as e:
                raise ModelValidationError(e.errors()) from e

        return self._client.request(
            "POST",
            "/api/v1/files",
            files=payload.dump_json(),
            response_model=list_file_adapter,
            error_models={400: BadRequest, 401: Unauthorized, 403: Forbidden},
        )

    @admin_only
    async def async_create(
        self,
        *,
        payload: CreateFilePayload = MISSING,
        files: list[MultipartFileTypes] | None = None,
        file_paths: list[str | os.PathLike] | None = None,
        type: FileType | None = None,
        challenge_id: int | None = None,
        challenge: int | None = None,
        page_id: int | None = None,
        page: int | None = None,
        location: str | None = None,
    ) -> list[StandardFile | ChallengeFile | PageFile]:
        """
        !!! note "This method is only available to admins"

        Create a new file.

        Parameters
        ----------
        payload: CreateFilePayload
            The payload to create the file with. If this is provided, no other parameter should be provided.
        files: list[MultipartFileTypes] | None
            The files to upload. This can either be a `#!python FileContent` or a tuple of length between 2 and 4
            in the format `(filename, file, content_type, headers)`. Defaults to None.
        file_paths: list[str | os.PathLike] | None
            The paths to the files to upload. Defaults to None.
        type: FileType | None
            The type of the file, defaults to None.
        challenge_id: int | None
            The ID of the challenge to associate the file with, defaults to None.
        page_id: int | None
            The ID of the page to associate the file with, defaults to None.
        location: str | None
            The location on the server to upload the files to, defaults to None.

        Returns
        -------
        list[StandardFile | ChallengeFile | PageFile]
            The files that were created.

        Raises
        ------
        ValueError
            If no files are provided.
        FileNotFoundError
            If a file path does not exist.
        ModelValidationError
            If the payload is invalid.
        BadRequest
            An error occurred processing the provided or stored data.
        AuthenticationRequired
            You must be logged in to access this resource.
        AdminOnly
            You must be an admin to access this resource.

        Examples
        --------
        Create a file for a challenge:

        ```python
        files = await ctfd.files.async_create(
            files=[("filename.txt", open("/path/to/file.txt", "rb"))],
            type=FileType.CHALLENGE,
            challenge_id=1,
        )
        ```
        """
        if payload is MISSING:
            files = files or []

            if file_paths is not None:
                for file_path in file_paths:
                    file_path = Path(file_path)
                    if not file_path.exists():
                        raise FileNotFoundError(f"File not found: {file_path}")
                    files.append((file_path.name, file_path.open("rb")))

            if len(files) == 0:
                raise ValueError("At least one file must be provided")

            try:
                payload = CreateFilePayload(
                    files=files,
                    type=type,
                    challenge_id=challenge_id or challenge,
                    page_id=page_id or page,
                    location=location,
                )
            except ValidationError as e:
                raise ModelValidationError(e.errors()) from e

        return await self._client.arequest(
            "POST",
            "/api/v1/files",
            files=payload.dump_json(),
            response_model=list_file_adapter,
            error_models={400: BadRequest, 401: Unauthorized, 403: Forbidden},
        )

    @admin_only
    def get(self, file_id: int) -> StandardFile | ChallengeFile | PageFile:
        """
        !!! note "This method is only available to admins"

        Get a file by its ID.

        Parameters
        ----------
        file_id: int
            The ID of the file to get.

        Returns
        -------
        StandardFile | ChallengeFile | PageFile
            The file with the provided ID.

        Raises
        ------
        BadRequest
            An error occurred processing the provided or stored data.
        NotFound
            The file with the provided ID does not exist.
        AuthenticationRequired
            You must be logged in to access this resource.
        AdminOnly
            You must be an admin to access this resource.

        Examples
        --------
        Get a file by its ID:

        ```python
        file = ctfd.files.get(1)
        ```
        """
        return self._client.request(
            "GET",
            f"/api/v1/files/{file_id}",
            response_model=file_adapter,
            error_models={
                400: BadRequest,
                401: Unauthorized,
                403: Forbidden,
                404: NotFound,
            },
        )

    @admin_only
    async def async_get(self, file_id: int) -> StandardFile | ChallengeFile | PageFile:
        """
        !!! note "This method is only available to admins"

        Get a file by its ID.

        Parameters
        ----------
        file_id: int
            The ID of the file to get.

        Returns
        -------
        StandardFile | ChallengeFile | PageFile
            The file with the provided ID.

        Raises
        ------
        BadRequest
            An error occurred processing the provided or stored data.
        NotFound
            The file with the provided ID does not exist.
        AuthenticationRequired
            You must be logged in to access this resource.
        AdminOnly
            You must be an admin to access this resource.

        Examples
        --------
        Get a file by its ID:

        ```python
        file = await ctfd.files.async_get(1)
        ```
        """
        return await self._client.arequest(
            "GET",
            f"/api/v1/files/{file_id}",
            response_model=file_adapter,
            error_models={
                400: BadRequest,
                401: Unauthorized,
                403: Forbidden,
                404: NotFound,
            },
        )

    @admin_only
    def delete(self, file_id: int) -> bool:
        """
        !!! note "This method is only available to admins"

        Delete a file by its ID.

        Parameters
        ----------
        file_id: int
            The ID of the file to delete.

        Returns
        -------
        bool
            `#!python True` if the file was successfully deleted.

        Raises
        ------
        BadRequest
            An error occurred processing the provided or stored data.
        AuthenticationRequired
            You must be logged in to access this resource.
        AdminOnly
            You must be an admin to access this resource.
        NotFound
            The file with the provided ID does not exist.

        Examples
        --------
        Delete a file by its ID:

        ```python
        success = ctfd.files.delete(1)
        ```
        """
        return self._client.request(
            "DELETE",
            f"/api/v1/files/{file_id}",
            error_models={
                400: BadRequest,
                401: Unauthorized,
                403: Forbidden,
                404: NotFound,
            },
        )

    @admin_only
    async def async_delete(self, file_id: int) -> bool:
        """
        !!! note "This method is only available to admins"

        Delete a file by its ID.

        Parameters
        ----------
        file_id: int
            The ID of the file to delete.

        Returns
        -------
        bool
            `#!python True` if the file was successfully deleted.

        Raises
        ------
        BadRequest
            An error occurred processing the provided or stored data.
        AuthenticationRequired
            You must be logged in to access this resource.
        AdminOnly
            You must be an admin to access this resource.
        NotFound
            The file with the provided ID does not exist.

        Examples
        --------
        Delete a file by its ID:

        ```python
        success = await ctfd.files.async_delete(1)
        ```
        """
        return await self._client.arequest(
            "DELETE",
            f"/api/v1/files/{file_id}",
            error_models={
                400: BadRequest,
                401: Unauthorized,
                403: Forbidden,
                404: NotFound,
            },
        )

list

list(
    *,
    type: FileType | None = None,
    location: str | None = None,
    q: str | None = None,
    field: Literal["type", "location"] | None = None
) -> list[StandardFile | ChallengeFile | PageFile]

This method is only available to admins

List all files with optional filtering.

Parameters:

Name Type Description Default
type FileType | None

The type of file to filter by, defaults to None.

None
location str | None

The location of the file to filter by, defaults to None.

None
q str | None

The query string to search for, defaults to None.

None
field Literal['type', 'location'] | None

The field to search in, defaults to None.

None

Returns:

Type Description
list[StandardFile | ChallengeFile | PageFile]

A list of files that match the query.

Raises:

Type Description
ValueError

If q and field are not provided together.

BadRequest

An error occurred processing the provided or stored data.

AuthenticationRequired

You must be logged in to access this resource.

AdminOnly

You must be an admin to access this resource.

Examples:

Get all files:

files = ctfd.files.list()

Get all challenge files:

files = ctfd.files.list(type=FileType.CHALLENGE)
Source code in ctfdpy\api\files.py
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
@admin_only
def list(
    self,
    *,
    type: FileType | None = None,
    location: str | None = None,
    q: str | None = None,
    field: Literal["type", "location"] | None = None,
) -> list[StandardFile | ChallengeFile | PageFile]:
    """
    !!! note "This method is only available to admins"

    List all files with optional filtering.

    Parameters
    ----------
    type: FileType | None
        The type of file to filter by, defaults to None.
    location: str | None
        The location of the file to filter by, defaults to None.
    q: str | None
        The query string to search for, defaults to None.
    field: Literal["type", "location"] | None
        The field to search in, defaults to None.

    Returns
    -------
    list[StandardFile | ChallengeFile | PageFile]
        A list of files that match the query.

    Raises
    ------
    ValueError
        If q and field are not provided together.
    BadRequest
        An error occurred processing the provided or stored data.
    AuthenticationRequired
        You must be logged in to access this resource.
    AdminOnly
        You must be an admin to access this resource.

    Examples
    --------
    Get all files:

    ```python
    files = ctfd.files.list()
    ```

    Get all challenge files:

    ```python
    files = ctfd.files.list(type=FileType.CHALLENGE)
    ```
    """
    # Check if q and field are both provided or both not provided
    if q is None != field is None:
        raise ValueError("q and field must be provided together")

    params = {}
    if type is not None:
        params["type"] = type.value
    if location is not None:
        params["location"] = location
    if q is not None:
        params["q"] = q
        params["field"] = field

    return self._client.request(
        "GET",
        "/api/v1/files",
        params=params,
        response_model=list_file_adapter,
        error_models={400: BadRequest, 401: Unauthorized, 403: Forbidden},
    )

async_list async

async_list(
    *,
    type: FileType | None = None,
    location: str | None = None,
    q: str | None = None,
    field: Literal["type", "location"] | None = None
) -> list[StandardFile | ChallengeFile | PageFile]

This method is only available to admins

List all files with optional filtering.

Parameters:

Name Type Description Default
type FileType | None

The type of file to filter by, defaults to None.

None
location str | None

The location of the file to filter by, defaults to None.

None
q str | None

The query string to search for, defaults to None.

None
field Literal['type', 'location'] | None

The field to search in, defaults to None.

None

Returns:

Type Description
list[StandardFile | ChallengeFile | PageFile]

A list of files that match the query.

Raises:

Type Description
ValueError

If q and field are both provided or both not provided.

BadRequest

An error occurred processing the provided or stored data.

AuthenticationRequired

You must be logged in to access this resource.

AdminOnly

You must be an admin to access this resource.

Examples:

Get all files:

files = await ctfd.files.async_list()

Get all challenge files:

files = await ctfd.files.async_list(type=FileType.CHALLENGE)
Source code in ctfdpy\api\files.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
@admin_only
async def async_list(
    self,
    *,
    type: FileType | None = None,
    location: str | None = None,
    q: str | None = None,
    field: Literal["type", "location"] | None = None,
) -> list[StandardFile | ChallengeFile | PageFile]:
    """
    !!! note "This method is only available to admins"

    List all files with optional filtering.

    Parameters
    ----------
    type: FileType | None
        The type of file to filter by, defaults to None.
    location: str | None
        The location of the file to filter by, defaults to None.
    q: str | None
        The query string to search for, defaults to None.
    field: Literal["type", "location"] | None
        The field to search in, defaults to None.

    Returns
    -------
    list[StandardFile | ChallengeFile | PageFile]
        A list of files that match the query.

    Raises
    ------
    ValueError
        If q and field are both provided or both not provided.
    BadRequest
        An error occurred processing the provided or stored data.
    AuthenticationRequired
        You must be logged in to access this resource.
    AdminOnly
        You must be an admin to access this resource.

    Examples
    --------
    Get all files:

    ```python
    files = await ctfd.files.async_list()
    ```

    Get all challenge files:

    ```python
    files = await ctfd.files.async_list(type=FileType.CHALLENGE)
    ```
    """
    # Check if q and field are both provided or both not provided
    if q is None != field is None:
        raise ValueError("q and field must be provided together")

    params = {}
    if type is not None:
        params["type"] = type.value
    if location is not None:
        params["location"] = location
    if q is not None:
        params["q"] = q
        params["field"] = field

    return await self._client.arequest(
        "GET",
        "/api/v1/files",
        params=params,
        response_model=list_file_adapter,
        error_models={400: BadRequest, 401: Unauthorized, 403: Forbidden},
    )

create

create(
    *,
    payload: CreateFilePayload = MISSING,
    files: list[MultipartFileTypes] | None = None,
    file_paths: list[str | PathLike] | None = None,
    type: FileType | None = None,
    challenge_id: int | None = None,
    challenge: int | None = None,
    page_id: int | None = None,
    page: int | None = None,
    location: str | None = None
) -> list[StandardFile | ChallengeFile | PageFile]

This method is only available to admins

Create a new file.

Parameters:

Name Type Description Default
payload CreateFilePayload

The payload to create the file with. If this is provided, no other parameter should be provided.

MISSING
files list[MultipartFileTypes] | None

The files to upload. This can either be a FileContent or a tuple of length between 2 and 4 in the format (filename, file, content_type, headers). Defaults to None.

None
file_paths list[str | PathLike] | None

The paths to the files to upload. Defaults to None.

None
type FileType | None

The type of the file, defaults to None.

None
challenge_id int | None

The ID of the challenge to associate the file with, defaults to None.

None
page_id int | None

The ID of the page to associate the file with, defaults to None.

None
location str | None

The location on the server to upload the files to, defaults to None.

None

Returns:

Type Description
list[StandardFile | ChallengeFile | PageFile]

The files that were created.

Raises:

Type Description
ValueError

If no files are provided.

FileNotFoundError

If a file path does not exist.

ModelValidationError

If the payload is invalid.

BadRequest

An error occurred processing the provided or stored data.

AuthenticationRequired

You must be logged in to access this resource.

AdminOnly

You must be an admin to access this resource.

Examples:

Create a file for a challenge:

files = ctfd.files.create(
    files=[("filename.txt", open("/path/to/file.txt", "rb"))],
    type=FileType.CHALLENGE,
    challenge_id=1,
)
Source code in ctfdpy\api\files.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
@admin_only
def create(
    self,
    *,
    payload: CreateFilePayload = MISSING,
    files: list[MultipartFileTypes] | None = None,
    file_paths: list[str | os.PathLike] | None = None,
    type: FileType | None = None,
    challenge_id: int | None = None,
    challenge: int | None = None,
    page_id: int | None = None,
    page: int | None = None,
    location: str | None = None,
) -> list[StandardFile | ChallengeFile | PageFile]:
    """
    !!! note "This method is only available to admins"

    Create a new file.

    Parameters
    ----------
    payload: CreateFilePayload
        The payload to create the file with. If this is provided, no other parameter should be provided.
    files: list[MultipartFileTypes] | None
        The files to upload. This can either be a `#!python FileContent` or a tuple of length between 2 and 4
        in the format `(filename, file, content_type, headers)`. Defaults to None.
    file_paths: list[str | os.PathLike] | None
        The paths to the files to upload. Defaults to None.
    type: FileType | None
        The type of the file, defaults to None.
    challenge_id: int | None
        The ID of the challenge to associate the file with, defaults to None.
    page_id: int | None
        The ID of the page to associate the file with, defaults to None.
    location: str | None
        The location on the server to upload the files to, defaults to None.

    Returns
    -------
    list[StandardFile | ChallengeFile | PageFile]
        The files that were created.

    Raises
    ------
    ValueError
        If no files are provided.
    FileNotFoundError
        If a file path does not exist.
    ModelValidationError
        If the payload is invalid.
    BadRequest
        An error occurred processing the provided or stored data.
    AuthenticationRequired
        You must be logged in to access this resource.
    AdminOnly
        You must be an admin to access this resource.

    Examples
    --------
    Create a file for a challenge:

    ```python
    files = ctfd.files.create(
        files=[("filename.txt", open("/path/to/file.txt", "rb"))],
        type=FileType.CHALLENGE,
        challenge_id=1,
    )
    ```
    """
    if payload is MISSING:
        files = files or []

        if file_paths is not None:
            for file_path in file_paths:
                file_path = Path(file_path)
                if not file_path.exists():
                    raise FileNotFoundError(f"File not found: {file_path}")
                files.append((file_path.name, file_path.open("rb")))

        if len(files) == 0:
            raise ValueError("At least one file must be provided")

        try:
            payload = CreateFilePayload(
                files=files,
                type=type,
                challenge_id=challenge_id or challenge,
                page_id=page_id or page,
                location=location,
            )
        except ValidationError as e:
            raise ModelValidationError(e.errors()) from e

    return self._client.request(
        "POST",
        "/api/v1/files",
        files=payload.dump_json(),
        response_model=list_file_adapter,
        error_models={400: BadRequest, 401: Unauthorized, 403: Forbidden},
    )

async_create async

async_create(
    *,
    payload: CreateFilePayload = MISSING,
    files: list[MultipartFileTypes] | None = None,
    file_paths: list[str | PathLike] | None = None,
    type: FileType | None = None,
    challenge_id: int | None = None,
    challenge: int | None = None,
    page_id: int | None = None,
    page: int | None = None,
    location: str | None = None
) -> list[StandardFile | ChallengeFile | PageFile]

This method is only available to admins

Create a new file.

Parameters:

Name Type Description Default
payload CreateFilePayload

The payload to create the file with. If this is provided, no other parameter should be provided.

MISSING
files list[MultipartFileTypes] | None

The files to upload. This can either be a FileContent or a tuple of length between 2 and 4 in the format (filename, file, content_type, headers). Defaults to None.

None
file_paths list[str | PathLike] | None

The paths to the files to upload. Defaults to None.

None
type FileType | None

The type of the file, defaults to None.

None
challenge_id int | None

The ID of the challenge to associate the file with, defaults to None.

None
page_id int | None

The ID of the page to associate the file with, defaults to None.

None
location str | None

The location on the server to upload the files to, defaults to None.

None

Returns:

Type Description
list[StandardFile | ChallengeFile | PageFile]

The files that were created.

Raises:

Type Description
ValueError

If no files are provided.

FileNotFoundError

If a file path does not exist.

ModelValidationError

If the payload is invalid.

BadRequest

An error occurred processing the provided or stored data.

AuthenticationRequired

You must be logged in to access this resource.

AdminOnly

You must be an admin to access this resource.

Examples:

Create a file for a challenge:

files = await ctfd.files.async_create(
    files=[("filename.txt", open("/path/to/file.txt", "rb"))],
    type=FileType.CHALLENGE,
    challenge_id=1,
)
Source code in ctfdpy\api\files.py
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
@admin_only
async def async_create(
    self,
    *,
    payload: CreateFilePayload = MISSING,
    files: list[MultipartFileTypes] | None = None,
    file_paths: list[str | os.PathLike] | None = None,
    type: FileType | None = None,
    challenge_id: int | None = None,
    challenge: int | None = None,
    page_id: int | None = None,
    page: int | None = None,
    location: str | None = None,
) -> list[StandardFile | ChallengeFile | PageFile]:
    """
    !!! note "This method is only available to admins"

    Create a new file.

    Parameters
    ----------
    payload: CreateFilePayload
        The payload to create the file with. If this is provided, no other parameter should be provided.
    files: list[MultipartFileTypes] | None
        The files to upload. This can either be a `#!python FileContent` or a tuple of length between 2 and 4
        in the format `(filename, file, content_type, headers)`. Defaults to None.
    file_paths: list[str | os.PathLike] | None
        The paths to the files to upload. Defaults to None.
    type: FileType | None
        The type of the file, defaults to None.
    challenge_id: int | None
        The ID of the challenge to associate the file with, defaults to None.
    page_id: int | None
        The ID of the page to associate the file with, defaults to None.
    location: str | None
        The location on the server to upload the files to, defaults to None.

    Returns
    -------
    list[StandardFile | ChallengeFile | PageFile]
        The files that were created.

    Raises
    ------
    ValueError
        If no files are provided.
    FileNotFoundError
        If a file path does not exist.
    ModelValidationError
        If the payload is invalid.
    BadRequest
        An error occurred processing the provided or stored data.
    AuthenticationRequired
        You must be logged in to access this resource.
    AdminOnly
        You must be an admin to access this resource.

    Examples
    --------
    Create a file for a challenge:

    ```python
    files = await ctfd.files.async_create(
        files=[("filename.txt", open("/path/to/file.txt", "rb"))],
        type=FileType.CHALLENGE,
        challenge_id=1,
    )
    ```
    """
    if payload is MISSING:
        files = files or []

        if file_paths is not None:
            for file_path in file_paths:
                file_path = Path(file_path)
                if not file_path.exists():
                    raise FileNotFoundError(f"File not found: {file_path}")
                files.append((file_path.name, file_path.open("rb")))

        if len(files) == 0:
            raise ValueError("At least one file must be provided")

        try:
            payload = CreateFilePayload(
                files=files,
                type=type,
                challenge_id=challenge_id or challenge,
                page_id=page_id or page,
                location=location,
            )
        except ValidationError as e:
            raise ModelValidationError(e.errors()) from e

    return await self._client.arequest(
        "POST",
        "/api/v1/files",
        files=payload.dump_json(),
        response_model=list_file_adapter,
        error_models={400: BadRequest, 401: Unauthorized, 403: Forbidden},
    )

get

get(
    file_id: int,
) -> StandardFile | ChallengeFile | PageFile

This method is only available to admins

Get a file by its ID.

Parameters:

Name Type Description Default
file_id int

The ID of the file to get.

required

Returns:

Type Description
StandardFile | ChallengeFile | PageFile

The file with the provided ID.

Raises:

Type Description
BadRequest

An error occurred processing the provided or stored data.

NotFound

The file with the provided ID does not exist.

AuthenticationRequired

You must be logged in to access this resource.

AdminOnly

You must be an admin to access this resource.

Examples:

Get a file by its ID:

file = ctfd.files.get(1)
Source code in ctfdpy\api\files.py
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
@admin_only
def get(self, file_id: int) -> StandardFile | ChallengeFile | PageFile:
    """
    !!! note "This method is only available to admins"

    Get a file by its ID.

    Parameters
    ----------
    file_id: int
        The ID of the file to get.

    Returns
    -------
    StandardFile | ChallengeFile | PageFile
        The file with the provided ID.

    Raises
    ------
    BadRequest
        An error occurred processing the provided or stored data.
    NotFound
        The file with the provided ID does not exist.
    AuthenticationRequired
        You must be logged in to access this resource.
    AdminOnly
        You must be an admin to access this resource.

    Examples
    --------
    Get a file by its ID:

    ```python
    file = ctfd.files.get(1)
    ```
    """
    return self._client.request(
        "GET",
        f"/api/v1/files/{file_id}",
        response_model=file_adapter,
        error_models={
            400: BadRequest,
            401: Unauthorized,
            403: Forbidden,
            404: NotFound,
        },
    )

async_get async

async_get(
    file_id: int,
) -> StandardFile | ChallengeFile | PageFile

This method is only available to admins

Get a file by its ID.

Parameters:

Name Type Description Default
file_id int

The ID of the file to get.

required

Returns:

Type Description
StandardFile | ChallengeFile | PageFile

The file with the provided ID.

Raises:

Type Description
BadRequest

An error occurred processing the provided or stored data.

NotFound

The file with the provided ID does not exist.

AuthenticationRequired

You must be logged in to access this resource.

AdminOnly

You must be an admin to access this resource.

Examples:

Get a file by its ID:

file = await ctfd.files.async_get(1)
Source code in ctfdpy\api\files.py
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
@admin_only
async def async_get(self, file_id: int) -> StandardFile | ChallengeFile | PageFile:
    """
    !!! note "This method is only available to admins"

    Get a file by its ID.

    Parameters
    ----------
    file_id: int
        The ID of the file to get.

    Returns
    -------
    StandardFile | ChallengeFile | PageFile
        The file with the provided ID.

    Raises
    ------
    BadRequest
        An error occurred processing the provided or stored data.
    NotFound
        The file with the provided ID does not exist.
    AuthenticationRequired
        You must be logged in to access this resource.
    AdminOnly
        You must be an admin to access this resource.

    Examples
    --------
    Get a file by its ID:

    ```python
    file = await ctfd.files.async_get(1)
    ```
    """
    return await self._client.arequest(
        "GET",
        f"/api/v1/files/{file_id}",
        response_model=file_adapter,
        error_models={
            400: BadRequest,
            401: Unauthorized,
            403: Forbidden,
            404: NotFound,
        },
    )

delete

delete(file_id: int) -> bool

This method is only available to admins

Delete a file by its ID.

Parameters:

Name Type Description Default
file_id int

The ID of the file to delete.

required

Returns:

Type Description
bool

True if the file was successfully deleted.

Raises:

Type Description
BadRequest

An error occurred processing the provided or stored data.

AuthenticationRequired

You must be logged in to access this resource.

AdminOnly

You must be an admin to access this resource.

NotFound

The file with the provided ID does not exist.

Examples:

Delete a file by its ID:

success = ctfd.files.delete(1)
Source code in ctfdpy\api\files.py
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
@admin_only
def delete(self, file_id: int) -> bool:
    """
    !!! note "This method is only available to admins"

    Delete a file by its ID.

    Parameters
    ----------
    file_id: int
        The ID of the file to delete.

    Returns
    -------
    bool
        `#!python True` if the file was successfully deleted.

    Raises
    ------
    BadRequest
        An error occurred processing the provided or stored data.
    AuthenticationRequired
        You must be logged in to access this resource.
    AdminOnly
        You must be an admin to access this resource.
    NotFound
        The file with the provided ID does not exist.

    Examples
    --------
    Delete a file by its ID:

    ```python
    success = ctfd.files.delete(1)
    ```
    """
    return self._client.request(
        "DELETE",
        f"/api/v1/files/{file_id}",
        error_models={
            400: BadRequest,
            401: Unauthorized,
            403: Forbidden,
            404: NotFound,
        },
    )

async_delete async

async_delete(file_id: int) -> bool

This method is only available to admins

Delete a file by its ID.

Parameters:

Name Type Description Default
file_id int

The ID of the file to delete.

required

Returns:

Type Description
bool

True if the file was successfully deleted.

Raises:

Type Description
BadRequest

An error occurred processing the provided or stored data.

AuthenticationRequired

You must be logged in to access this resource.

AdminOnly

You must be an admin to access this resource.

NotFound

The file with the provided ID does not exist.

Examples:

Delete a file by its ID:

success = await ctfd.files.async_delete(1)
Source code in ctfdpy\api\files.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
@admin_only
async def async_delete(self, file_id: int) -> bool:
    """
    !!! note "This method is only available to admins"

    Delete a file by its ID.

    Parameters
    ----------
    file_id: int
        The ID of the file to delete.

    Returns
    -------
    bool
        `#!python True` if the file was successfully deleted.

    Raises
    ------
    BadRequest
        An error occurred processing the provided or stored data.
    AuthenticationRequired
        You must be logged in to access this resource.
    AdminOnly
        You must be an admin to access this resource.
    NotFound
        The file with the provided ID does not exist.

    Examples
    --------
    Delete a file by its ID:

    ```python
    success = await ctfd.files.async_delete(1)
    ```
    """
    return await self._client.arequest(
        "DELETE",
        f"/api/v1/files/{file_id}",
        error_models={
            400: BadRequest,
            401: Unauthorized,
            403: Forbidden,
            404: NotFound,
        },
    )