Skip to content

New IOResponse class for serving a response using any IO object #10465

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 21 commits into
base: master
Choose a base branch
from

Conversation

Derkades
Copy link
Contributor

@Derkades Derkades commented Feb 16, 2025

What do these changes do?

FileResponse now accepts an opened file instead of only a file path. This allows sending a temporary file to the client by opening the file, deleting it, and then passing the open file to FileResponse. FileResponse handles closing the file when it is no longer used.

Are there changes in behavior for the user?

FileResponse is now a subclass of BaseIOResponse, I don't expect any compatibility issues for normal API usage

Is it a substantial burden for the maintainers to support this?

The FileResponse class is now more complicated. I am still thinking about if it makes sense to split FileResponse into two classes, one for handling IO and one for handling paths. Now split into subclasses, I think it makes the code clearer than it was before.

It is a bit unusual for an API to take an open file and close it by itself. But it solves a problem. Other suggestions are welcome.

Related issue number

#10360

Checklist

  • I think the code is well written
  • Unit tests for the changes exist
  • Documentation reflects the changes
  • If you provide code modification, please add yourself to CONTRIBUTORS.txt
    • The format is <Name> <Surname>.
    • Please keep alphabetical order, the file is sorted by names.
  • Add a new news fragment into the CHANGES/ folder
    • name it <issue_or_pr_num>.<type>.rst (e.g. 588.bugfix.rst)

    • if you don't have an issue number, change it to the pull request
      number after creating the PR

      • .bugfix: A bug fix for something the maintainers deemed an
        improper undesired behavior that got corrected to match
        pre-agreed expectations.
      • .feature: A new behavior, public APIs. That sort of stuff.
      • .deprecation: A declaration of future API removals and breaking
        changes in behavior.
      • .breaking: When something public is removed in a breaking way.
        Could be deprecated in an earlier release.
      • .doc: Notable updates to the documentation structure or build
        process.
      • .packaging: Notes for downstreams about unobvious side effects
        and tooling. Changes in the test invocation considerations and
        runtime assumptions.
      • .contrib: Stuff that affects the contributor experience. e.g.
        Running tests, building the docs, setting up the development
        environment.
      • .misc: Changes that are hard to assign to any of the above
        categories.
    • Make sure to use full sentences with correct case and punctuation,
      for example:

      Fixed issue with non-ascii contents in doctest text files
      -- by :user:`contributor-gh-handle`.

      Use the past tense or the present tense a non-imperative mood,
      referring to what's changed compared to the last released version
      of this project.

Copy link

codspeed-hq bot commented Feb 16, 2025

CodSpeed Performance Report

Merging #10465 will degrade performances by 18.77%

Comparing Derkades:fileresponse-bufferedreader (0710fbf) with master (8afdc4d)

Summary

❌ 1 regressions
✅ 58 untouched benchmarks

⚠️ Please fix the performance issues or acknowledge them on CodSpeed.

Benchmarks breakdown

Benchmark BASE HEAD Change
test_simple_web_file_response_not_modified[pyloop] 55.4 ms 68.3 ms -18.77%

Comment on lines 404 to 406
# content-type cannot be determined if self._io is used
# instead of self._path
self.content_type = FALLBACK_CONTENT_TYPE
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unless I'm missing something, it seems like FileResponse is missing Content-Disposition by default. If we were to add this in and recommend the user to specify a filename for the download, then we could use that filename here (or just use it if the header has been explicitly passed):

>>> mimetypes.guess_type("foo.html")
('text/html', None)

Copy link
Member

@Dreamsorcerer Dreamsorcerer left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this looks reasonable. I suspect a subclass may be cleaner though (FileIOResponse maybe?).

@Derkades Derkades force-pushed the fileresponse-bufferedreader branch from c7de271 to c16bc35 Compare July 19, 2025 16:25
@Derkades
Copy link
Contributor Author

Now rewritten with subclasses. It is much cleaner. I still need to bring back Accept-Encoding support.

@Derkades Derkades changed the title FileResponse: accept BufferedReader New IOResponse class for serving a response using any IO object Jul 19, 2025
@Dreamsorcerer
Copy link
Member

Looks promising. We'll need to update the docs too, and make sure we have a warning highlighting that the handler should not close the file object (including using a context manager).

@Derkades
Copy link
Contributor Author

I am having difficulty solving test failures with this error: TypeError: Unsupported type for last_modified: MagicMock

It happens when setting self.last_modified in the _not_modified function. I am unfortunately not very familiar with mock. Do you have an idea how to fix this?

@psf-chronographer psf-chronographer bot added the bot:chronographer:provided There is a change note present in this PR label Jul 21, 2025
@Derkades
Copy link
Contributor Author

Derkades commented Jul 21, 2025

CodSpeed reports a small regression, I think this is because the current implementation always opens the file even if it is unchanged. I can probably fix this.

@Dreamsorcerer
Copy link
Member

It happens when setting self.last_modified in the _not_modified function. I am unfortunately not very familiar with mock. Do you have an idea how to fix this?

As far as I can see, last_modified comes from st_mtime, so we'll need to set it on the mock. e.g. Add a line after this one (presumably set to that value divided by 1000000 or whatever the appropriate order of magnitude is):
https://github.com/Derkades/aiohttp/blob/05e191d85cd65480b267cfccbe4d1f306a74ba8f/tests/test_web_sendfile.py#L152

@Derkades
Copy link
Contributor Author

With st_mtime added to the mock, the tests indeed pass. I am not sure why they didn't fail before, st_mtime was used previously.

test_file_response_sends_headers_immediately is failing because send_headers() is never called. That makes sense to me because send_headers() would be called in _sendfile(), but _sendfile() is replaced by a mock. Not sure how that worked before.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bot:chronographer:provided There is a change note present in this PR
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants