A MediaUpload for a file. Construct a MediaFileUpload and pass as the media_body parameter of the method. For example, if we had a service that allowed uploading images: media = MediaFileUpload('cow.png', mimetype='image/png', chunksize=1024*1024, resumable=True) farm.a
| 550 | |
| 551 | |
| 552 | class MediaFileUpload(MediaIoBaseUpload): |
| 553 | """A MediaUpload for a file. |
| 554 | |
| 555 | Construct a MediaFileUpload and pass as the media_body parameter of the |
| 556 | method. For example, if we had a service that allowed uploading images: |
| 557 | |
| 558 | media = MediaFileUpload('cow.png', mimetype='image/png', |
| 559 | chunksize=1024*1024, resumable=True) |
| 560 | farm.animals().insert( |
| 561 | id='cow', |
| 562 | name='cow.png', |
| 563 | media_body=media).execute() |
| 564 | |
| 565 | Depending on the platform you are working on, you may pass -1 as the |
| 566 | chunksize, which indicates that the entire file should be uploaded in a single |
| 567 | request. If the underlying platform supports streams, such as Python 2.6 or |
| 568 | later, then this can be very efficient as it avoids multiple connections, and |
| 569 | also avoids loading the entire file into memory before sending it. Note that |
| 570 | Google App Engine has a 5MB limit on request size, so you should never set |
| 571 | your chunksize larger than 5MB, or to -1. |
| 572 | """ |
| 573 | |
| 574 | @util.positional(2) |
| 575 | def __init__( |
| 576 | self, filename, mimetype=None, chunksize=DEFAULT_CHUNK_SIZE, resumable=False |
| 577 | ): |
| 578 | """Constructor. |
| 579 | |
| 580 | Args: |
| 581 | filename: string, Name of the file. |
| 582 | mimetype: string, Mime-type of the file. If None then a mime-type will be |
| 583 | guessed from the file extension. |
| 584 | chunksize: int, File will be uploaded in chunks of this many bytes. Only |
| 585 | used if resumable=True. Pass in a value of -1 if the file is to be |
| 586 | uploaded in a single chunk. Note that Google App Engine has a 5MB limit |
| 587 | on request size, so you should never set your chunksize larger than 5MB, |
| 588 | or to -1. |
| 589 | resumable: bool, True if this is a resumable upload. False means upload |
| 590 | in a single request. |
| 591 | """ |
| 592 | self._fd = None |
| 593 | self._filename = filename |
| 594 | self._fd = open(self._filename, "rb") |
| 595 | if mimetype is None: |
| 596 | # No mimetype provided, make a guess. |
| 597 | mimetype, _ = mimetypes.guess_type(filename) |
| 598 | if mimetype is None: |
| 599 | # Guess failed, use octet-stream. |
| 600 | mimetype = "application/octet-stream" |
| 601 | super(MediaFileUpload, self).__init__( |
| 602 | self._fd, mimetype, chunksize=chunksize, resumable=resumable |
| 603 | ) |
| 604 | |
| 605 | def __del__(self): |
| 606 | if self._fd: |
| 607 | self._fd.close() |
| 608 | |
| 609 | def to_json(self): |
no outgoing calls
searching dependent graphs…