Commit Graph

270 Commits

Author SHA1 Message Date
Alex Oleshkevich a7c5a41396
Allow Session scoped cookies. (#1387)
* Allow Session scoped cookies.

* Update docs/middleware.md

Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com>

* Improve typing.

Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com>
2022-01-12 10:57:47 +01:00
Amin Alaee 3c93a19cef
Add Mypy checks to tests (#1353) 2022-01-11 09:28:39 +01:00
Adrian Garcia Badaracco 4e86245c4c
Document and type annotate UploadFile as a bytes-only interface. Not bytes or text. (#1312) 2022-01-10 09:41:43 -08:00
Marcelo Trylesinski 2d6ddd3861
Don't set headers for responses with 1xx, 204 and 304 status code (#1397)
* Don't set  headers for responses with 1xx, 204 and 304 status code

* Fix test

Co-authored-by: Tom Christie <tom@tomchristie.com>
2022-01-10 12:08:31 +01:00
Adrian Garcia Badaracco f1c5049643
feat: add headers attribute to UploadFile (#1382)
This preserves the multipart field headers that may have been included in the original request

Co-authored-by: Tom Christie <tom@tomchristie.com>
2022-01-07 11:06:37 -08:00
Marcelo Trylesinski 4633427816
Don't omit `Content-Length` header for `Content-Length: 0` cases (#1395)
* Add content-length header by default

* Add test for #1099

* Revert changes and add tests

* Check if is StreamingResponse or FileResponse before adding content-length headers

* Change conditional logic to check if body is present
2022-01-07 12:48:21 +01:00
matiuszka 9d686a7125
Additional headers for WS `accept` message. (#1361)
* Additional headers for WS accept message.

* Update tests/test_websockets.py

Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com>

* fixup! Additional headers for WS accept message.

* Update tests/test_websockets.py

Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com>
2022-01-06 11:55:29 +01:00
Amin Alaee 76cd611b50
Add support for functools.partial in WebsocketRoute (#1356)
* Add support for functools.partial in WebsocketRoute

* remove commented code

* Refactor tests for partian endpoint and ws
2021-12-11 14:35:23 +01:00
Amin Alaee f53faba229
Add support for Staticfiles directory in packages (#1350) 2021-12-07 10:04:54 +01:00
Eugene Mayer 7c7ec5a7f7
Remove port from Host routing regex (#1322)
Co-authored-by: Amin Alaee <mohammadamin.alaee@gmail.com>
Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com>
2021-11-25 15:11:25 +01:00
Florimond Manca 6c9bc55af7
Prevent anyio.ExceptionGroup in error views under a BaseHTTPMiddleware (#1262)
* Prevent ExceptionGroup in error views under a BaseHTTPMiddleware

* Apply suggestion from @uSpike

Co-authored-by: euri10 <benoit.barthelet@gmail.com>
2021-10-28 18:50:33 +02:00
Eugene Mayer 26b5be48bb
Fix Staticfiles `404.html` in HTML mode (#1314)
Co-authored-by: Amin Alaee <mohammadamin.alaee@gmail.com>
2021-10-19 11:27:35 +02:00
Amin Alaee 1db8b5b4e8
handle staticfiles OSError exceptions (#1220)
Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com>
2021-10-05 09:31:10 +03:30
Marcelo Trylesinski 28088573ae
🔥 Remove GraphQL support (#1198)
* 🔥 Remove GraphQL support

* Remove graphene dependency and add docs

* Update docs/graphql.md

Co-authored-by: Jamie Hewland <jhewland@gmail.com>

* Update docs/graphql.md

Co-authored-by: Jamie Hewland <jhewland@gmail.com>

* Remove aiofiles warning on setup.cfg

Co-authored-by: Jamie Hewland <jhewland@gmail.com>
2021-10-03 17:21:38 +02:00
Daniel Hahler 6902361c98
test_database_execute_many: remove unnecessary statement (#778)
Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com>
2021-09-18 14:10:40 +02:00
Hannes Küttner 7e675a0b86
Fix BadSignature exception handling in SessionMiddleware (#1264) 2021-08-14 15:38:50 +01:00
Thomas Grainger b0a6d6ffbd
ignore charset_normalizer related warning (#1242) 2021-07-16 11:07:55 +01:00
Thomas Grainger 537ab6afd1
use an async context manager factory for lifespan (#1227) 2021-07-03 18:43:24 +01:00
Thomas Grainger 254d0d97e4
ensure TestClient requests run in the same EventLoop as lifespan (#1213)
* ensure TestClient requests run in the same EventLoop as lifespan

* for lifespan task verification, use native task identity rather than anyio.abc.TaskInfo equality

https://github.com/agronholm/anyio/issues/324

* remove redundant pragma: no cover

* it's now a loop_id not a threading.ident

* replace Protocol with plain Callable TypeAlias

* use lifespan_context to actually open a task group

trio should complain if used incorrectly here.

* assign self.portal once, schedule reset immediately after assignment

* inline apps into their tests

* make task/loop trackers nonlocals
2021-07-03 17:39:25 +01:00
Thomas Grainger d222b87cb4
TestClient accepts backend and backend_options as arguments to constructor (#1211)
as opposed to ClassVar assignment 

Co-authored-by: Jamie Hewland <jhewland@gmail.com>
Co-authored-by: Jordan Speicher <jordan@jspeicher.com>
Co-authored-by: Jordan Speicher <uSpike@users.noreply.github.com>
2021-06-28 21:36:13 +01:00
Thomas Grainger 906e9073a4
reset the `__eq__` and `__hash__` of HTTPConnection to allow WebSockets to be added to … (#1039) 2021-06-28 13:02:18 +01:00
Jamie Hewland ab0fff9dd3
Test on Python 3.10 (#1201) 2021-06-19 18:02:53 +01:00
Jordan Speicher 42592d68e5
anyio integration (#1157)
* First whack at anyio integration

* Fix formatting

* Remove debug messages

* mypy fixes

* Update README.md

Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com>

* Fix install_requires typo

* move_on_after blocks if deadline is too small

* Linter fixes

* Improve WSGI structured concurrency

* Tests use anyio

* Checkin progress on testclient

* Prep for anyio 3

* Remove debug backend option

* Use anyio 3.0.0rc1

* Remove old style executor from GraphQLApp

* Fix extra import

* Don't cancel task scope early

* Wait for wsgi sender to finish before exiting

* Use memory object streams in websocket tests

* Test on asyncio, asyncio+uvloop, and trio

* Formatting fixes

* run_until_first_complete doesn't need a return

* Fix middleware app call

* Simplify middleware exceptions

* Use anyio for websocket test

* Set STARLETTE_TESTCLIENT_ASYNC_BACKEND in tests

* Pass async backend to portal

* Formatting fixes

* Bump anyio

* Cleanup portals and add TestClient.async_backend

* Use anyio.run_async_from_thread to send from worker thread

* Use websocket_connect as context manager

* Document changes in TestClient

* Formatting fix

* Fix websocket raises coverage

* Update to anyio 3.0.0rc3 and replace aiofiles

* Apply suggestions from code review

Co-authored-by: Alex Grönholm <alex.gronholm@nextday.fi>

* Bump to require anyio 3.0.0 final

* Remove mention of aiofiles in README.md

* Pin jinja2 to releases before 3 due to DeprecationWarnings

* Add task_group as application attribute

* Remove run_until_first_complete

* Undo jinja pin

* Refactor anyio.sleep into an event

* Use one less task in test_websocket_concurrency_pattern

* Apply review suggestions

* Rename argument

* fix start_task_soon type

* fix BaseHTTPMiddleware when used without Starlette

* Testclient receive() is a non-trapping function if the response is already complete

This allows for a zero deadline when waiting for a disconnect message

* Use variable annotation for async_backend

* Update docs regarding dependency on anyio

* Use CancelScope instead of move_on_after in request.is_disconnected

* Cancel task group after returning middleware response

Add test for https://github.com/encode/starlette/issues/1022

* Add link to anyio backend options in testclient docs

* Add types-dataclasses

* Re-implement starlette.concurrency.run_until_first_complete and add a test

* Fix type on handler callable

* Apply review comments to clarify run_until_first_complete scope

Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com>
Co-authored-by: Alex Grönholm <alex.gronholm@nextday.fi>
Co-authored-by: Thomas Grainger <tagrain@gmail.com>
2021-06-18 15:48:43 +01:00
laggardkernel 15761fb48e
Deduplicate failure text in CORS preflight response (#1199)
Co-authored-by: Jamie Hewland <jhewland@gmail.com>
2021-06-13 16:59:17 +01:00
Jordan Speicher b6f3578bb2
Updates to python 3.6+ syntax (#1189)
* Convert comment type hints to annotations

* Update to python 3.6+ syntax

* Explicitly state response type annotation

* Explicitly define queue generic type
2021-05-27 19:54:43 +01:00
Yurii Karabas b7aeae70fd
Add better exception msg for duplicated param names (#1177) 2021-05-04 10:36:16 +01:00
Ben Falk f997938916
use quote instead of quote_plus for RedirectResponse location header (#1164)
* use quote instead of quote_plus for RedirectResponse location header

adjust safe characters: rem. duplicate & symbol

add test for redirect quoting

* remove unused import

Co-authored-by: Jamie Hewland <jhewland@gmail.com>
2021-04-14 20:14:53 +01:00
Josh Wilson 995d70c7c6
Set explicit Origin in CORS preflight response if allow_credentials is True and allow_origins is wildcard (#1113)
* Set explicit Origin in CORS preflight response if allow_credentials is True and allow_origins is wildcard

When making a preflight request, the browser makes no indication as to whether the actual subsequent
request will pass up credentials. However, unless the preflight response explicitly allows the
request's `Origin` in the `Access-Control-Response-Header`, the browser will fail the CORS check and
prevent the actual follow-up CORS request. This means that responding with the `*` wildcard is not
sufficient to allow preflighted credentialed requests. The current workaround is to provide an
equivalently permissive `allow_origin_regex` pattern.

The `simple_response()` code already performs similar logic which currently only applies to
non-preflighted requests since the browser would never make a preflighted request that hits this
code due to this issue:

```
if self.allow_all_origins and has_cookie:
    headers["Access-Control-Allow-Origin"] = origin
```

This just bring the two halves inline with each other.

* Add Vary header to preflight response if allow_credentials

* Use allow_explicit_origin() for preflight request_headers

This simplifies the code slightly by using this recently added method.

It has some trade-offs, though. We now construct a `MutableHeaders` instead of a simple `dict` when
copying the pre-computed preflight headers, and we move the `Vary` header construction out of the
pre-computation and into the call handler.

I think it makes the code more maintainable and the added per-call computation is minimal.

* Convert MutableHeaders to dict for PlainTextResponse

* Revert back to dict() for preflight headers

This also names and caches some of the boolean tests in __init__() which we use in later if-blocks.
This follows the existing pattern in order to better self-document the code.

* Clean up comments

* Remove unused self.allow_credentials attribute
2021-04-14 20:10:20 +01:00
Josh Wilson f5ecb53895
Add HEAD to CORS ALL_METHODS list (#1112)
* Add HEAD to CORS ALL_METHODS list

The HEAD method is conspicuously absent from the allowed methods list when `allow_methods="*"` is
used. This doesn't really affect CORS preflight requests, as HEAD requests aren't preflighted by the
browser, but it does prevent the actual cross-origin HEAD response from being read by the calling
app.
[This can catch people off-guard.](https://discuss.encode.io/t/for-cors-middleware-why-is-head-not-included-in-all-methods/939)

This simply adds HEAD to the `ALL_METHODS` list in the CORS middleware module and includes some
additional tests to validate the new behavior.

* Update tests/middleware/test_cors.py to use more explicit status code check

Co-authored-by: euri10 <euri10@users.noreply.github.com>

Co-authored-by: euri10 <euri10@users.noreply.github.com>
Co-authored-by: Jamie Hewland <jhewland@gmail.com>
2021-04-06 21:38:48 +01:00
Josh Wilson 602212613c
Add Origin to Vary header on credentialed CORS response (#1111)
* Add Origin to Vary header on credentialed CORS response

According to the [MDN CORS docs]
(https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Access-Control-Allow-Origin), the `Origin`
item should be added to the `Vary` header when the `Access-Control-Allow-Origin` is set to an
explicit origin value, as opposed to the `*` wildcard.

>If the server specifies a single origin (that may dynamically change based on the requesting origin
as part of a white-list) rather than the "*" wildcard, then the server should also include Origin in
the Vary response header — to indicate to clients that server responses will differ based on the
value of the Origin request header.

The existing code fails to update the `Vary` list when the server is configured to allow all
origins (`*`) and the request has a `Cookie` header (ie. credentialed). In that situation, the
`Access-Control-Allow-Origin` header will be set to the request's `Origin` value.

It appears this may have just been a simple oversight in the original implementation. This updates
the code to add `Origin` to the `Vary` header under these circumstancesIf it was intentionally
omitted, I'd be delighted to learn why.

* Add type annotations

* Add test to ensure that the vary header does not contain origin if request is non-credentialed
2021-04-06 21:36:41 +01:00
Mahmoud Hossam 5ee04ef9b1
Make session cookie use ASGI root path (#1147)
* Make session cookie use ASGI root path

* Check if ASGI root_path exists before using it

Co-authored-by: Tom Christie <tom@tomchristie.com>

* Remove comment

* Add test

Co-authored-by: Mahmoud Hanafy <mahmoud.hanafy@retresco.de>
Co-authored-by: Tom Christie <tom@tomchristie.com>
2021-03-12 12:49:52 +00:00
ilunev 0ac60bbeb2
StaticFiles: Fix cache validation bug for deleted files in html mode (#1023)
* StaticFiles: Fix cache validation bug for deleted files in html mode

Previously StaticFiles would return 304 for a deleted file if its
Last-Modified date was the same as that of 404.html

* Use black formatter

Co-authored-by: Jamie Hewland <jhewland@gmail.com>
2021-02-05 20:15:25 +00:00
Vlad Stefan Munteanu fe908b1c29
Fix functools.partial async handlers for classmethods (#1106)
* Showcase the bug

* Fixed functools.partial usage with classmethods

* Updated comment

* Updated docstring according to suggestion

Co-authored-by: Jamie Hewland <jhewland@gmail.com>

Co-authored-by: Jamie Hewland <jhewland@gmail.com>
2021-02-02 10:30:30 +00:00
Jamie Hewland 62e95b89fc
Fix middleware traceback fetching on Python 3.8+, fix ResourceWarnings in TestClient, fix CI build (#1132)
* Add __init__ file for tests.middleware so Mypy 0.800 is happy

* testclient: Tie loop lifetime to thread

* ServerErrorMiddleware: Don't use undocumented TracebackException.exc_traceback attribute
2021-01-31 12:43:07 +01:00
Jamie Hewland 99b37781eb
Remove UJSONResponse (#1047)
* Remove UJSONResponse

* Add documentation about custom JSON serialization
2020-11-08 22:49:12 +02:00
Vlad Stefan Munteanu fe961dd22c
Allow usage of functools.partial async handlers (#984)
* Allow usage of async partial methods

* Added test for partial async endpoint

* Double quotes vs single quotes

* Support multiple levels of partials, check Python < 3.8

* Skip coverage for py3.8 branch

Co-authored-by: Florimond Manca <florimond.manca@gmail.com>
2020-11-07 17:33:11 -08:00
witling a9f8821f3b
fix 793: allow custom async iterator (#1041)
* fix 793

* custom async generator: implement pr notes

* custom async generator: cleanup dependencies

* update tests

* newline at end of tests

* fix linting

* Update tests/test_responses.py

Co-authored-by: Jamie Hewland <jhewland@gmail.com>

* Update tests/test_responses.py

Co-authored-by: Jamie Hewland <jhewland@gmail.com>

* fix naming for custom generator tests

* comply with pep 492

* Shift streaming tests to be in one place

Co-authored-by: witling <noreply@my.email>
Co-authored-by: Jamie Hewland <jhewland@gmail.com>
2020-10-21 20:10:30 +02:00
Jamie Hewland 41218ac546
Move lifespan tests out of obsolete middleware test module (#1055)
* Move lifespan tests out of obsolete middleware test module

* Add test_lifespan_async
2020-09-11 15:26:55 +02:00
Elliana May faea6c290a
Use format_exception instead of format_tb (#1031)
* Use format_exception instead of format_tb

This gives much more information about the exception, including causes, and the exception message itself, in addition to the trackback

* Update test

Co-authored-by: Jamie Hewland <jhewland@gmail.com>
2020-09-11 13:15:50 +02:00
Thomas Grainger b043fe56bc
configure pytest to be stricter (#1040)
* fix tests/test_datastructures::TestUploadFile PytestCollectionWarning

enhance pytest strictness to catch warnings that would have prevented
thest TestUploadFile file warning

restore cov-report and require 100% coverage

* Apply suggestions from code review

Co-authored-by: Jamie Hewland <jhewland@gmail.com>

* remove cov-fail-under

* Apply suggestions from code review

Co-authored-by: Jamie Hewland <jhewland@gmail.com>

* Apply suggestions from code review

Co-authored-by: Jamie Hewland <jhewland@gmail.com>

* Update setup.cfg

Co-authored-by: Jamie Hewland <jhewland@gmail.com>

Co-authored-by: Jamie Hewland <jhewland@gmail.com>
2020-09-11 11:19:47 +02:00
Thomas Grainger aa85713d82
allow black to pass on v20.8b1 and v19.10b0 (#1049)
by running black v19.3b0 (we miss you) and then running black v20.8b1
2020-09-07 09:19:20 +02:00
Jamie Hewland b95acea973
Update CI scripts to match httpcore (#1043)
* Update CI scripts to match httpcore

* Run test suite on pushes to master

* Update scripts README

* Don't bother with flake8 extensions for now

* Remove unnecessary PYTHONPATH from build, publish

* test_routing: Use a stub app instead of ellipsis

* Add link to issue about type-checking tests
2020-09-06 12:08:07 +02:00
Jamie Hewland 8729e9fc69
Use and pin black 20 (#1042) 2020-09-05 15:16:56 +02:00
Hannes Küttner c566fc6c81
Be more lenient with route arguments in AuthencationMiddleware 'requires' decorator (#942) 2020-08-16 07:24:23 -07:00
Kevin Stone 93878323e5
Use os.PathLike in StaticFiles for directory (#1007)
* Use os.PathLike in StaticFiles for directory

This allows using `pathlib.Path` in addition to `str` for configuring
the base directory of the static files in line with how python3.6+
handles filesystem operations.

Fixes #1004

* Fixed `mimetypes.guess_type` not supporting PathLike on py3.7 and below

* Updated staticfiles documentation with `PathLike` param
2020-08-05 16:04:07 -07:00
子休 85b9c2642b
fix wsgi PATH_INFO encoding (#998)
* fix wsgi PATH_INFO encoding

* encode root_path

* wsgi middleware: Add test for PATH_INFO & SCRIPT_NAME encoding

Co-authored-by: Jamie Hewland <jhewland@gmail.com>
2020-07-15 20:27:17 +02:00
Vlad Stefan Munteanu 349cc73763
Fix hanging graphql tests (#989)
* Use pytest-asyncio event loop when creating AsyncioExecutor in tests

* Reformatting line width
2020-06-29 12:35:40 +01:00
Peer Sommerlund f12e237da5
Allow path to contain regex meta characters (#932)
* Allow path to contain regex meta characters
2020-05-11 12:22:59 +01:00
euri10 e57fa2a6b1
Middleware should treat `body` in response ASGI messages as an optional key. (#935)
* Failing test for HEAD method when using a middleware

* Fixed by sending empty body if send_header_only

* Lint

* Respect asgi spec

* Be explicit in case we send headers only
2020-05-07 14:50:24 +02:00
云中君 97257515f8
Thread pool is no longer used for files in memory (#933)
* https://github.com/Tinche/aiofiles/issues/47
Thread pool is no longer used for files in memory

* fix tests

* fix import sorted

* little change
2020-05-06 14:52:26 +01:00