internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: sanic-org/sanic

Issue:
Publish 19.3 release to PyPI
Thank you for the release 3 days ago!

https://github.com/huge-success/sanic/releases/tag/19.3

It's missing from PyPI at the moment:

https://pypi.org/project/sanic/#history

Please publish it at your convenience 🙇 

Keep up the awesome work ❤️ 


Discussion:
I think @sjsadowski is already looking into it. 
Yeah we have a credentialing issue which we are working to resolve. I'll leave this open until 19.3 gets pushed.
See #1529

Resolving patch:
diff --git a/sanic/__init__.py b/sanic/__init__.py
--- a/sanic/__init__.py
+++ b/sanic/__init__.py
@@ -2,6 +2,6 @@
 from sanic.blueprints import Blueprint
 
 
-__version__ = "19.03.0"
+__version__ = "19.03.1"
 
 __all__ = ["Sanic", "Blueprint"]


Test patch:
Repository: sanic-org/sanic

Issue:
Unable to start server -- Running run_async.py failed
**Describe the bug**
[2019-04-14 19:22:02 +0800] [21512] [INFO] Goin' Fast @ http://0.0.0.0:8000
[2019-04-14 19:22:02 +0800] [21512] [ERROR] Unable to start server
Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\envs\venom\lib\site-packages\sanic\server.py", line 745, in serve
    http_server = loop.run_until_complete(server_coroutine)
  File "C:\ProgramData\Anaconda3\envs\venom\lib\asyncio\base_events.py", line 571, in run_until_complete
    self.run_forever()
  File "C:\ProgramData\Anaconda3\envs\venom\lib\asyncio\base_events.py", line 529, in run_forever
    'Cannot run the event loop while another loop is running')
RuntimeError: Cannot run the event loop while another loop is running

**Code snippet**
Relevant source code, make sure to remove what is not necessary.

https://github.com/huge-success/sanic/blob/master/examples/run_async.py

**Expected behavior**
A clear and concise description of what you expected to happen.


**Environment (please complete the following information):**
 - OS: [e.g. iOS]
 - Version [e.g. 0.8.3]
Window and Linux, Python 3.6 or 3.7 don't work

**Additional context**
Add any other context about the problem here.


Is this example still work ?


Discussion:
It does... but there was a slight change. You are running `0.8.3`?

If you are in a newer release, then you would need to add `return_asyncio_server=True` to `create_server(...)`
I run in this issue too. The fix proposed works. I think documentation needs update on this point.
@jrmi Agreed. I was planning on pushing a change to this when I get a chance tomorrow. Unless of course, you'd like to push a PR?

Resolving patch:
diff --git a/examples/log_request_id.py b/examples/log_request_id.py
--- a/examples/log_request_id.py
+++ b/examples/log_request_id.py
@@ -76,7 +76,7 @@ async def test(request):
 
 if __name__ == '__main__':
     asyncio.set_event_loop(uvloop.new_event_loop())
-    server = app.create_server(host="0.0.0.0", port=8000)
+    server = app.create_server(host="0.0.0.0", port=8000, return_asyncio_server=True)
     loop = asyncio.get_event_loop()
     loop.set_task_factory(context.task_factory)
     task = asyncio.ensure_future(server)
diff --git a/examples/run_async.py b/examples/run_async.py
--- a/examples/run_async.py
+++ b/examples/run_async.py
@@ -12,7 +12,7 @@ async def test(request):
     return response.json({"answer": "42"})
 
 asyncio.set_event_loop(uvloop.new_event_loop())
-server = app.create_server(host="0.0.0.0", port=8000)
+server = app.create_server(host="0.0.0.0", port=8000, return_asyncio_server=True)
 loop = asyncio.get_event_loop()
 task = asyncio.ensure_future(server)
 signal(SIGINT, lambda s, f: loop.stop())


Test patch:
Repository: sanic-org/sanic

Issue:
2 failed tests when tox is not used (missing fixture "benchmark")
`pytest-benchmark` is not present in `tests_require`, so there are 2 failed tests in `tests/benchmark/test_route_resolution_benchmark.py` when tox is not used.

This requirement is present in `tox.ini` so tox and Travis CI are working fine.

(I don't know what's a better fix — disable the benchmark tests or add `pytest-benchmark` to `tests_require`, so I didn't create a PR)


Discussion:
add to tests_require

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -96,6 +96,7 @@ def open_local(paths, mode="r", encoding="utf8"):
     ujson,
     "pytest-sanic",
     "pytest-sugar",
+    "pytest-benchmark",
 ]
 
 if strtobool(os.environ.get("SANIC_NO_UJSON", "no")):


Test patch:
Repository: sanic-org/sanic

Issue:
The response.content_type is not add to headers in ASGI
Perhaps the response.content_type is add to headers here.


Discussion:

Resolving patch:
diff --git a/sanic/asgi.py b/sanic/asgi.py
--- a/sanic/asgi.py
+++ b/sanic/asgi.py
@@ -328,6 +328,11 @@ async def stream_callback(self, response: HTTPResponse) -> None:
                 (b"content-length", str(len(response.body)).encode("latin-1"))
             ]
 
+        if "content-type" not in response.headers:
+            headers += [
+                (b"content-type", str(response.content_type).encode("latin-1"))
+            ]
+
         if response.cookies:
             cookies.update(
                 {


Test patch:
diff --git a/tests/test_asgi.py b/tests/test_asgi.py
--- a/tests/test_asgi.py
+++ b/tests/test_asgi.py
@@ -9,7 +9,7 @@
 from sanic.asgi import MockTransport
 from sanic.exceptions import InvalidUsage
 from sanic.request import Request
-from sanic.response import text
+from sanic.response import json, text
 from sanic.websocket import WebSocketConnection
 
 
@@ -256,3 +256,27 @@ def get_cookie(request):
         assert cookie_map.get(k).get("value") == v.value
         if cookie_map.get(k).get("HttpOnly"):
             assert "HttpOnly" in v._rest.keys()
+
+
+@pytest.mark.asyncio
+async def test_json_content_type(app):
+    @app.get("/json")
+    def send_json(request):
+        return json({"foo": "bar"})
+
+    @app.get("/text")
+    def send_text(request):
+        return text("foobar")
+
+    @app.get("/custom")
+    def send_custom(request):
+        return text("foobar", content_type="somethingelse")
+
+    _, response = await app.asgi_client.get("/json")
+    assert response.headers.get("content-type") == "application/json"
+
+    _, response = await app.asgi_client.get("/text")
+    assert response.headers.get("content-type") == "text/plain; charset=utf-8"
+
+    _, response = await app.asgi_client.get("/custom")
+    assert response.headers.get("content-type") == "somethingelse"
Repository: sanic-org/sanic

Issue:
Improve documentation in *Accessing values using `get` and `getlist`*
**Is your feature request related to a problem? Please describe.**
Documentation here should be improved:
https://sanic.readthedocs.io/en/latest/sanic/request_data.html#accessing-values-using-get-and-getlist
It isn't clear how to use `get` and `getlist`

**Describe the solution you'd like**
Change
> The request properties which return a dictionary actually return a subclass of dict called RequestParameters.

To
> `request.args` which return a dictionary actually return a subclass of dict called RequestParameters.


Discussion:

Resolving patch:
diff --git a/sanic/request.py b/sanic/request.py
--- a/sanic/request.py
+++ b/sanic/request.py
@@ -519,8 +519,11 @@ def url_for(self, view_name, **kwargs):
         :rtype: str
         """
         # Full URL SERVER_NAME can only be handled in app.url_for
-        if "//" in self.app.config.SERVER_NAME:
-            return self.app.url_for(view_name, _external=True, **kwargs)
+        try:
+            if "//" in self.app.config.SERVER_NAME:
+                return self.app.url_for(view_name, _external=True, **kwargs)
+        except AttributeError:
+            pass
 
         scheme = self.scheme
         host = self.server_name


Test patch:
diff --git a/tests/test_requests.py b/tests/test_requests.py
--- a/tests/test_requests.py
+++ b/tests/test_requests.py
@@ -2103,3 +2103,19 @@ async def bp_root(request):
     request, response = await app.asgi_client.get("/bp")
 
     assert request.endpoint == "named.my_blueprint.bp_root"
+
+
+def test_url_for_without_server_name(app):
+    @app.route("/sample")
+    def sample(request):
+        return json({"url": request.url_for("url_for")})
+
+    @app.route("/url-for")
+    def url_for(request):
+        return text("url-for")
+
+    request, response = app.test_client.get("/sample")
+    assert (
+        response.json["url"]
+        == f"http://127.0.0.1:{app.test_client.port}/url-for"
+    )
Repository: sanic-org/sanic

Issue:
Nightly build fails due to websockets version not matching setup.py
on setup.py: >=0.7.0,<0.9
on tox.ini: >=0.7.0,<0.8


Discussion:

Resolving patch:
diff --git a/sanic/websocket.py b/sanic/websocket.py
--- a/sanic/websocket.py
+++ b/sanic/websocket.py
@@ -113,7 +113,7 @@ async def websocket_handshake(self, request, subprotocols=None):
 
         # hook up the websocket protocol
         self.websocket = WebSocketCommonProtocol(
-            timeout=self.websocket_timeout,
+            close_timeout=self.websocket_timeout,
             max_size=self.websocket_max_size,
             max_queue=self.websocket_max_queue,
             read_limit=self.websocket_read_limit,
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -79,7 +79,7 @@ def open_local(paths, mode="r", encoding="utf8"):
     uvloop,
     ujson,
     "aiofiles>=0.3.0",
-    "websockets>=7.0,<9.0",
+    "websockets>=8.1,<9.0",
     "multidict>=4.0,<5.0",
     "httpx==0.11.1",
 ]


Test patch:
diff --git a/tests/test_reloader.py b/tests/test_reloader.py
--- a/tests/test_reloader.py
+++ b/tests/test_reloader.py
@@ -1,8 +1,9 @@
 import os
 import secrets
 import sys
+from contextlib import suppress
 
-from subprocess import PIPE, Popen
+from subprocess import PIPE, Popen, TimeoutExpired
 from tempfile import TemporaryDirectory
 from textwrap import dedent
 from threading import Timer
@@ -85,4 +86,5 @@ async def test_reloader_live(runargs, mode):
         finally:
             timeout.cancel()
             terminate(proc)
-            proc.wait(timeout=3)
+            with suppress(TimeoutExpired):
+                proc.wait(timeout=3)
Repository: sanic-org/sanic

Issue:
sanic-testing integration improvements
In the testing client properties, let's add a check for the `TestManager` instance.

```
elif hasattr(self, "_test_manager"):
    return self._test_manager.test_client
```



Discussion:

Resolving patch:
diff --git a/sanic/app.py b/sanic/app.py
--- a/sanic/app.py
+++ b/sanic/app.py
@@ -86,6 +86,7 @@ def __init__(
         self.websocket_tasks: Set[Future] = set()
         self.named_request_middleware: Dict[str, MiddlewareType] = {}
         self.named_response_middleware: Dict[str, MiddlewareType] = {}
+        self._test_manager = None
         self._test_client = None
         self._asgi_client = None
         # Register alternative method names
@@ -1032,18 +1033,22 @@ async def handle_request(self, request):
     # -------------------------------------------------------------------- #
 
     @property
-    def test_client(self):
+    def test_client(self):  # noqa
         if self._test_client:
             return self._test_client
+        elif self._test_manager:
+            return self._test_manager.test_client
         from sanic_testing.testing import SanicTestClient  # type: ignore
 
         self._test_client = SanicTestClient(self)
         return self._test_client
 
     @property
-    def asgi_client(self):
+    def asgi_client(self):  # noqa
         if self._asgi_client:
             return self._asgi_client
+        elif self._test_manager:
+            return self._test_manager.test_client
         from sanic_testing.testing import SanicASGITestClient  # type: ignore
 
         self._asgi_client = SanicASGITestClient(self)


Test patch:
diff --git a/tests/test_static.py b/tests/test_static.py
--- a/tests/test_static.py
+++ b/tests/test_static.py
@@ -1,5 +1,6 @@
 import inspect
 import os
+
 from pathlib import Path
 from time import gmtime, strftime
 
@@ -93,8 +94,8 @@ def test_static_file_pathlib(app, static_file_directory, file_name):
     [b"test.file", b"decode me.txt", b"python.png"],
 )
 def test_static_file_bytes(app, static_file_directory, file_name):
-    bsep = os.path.sep.encode('utf-8')
-    file_path = static_file_directory.encode('utf-8') + bsep + file_name
+    bsep = os.path.sep.encode("utf-8")
+    file_path = static_file_directory.encode("utf-8") + bsep + file_name
     app.static("/testing.file", file_path)
     request, response = app.test_client.get("/testing.file")
     assert response.status == 200
Repository: sanic-org/sanic

Issue:
RecursionError on Sanic subclass initialisation
Discovered at https://github.com/sanic-org/sanic/issues/2071

version: latest sanic master (`8a2ea626c6d04a5eb1e28d071ffa56bf9ad98a12`)

description:

RecursionError occurs when initialising Sanic subclass

minimal code to reproduce:

```python
from sanic import Sanic


class Custom(Sanic):
    pass

custom = Custom("custom")
```


Potential fix: https://github.com/sanic-org/sanic/pull/2072


Discussion:

Resolving patch:
diff --git a/sanic/base.py b/sanic/base.py
--- a/sanic/base.py
+++ b/sanic/base.py
@@ -8,38 +8,19 @@
 from sanic.mixins.signals import SignalMixin
 
 
-class Base(type):
-    def __new__(cls, name, bases, attrs):
-        init = attrs.get("__init__")
-
-        def __init__(self, *args, **kwargs):
-            nonlocal init
-            nonlocal name
-
-            bases = [
-                b for base in type(self).__bases__ for b in base.__bases__
-            ]
-
-            for base in bases:
-                base.__init__(self, *args, **kwargs)
-
-            if init:
-                init(self, *args, **kwargs)
-
-        attrs["__init__"] = __init__
-        return type.__new__(cls, name, bases, attrs)
-
-
 class BaseSanic(
     RouteMixin,
     MiddlewareMixin,
     ListenerMixin,
     ExceptionMixin,
     SignalMixin,
-    metaclass=Base,
 ):
     __fake_slots__: Tuple[str, ...]
 
+    def __init__(self, *args, **kwargs) -> None:
+        for base in BaseSanic.__bases__:
+            base.__init__(self, *args, **kwargs)  # type: ignore
+
     def __str__(self) -> str:
         return f"<{self.__class__.__name__} {self.name}>"
 
diff --git a/sanic/blueprints.py b/sanic/blueprints.py
--- a/sanic/blueprints.py
+++ b/sanic/blueprints.py
@@ -73,6 +73,7 @@ def __init__(
         version: Optional[int] = None,
         strict_slashes: Optional[bool] = None,
     ):
+        super().__init__()
 
         self._apps: Set[Sanic] = set()
         self.ctx = SimpleNamespace()


Test patch:
diff --git a/tests/test_app.py b/tests/test_app.py
--- a/tests/test_app.py
+++ b/tests/test_app.py
@@ -405,3 +405,10 @@ def test_app_set_context(app):
 
     retrieved = Sanic.get_app(app.name)
     assert retrieved.ctx.foo == 1
+
+
+def test_subclass_initialisation():
+    class CustomSanic(Sanic):
+        pass
+
+    CustomSanic("test_subclass_initialisation")
Repository: sanic-org/sanic

Issue:
Static files inside subfolders are not accessible (404)
**Describe the bug**

After upgrading from 20.12.3 to 21.3.0 I'm getting 404 for all my static files (those files are located inside subfolders), example:
GET http://127.0.0.1:8000/static/node_modules/jquery/dist/jquery.min.js 404

but static files that are located directly inside static folder are accessible, example:
GET http://127.0.0.1:8000/static/package.json 200

**Code snippet**
I added static in this way (it was working fine for Sanic <= 20.12.3):
`app.static("/static", "./static")`

I'm assuming the problem is in this line:
`uri += "/<__file_uri__>"`
https://github.com/sanic-org/sanic/blob/master/sanic/mixins/routes.py#L779
looks like there is no place for subfolders

**Expected behavior**
I expect static files inside subfolders to accessible.

**Environment (please complete the following information):**
 - OS: MacOS 11.2.3
 - Version 21.3.0 
 - Python 3.9.0

**Additional context**
This is a problem only for local environment, for prod static files are not served by Sanic



Discussion:
:unamused: I knew there was bound to be some bug with such sweeping changes. I will work on a patch for this and get a 21.3.1 out as soon as I can. We need to add this to test coverage as well.

Resolving patch:
diff --git a/examples/static_assets.py b/examples/static_assets.py
new file mode 100644
--- /dev/null
+++ b/examples/static_assets.py
@@ -0,0 +1,6 @@
+from sanic import Sanic
+
+
+app = Sanic(__name__)
+
+app.static("/", "./static")
diff --git a/sanic/__version__.py b/sanic/__version__.py
--- a/sanic/__version__.py
+++ b/sanic/__version__.py
@@ -1 +1 @@
-__version__ = "21.3.0"
+__version__ = "21.3.1"
diff --git a/sanic/mixins/routes.py b/sanic/mixins/routes.py
--- a/sanic/mixins/routes.py
+++ b/sanic/mixins/routes.py
@@ -776,7 +776,7 @@ def _register_static(
         # If we're not trying to match a file directly,
         # serve from the folder
         if not path.isfile(file_or_directory):
-            uri += "/<__file_uri__>"
+            uri += "/<__file_uri__:path>"
 
         # special prefix for static files
         # if not static.name.startswith("_static_"):


Test patch:
diff --git a/tests/static/nested/dir/foo.txt b/tests/static/nested/dir/foo.txt
new file mode 100644
--- /dev/null
+++ b/tests/static/nested/dir/foo.txt
@@ -0,0 +1 @@
+foo
diff --git a/tests/test_static.py b/tests/test_static.py
--- a/tests/test_static.py
+++ b/tests/test_static.py
@@ -445,3 +445,12 @@ def test_static_name(app, static_file_directory, static_name, file_name):
     request, response = app.test_client.get(f"/static/{file_name}")
 
     assert response.status == 200
+
+
+def test_nested_dir(app, static_file_directory):
+    app.static("/static", static_file_directory)
+
+    request, response = app.test_client.get("/static/nested/dir/foo.txt")
+
+    assert response.status == 200
+    assert response.text == "foo\n"
Repository: sanic-org/sanic

Issue:
Allow later websockets releases
**Describe the bug**
`websockets` is [pinned](https://github.com/sanic-org/sanic/blob/main/setup.py#L91
). The latest `websockets` is 9.1 and this release is fixing a [authentication vulnerability](https://websockets.readthedocs.io/en/stable/changelog.html) which was introduced with 8.0.

**Expected behavior**
Allow to use `websockets>9`

**Environment (please complete the following information):**
 - OS: probably all
 - Version: current

**Additional context**
n/a


Discussion:
Working on an implementation in #2000 that would resolve this.
Sanic isn't affected by the security vulnerability:

https://github.com/sanic-org/sanic/search?q=BasicAuthWebSocketServerProtocol
https://github.com/sanic-org/sanic/search?q=basic_auth_protocol_factory

Only downside of sticking with the old version: you'll get issues like this one.

Let me see if I can offer a PR to bump the dependency.

Resolving patch:
diff --git a/sanic/websocket.py b/sanic/websocket.py
--- a/sanic/websocket.py
+++ b/sanic/websocket.py
@@ -14,9 +14,13 @@
     ConnectionClosed,
     InvalidHandshake,
     WebSocketCommonProtocol,
-    handshake,
 )
 
+# Despite the "legacy" namespace, the primary maintainer of websockets
+# committed to maintaining backwards-compatibility until 2026 and will
+# consider extending it if sanic continues depending on this module.
+from websockets.legacy import handshake
+
 from sanic.exceptions import InvalidUsage
 from sanic.server import HttpProtocol
 
@@ -126,7 +130,9 @@ async def websocket_handshake(self, request, subprotocols=None):
             ping_interval=self.websocket_ping_interval,
             ping_timeout=self.websocket_ping_timeout,
         )
-        # Following two lines are required for websockets 8.x
+        # we use WebSocketCommonProtocol because we don't want the handshake
+        # logic from WebSocketServerProtocol; however, we must tell it that
+        # we're running on the server side
         self.websocket.is_client = False
         self.websocket.side = "server"
         self.websocket.subprotocol = subprotocol
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -88,12 +88,12 @@ def open_local(paths, mode="r", encoding="utf8"):
     uvloop,
     ujson,
     "aiofiles>=0.6.0",
-    "websockets>=8.1,<9.0",
+    "websockets>=9.0",
     "multidict>=5.0,<6.0",
 ]
 
 tests_require = [
-    "sanic-testing",
+    "sanic-testing>=0.6.0",
     "pytest==5.2.1",
     "multidict>=5.0,<6.0",
     "gunicorn==20.0.4",


Test patch:
Repository: sanic-org/sanic

Issue:
Request streaming results in a phantom 503
When streaming a request body, you end up with a phantom 503 response. To the client, everything looks fine. The data is transmitted, and a response received OK.

```
[2021-07-05 22:45:47 +0300] - (sanic.access)[INFO][127.0.0.1:34264]: POST http://localhost:9999/upload  201 4
[2021-07-05 22:45:47 +0300] - (sanic.access)[INFO][127.0.0.1:34264]: POST http://localhost:9999/upload  503 666
[2021-07-05 22:45:47 +0300] [686804] [ERROR] Connection lost before response written @ ('127.0.0.1', 34264) <Request: POST /upload>
```

But, there is an extra 503 that is caused by a task cancel while waiting on `receive_more`. This appears to be caused by leaving one extra CRLF in the buffer.


Discussion:

Resolving patch:
diff --git a/sanic/http.py b/sanic/http.py
--- a/sanic/http.py
+++ b/sanic/http.py
@@ -490,6 +490,9 @@ async def read(self) -> Optional[bytes]:
 
             if size <= 0:
                 self.request_body = None
+                # Because we are leaving one CRLF in the buffer, we manually
+                # reset the buffer here
+                self.recv_buffer = bytearray()
 
                 if size < 0:
                     self.keep_alive = False


Test patch:
Repository: sanic-org/sanic

Issue:
Sanic prints "auto-reload: enabled" even when auto_reload is False.
Kinda related to #2237 

https://github.com/sanic-org/sanic/blob/404c5f9f9eb54f06d1f30250bc2cc840c18a0eab/sanic/app.py#L1340



Discussion:
Message introduced in https://github.com/sanic-org/sanic/pull/2136
Can you provide an example?
```
app = Sanic("app")
if __name__ == "__main__"":
    app.run("127.0.0.1", 8080, debug=True, auto_reload=False)
```

Always Prints:
> "Sanic auto-reload: enabled"

Even though auto-reload is actually disabled.

Resolving patch:
diff --git a/sanic/app.py b/sanic/app.py
--- a/sanic/app.py
+++ b/sanic/app.py
@@ -1330,7 +1330,8 @@ def _helper(
                 logger.info(f"Goin' Fast @ {proto}://{host}:{port}")
 
         debug_mode = "enabled" if self.debug else "disabled"
-        logger.debug("Sanic auto-reload: enabled")
+        reload_mode = "enabled" if auto_reload else "disabled"
+        logger.debug(f"Sanic auto-reload: {reload_mode}")
         logger.debug(f"Sanic debug mode: {debug_mode}")
 
         return server_settings


Test patch: