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

Issue:
[Errno 13] Permission denied: '/access.log' with disabled debug & logging?
With:

```text
app.run(host=API_HOST, port=PORT, sock=None, debug=False, workers=API_WORKERS, log_config=None)
```

```text
app = Sanic(__name__)
  File "/usr/local/anaconda/envs/proj/lib/python3.6/site-packages/sanic/app.py", line 33, in __init__
    logging.config.dictConfig(log_config)
  File "/usr/local/anaconda/envs/proj/lib/python3.6/logging/config.py", line 795, in dictConfig
    dictConfigClass(config).configure()
  File "/usr/local/anaconda/envs/proj/lib/python3.6/logging/config.py", line 566, in configure
    '%r: %s' % (name, e))
ValueError: Unable to configure handler 'accessTimedRotatingFile': [Errno 13] Permission denied: '/access.log'
```


Discussion:
Same here..
Looks like it's trying to create that at the host root folder
Actually, it shouldn't create any log file at all.
I can't reproduce this. Can one of you give the full example you're using? Also the sanic version:

```
import sanic
sanic.__version__
'0.5.4'
```
Hi @r0fls, see this repo: https://github.com/woutor/sanic-logging
+1

Resolving patch:
diff --git a/sanic/app.py b/sanic/app.py
--- a/sanic/app.py
+++ b/sanic/app.py
@@ -33,7 +33,9 @@ def __init__(self, name=None, router=None, error_handler=None,
             logging.config.dictConfig(log_config)
         # Only set up a default log handler if the
         # end-user application didn't set anything up.
-        if not logging.root.handlers and log.level == logging.NOTSET:
+        if not (logging.root.handlers and
+                log.level == logging.NOTSET and
+                log_config):
             formatter = logging.Formatter(
                 "%(asctime)s: %(levelname)s: %(message)s")
             handler = logging.StreamHandler()


Test patch:
Repository: sanic-org/sanic

Issue:
Configs loaded from environmental variables aren't properly typed
When setting configs using environmental variables `export SANIC_REQUEST_TIMEOUT=30`

```
app = Sanic(__name__)
print(type(app.config.REQUEST_TIMEOUT))  #  <class 'str'>
```

The problem is in this function
```
# .../sanic/config.py
    def load_environment_vars(self):
        """
        Looks for any SANIC_ prefixed environment variables and applies
        them to the configuration if present.
        """
        for k, v in os.environ.items():
            if k.startswith(SANIC_PREFIX):
                _, config_key = k.split(SANIC_PREFIX, 1)
                self[config_key] = v  # os.environ values are always of type str
```



Discussion:
This could be solved by simply trying to cast `v` into `int` except `ValueError` then just leave it as string.
@mczp ya I was thinking that, but then I guess there could be other types as well.. :( 🤔  oh well, let's do that for now unless we come up with something better

Resolving patch:
diff --git a/sanic/config.py b/sanic/config.py
--- a/sanic/config.py
+++ b/sanic/config.py
@@ -201,4 +201,10 @@ def load_environment_vars(self):
         for k, v in os.environ.items():
             if k.startswith(SANIC_PREFIX):
                 _, config_key = k.split(SANIC_PREFIX, 1)
-                self[config_key] = v
+                try:
+                    self[config_key] = int(v)
+                except ValueError:
+                    try:
+                        self[config_key] = float(v)
+                    except ValueError:
+                        self[config_key] = v


Test patch:
Repository: sanic-org/sanic

Issue:
[Errno 13] Permission denied: '/access.log' with disabled debug & logging?
With:

```text
app.run(host=API_HOST, port=PORT, sock=None, debug=False, workers=API_WORKERS, log_config=None)
```

```text
app = Sanic(__name__)
  File "/usr/local/anaconda/envs/proj/lib/python3.6/site-packages/sanic/app.py", line 33, in __init__
    logging.config.dictConfig(log_config)
  File "/usr/local/anaconda/envs/proj/lib/python3.6/logging/config.py", line 795, in dictConfig
    dictConfigClass(config).configure()
  File "/usr/local/anaconda/envs/proj/lib/python3.6/logging/config.py", line 566, in configure
    '%r: %s' % (name, e))
ValueError: Unable to configure handler 'accessTimedRotatingFile': [Errno 13] Permission denied: '/access.log'
```


Discussion:
Same here..
Looks like it's trying to create that at the host root folder
Actually, it shouldn't create any log file at all.
I can't reproduce this. Can one of you give the full example you're using? Also the sanic version:

```
import sanic
sanic.__version__
'0.5.4'
```
Hi @r0fls, see this repo: https://github.com/woutor/sanic-logging
+1

Resolving patch:
diff --git a/sanic/app.py b/sanic/app.py
--- a/sanic/app.py
+++ b/sanic/app.py
@@ -33,9 +33,7 @@ def __init__(self, name=None, router=None, error_handler=None,
             logging.config.dictConfig(log_config)
         # Only set up a default log handler if the
         # end-user application didn't set anything up.
-        if not (logging.root.handlers and
-                log.level == logging.NOTSET and
-                log_config):
+        if not logging.root.handlers and log.level == logging.NOTSET:
             formatter = logging.Formatter(
                 "%(asctime)s: %(levelname)s: %(message)s")
             handler = logging.StreamHandler()


Test patch:
diff --git a/tests/test_logging.py b/tests/test_logging.py
--- a/tests/test_logging.py
+++ b/tests/test_logging.py
@@ -1,5 +1,7 @@
-import asyncio
 import uuid
+from importlib import reload
+
+from sanic.config import LOGGING
 from sanic.response import text
 from sanic import Sanic
 from io import StringIO
@@ -10,6 +12,11 @@
 message: %(message)s'''
 
 
+def reset_logging():
+    logging.shutdown()
+    reload(logging)
+
+
 def test_log():
     log_stream = StringIO()
     for handler in logging.root.handlers[:]:
@@ -32,5 +39,19 @@ def handler(request):
     log_text = log_stream.getvalue()
     assert rand_string in log_text
 
+
+def test_default_log_fmt():
+
+    reset_logging()
+    Sanic()
+    for fmt in [h.formatter for h in logging.getLogger('sanic').handlers]:
+        assert fmt._fmt == LOGGING['formatters']['simple']['format']
+
+    reset_logging()
+    Sanic(log_config=None)
+    for fmt in [h.formatter for h in logging.getLogger('sanic').handlers]:
+        assert fmt._fmt == "%(asctime)s: %(levelname)s: %(message)s"
+
+
 if __name__ == "__main__":
     test_log()
Repository: sanic-org/sanic

Issue:
0.5.5 release request
Because 0.5.4 has actual protocol parsing problem (#755)  I request to quickly release 0.5.5.

It causes actual request loss and unhandlable 400 errors for the sanic users. (unless they make local patch for sanic)


Discussion:
https://github.com/channelcat/sanic/issues/830

Resolving patch:
diff --git a/sanic/__init__.py b/sanic/__init__.py
--- a/sanic/__init__.py
+++ b/sanic/__init__.py
@@ -1,6 +1,6 @@
 from sanic.app import Sanic
 from sanic.blueprints import Blueprint
 
-__version__ = '0.5.4'
+__version__ = '0.6.0'
 
 __all__ = ['Sanic', 'Blueprint']


Test patch:
Repository: sanic-org/sanic

Issue:
Support blueprint static files per vhost
Right now, static files/folders (using app.static or bp.static) are served for all vhost.
I'd like Sanic to support static assets per vhost.



Discussion:

Resolving patch:
diff --git a/sanic/app.py b/sanic/app.py
--- a/sanic/app.py
+++ b/sanic/app.py
@@ -354,13 +354,13 @@ def middleware(self, middleware_or_request):
     # Static Files
     def static(self, uri, file_or_directory, pattern=r'/?.+',
                use_modified_since=True, use_content_range=False,
-               stream_large_files=False, name='static'):
+               stream_large_files=False, name='static', host=None):
         """Register a root to serve files from. The input can either be a
         file or a directory. See
         """
         static_register(self, uri, file_or_directory, pattern,
                         use_modified_since, use_content_range,
-                        stream_large_files, name)
+                        stream_large_files, name, host)
 
     def blueprint(self, blueprint, **options):
         """Register a blueprint on the application.
diff --git a/sanic/static.py b/sanic/static.py
--- a/sanic/static.py
+++ b/sanic/static.py
@@ -18,7 +18,7 @@
 
 def register(app, uri, file_or_directory, pattern,
              use_modified_since, use_content_range,
-             stream_large_files, name='static'):
+             stream_large_files, name='static', host=None):
     # TODO: Though sanic is not a file server, I feel like we should at least
     #       make a good effort here.  Modified-since is nice, but we could
     #       also look into etags, expires, and caching
@@ -122,4 +122,4 @@ async def _handler(request, file_uri=None):
     if not name.startswith('_static_'):
         name = '_static_{}'.format(name)
 
-    app.route(uri, methods=['GET', 'HEAD'], name=name)(_handler)
+    app.route(uri, methods=['GET', 'HEAD'], name=name, host=host)(_handler)


Test patch:
diff --git a/tests/test_static.py b/tests/test_static.py
--- a/tests/test_static.py
+++ b/tests/test_static.py
@@ -161,3 +161,20 @@ def test_static_content_range_error(file_name, static_file_directory):
     assert 'Content-Range' in response.headers
     assert response.headers['Content-Range'] == "bytes */%s" % (
         len(get_file_content(static_file_directory, file_name)),)
+
+
+@pytest.mark.parametrize('file_name', ['test.file', 'decode me.txt', 'python.png'])
+def test_static_file(static_file_directory, file_name):
+    app = Sanic('test_static')
+    app.static(
+        '/testing.file',
+        get_file_path(static_file_directory, file_name),
+        host="www.example.com"
+    )
+
+    headers = {"Host": "www.example.com"}
+    request, response = app.test_client.get('/testing.file', headers=headers)
+    assert response.status == 200
+    assert response.body == get_file_content(static_file_directory, file_name)
+    request, response = app.test_client.get('/testing.file')
+    assert response.status == 404
Repository: sanic-org/sanic

Issue:
Cookie secure option not encoded properly
When `Cookies.encode` encounters `response.cookies["<cookie>"]["secure"] = False` then it outputs:

`b'Domain=xad.com; Path=/; Secure=False'`

where it should output:

`b'Domain=xad.com; Path=/;'` when `response.cookies["<cookie>"]["secure"] = False`

and

`b'Domain=xad.com; Path=/; Secure;'` when `response.cookies["<cookie>"]["secure"] = True`


Discussion:

Resolving patch:
diff --git a/sanic/cookies.py b/sanic/cookies.py
--- a/sanic/cookies.py
+++ b/sanic/cookies.py
@@ -98,7 +98,8 @@ def __init__(self, key, value):
     def __setitem__(self, key, value):
         if key not in self._keys:
             raise KeyError("Unknown cookie property")
-        return super().__setitem__(key, value)
+        if value is not False:
+            return super().__setitem__(key, value)
 
     def encode(self, encoding):
         output = ['%s=%s' % (self.key, _quote(self.value))]


Test patch:
diff --git a/tests/test_cookies.py b/tests/test_cookies.py
--- a/tests/test_cookies.py
+++ b/tests/test_cookies.py
@@ -25,6 +25,25 @@ def handler(request):
     assert response.text == 'Cookies are: working!'
     assert response_cookies['right_back'].value == 'at you'
 
+@pytest.mark.parametrize("httponly,expected", [
+        (False, False),
+        (True, True),
+])
+def test_false_cookies_encoded(httponly, expected):
+    app = Sanic('test_text')
+
+    @app.route('/')
+    def handler(request):
+        response = text('hello cookies')
+        response.cookies['hello'] = 'world'
+        response.cookies['hello']['httponly'] = httponly
+        return text(response.cookies['hello'].encode('utf8'))
+
+    request, response = app.test_client.get('/')
+
+    assert ('HttpOnly' in response.text) == expected
+
+
 @pytest.mark.parametrize("httponly,expected", [
         (False, False),
         (True, True),
@@ -34,7 +53,7 @@ def test_false_cookies(httponly, expected):
 
     @app.route('/')
     def handler(request):
-        response = text('Cookies are: {}'.format(request.cookies['test']))
+        response = text('hello cookies')
         response.cookies['right_back'] = 'at you'
         response.cookies['right_back']['httponly'] = httponly
         return response
@@ -43,7 +62,7 @@ def handler(request):
     response_cookies = SimpleCookie()
     response_cookies.load(response.headers.get('Set-Cookie', {}))
 
-    'HttpOnly' in response_cookies == expected
+    assert ('HttpOnly' in response_cookies['right_back'].output()) == expected
 
 def test_http2_cookies():
     app = Sanic('test_http2_cookies')
Repository: sanic-org/sanic

Issue:
0.6.1 release to PyPi
Hey folks,

There's been a bunch of substantive changes in the past few months; I think it warrants a release of 0.6.1 (or 0.7, considering there may be large changes in PRs like #939). Any chance we could get a new candidate uploaded to PyPi? 

If there's a better place to ask this, I'm happy to head there.


Discussion:
I'll make some time to do a full `0.7.0` release this week
cc @r0fls 
Thanks! 
Please update the CHANGELOG as well!
@pikeas 
I think the changelog has been abandoned at this point. There has been a _lot_ of releases since it was last updated. For now, the best way to see changes is in the Releases page on github, here: https://github.com/channelcat/sanic/releases

@seemethere 
Do you still plan to do a 0.7.0 release soon? Is there anymore testing or QC you need before it is released, given the large number of changes since 0.6.0, including my commits in #939 ?

For what its worth, I am using Sanic@master in a semi-production application at work and it's performing great.
Any updates on the v0.7 release @seemethere?
If you're too busy at the moment @seemethere, isn't there someone else who can release 0.7.0?

Resolving patch:
diff --git a/sanic/__init__.py b/sanic/__init__.py
--- a/sanic/__init__.py
+++ b/sanic/__init__.py
@@ -1,6 +1,6 @@
 from sanic.app import Sanic
 from sanic.blueprints import Blueprint
 
-__version__ = '0.6.0'
+__version__ = '0.7.0'
 
 __all__ = ['Sanic', 'Blueprint']


Test patch:
Repository: sanic-org/sanic

Issue:
Accessing app in a background task
The example in the docs shows a nice way of scheduling a long-running task:

```python
async def notify_server_started_after_five_seconds():
    await asyncio.sleep(5)
    print('Server successfully started!')

app.add_task(notify_server_started_after_five_seconds())
```

If I've stashed my `notify_server_started_after_five_seconds()` function in `tasks.py`, What's the best way to access the `app` instance from it?

I've looked at dirty solutions like making `app` global... but I'm surprised that `app` and `loop` don't get injected like they do on the decorated methods.

Thanks in advance!


Discussion:

Resolving patch:
diff --git a/sanic/app.py b/sanic/app.py
--- a/sanic/app.py
+++ b/sanic/app.py
@@ -88,14 +88,20 @@ def add_task(self, task):
         """
         try:
             if callable(task):
-                self.loop.create_task(task())
+                try:
+                    self.loop.create_task(task(self))
+                except TypeError:
+                    self.loop.create_task(task())
             else:
                 self.loop.create_task(task)
         except SanicException:
             @self.listener('before_server_start')
             def run(app, loop):
                 if callable(task):
-                    loop.create_task(task())
+                    try:
+                        loop.create_task(task(self))
+                    except TypeError:
+                        loop.create_task(task())
                 else:
                     loop.create_task(task)
 


Test patch:
diff --git a/tests/test_create_task.py b/tests/test_create_task.py
--- a/tests/test_create_task.py
+++ b/tests/test_create_task.py
@@ -2,6 +2,7 @@
 from sanic.response import text
 from threading import Event
 import asyncio
+from queue import Queue
 
 
 def test_create_task():
@@ -28,3 +29,19 @@ async def set(request):
 
     request, response = app.test_client.get('/late')
     assert response.body == b'True'
+
+def test_create_task_with_app_arg():
+    app = Sanic('test_add_task')
+    q = Queue()
+
+    @app.route('/')
+    def not_set(request):
+        return "hello"
+
+    async def coro(app):
+        q.put(app.name)
+
+    app.add_task(coro)
+
+    request, response = app.test_client.get('/')
+    assert q.get() == 'test_add_task'
Repository: sanic-org/sanic

Issue:
restrictive call to handlers from sanic.handlers.ErrorHandler.response
`sanic.handlers.ErrorHandler.response` use keywords arguments on handler call and so force the signature of the handler

Consider this very basic application:

```python
from sanic import Sanic
from sanic.exceptions import SanicException
from sanic.response import text

app = Sanic()

@app.exception(SanicException)
def http_error_handler(request, exception):
	return text(":(")

app.run()
```

it works as intended:

	$ python server.py 
	[2018-02-21 00:35:04 +0100] [23560] [INFO] Goin' Fast @ http://127.0.0.1:8000
	[2018-02-21 00:35:04 +0100] [23560] [INFO] Starting worker [23560]
	[2018-02-21 00:35:16 +0100] - (sanic.access)[INFO][1:2]: GET http://127.0.0.1:8000/  200 2
	[2018-02-21 00:36:01 +0100] [23560] [INFO] Stopping worker [23560]
	[2018-02-21 00:36:01 +0100] [23560] [INFO] Server Stopped

But you cannot change the argument names:

```python
@app.exception(SanicException)
def http_error_handler(req, exc):
	return text(":(")
```

because `ErrorHandler.response` use keyword arguments:

	$ python server.py 
	[2018-02-21 00:36:02 +0100] [23608] [INFO] Goin' Fast @ http://127.0.0.1:8000
	[2018-02-21 00:36:02 +0100] [23608] [INFO] Starting worker [23608]
	[2018-02-21 00:36:05 +0100] [23608] [ERROR] Traceback (most recent call last):
	  File "[..]/sanic/app.py", line 546, in handle_request
	    handler, args, kwargs, uri = self.router.get(request)
	  File "[..]/sanic/router.py", line 344, in get
	    return self._get(request.path, request.method, '')
	  File "[..]/sanic/router.py", line 393, in _get
	    raise NotFound('Requested URL {} not found'.format(url))
	sanic.exceptions.NotFound: Requested URL / not found

	During handling of the above exception, another exception occurred:

	Traceback (most recent call last):
	  File "[..]/sanic/handlers.py", line 82, in response
	    response = handler(request=request, exception=exception)
	TypeError: http_error_handler() got an unexpected keyword argument 'request'

	[2018-02-21 00:36:05 +0100] - (sanic.access)[INFO][1:2]: GET http://127.0.0.1:8000/  500 41
	[2018-02-21 00:36:10 +0100] [23608] [INFO] KeepAlive Timeout. Closing connection.
	[2018-02-21 00:38:27 +0100] [23608] [INFO] Stopping worker [23608]
	[2018-02-21 00:38:27 +0100] [23608] [INFO] Server Stopped


A pull request is coming shortly to use regular arguments instead of keywords in the `ErrorHandler.response`.


Discussion:

Resolving patch:
diff --git a/sanic/handlers.py b/sanic/handlers.py
--- a/sanic/handlers.py
+++ b/sanic/handlers.py
@@ -79,9 +79,9 @@ def response(self, request, exception):
         response = None
         try:
             if handler:
-                response = handler(request=request, exception=exception)
+                response = handler(request, exception)
             if response is None:
-                response = self.default(request=request, exception=exception)
+                response = self.default(request, exception)
         except Exception:
             self.log(format_exc())
             if self.debug:


Test patch:
Repository: sanic-org/sanic

Issue:
Sanic `Request` object is falsey
```python
@app.route('/myroute')
async def someroute(request):
    if request:
        return 'some data'
    raise Exception("Woops")
```

This code will raise the exception because `bool(request)` is `False`. 


Discussion:

Resolving patch:
diff --git a/sanic/request.py b/sanic/request.py
--- a/sanic/request.py
+++ b/sanic/request.py
@@ -78,6 +78,11 @@ def __repr__(self):
                                        self.method,
                                        self.path)
 
+    def __bool__(self):
+        if self.transport:
+            return True
+        return False
+
     @property
     def json(self):
         if self.parsed_json is None:


Test patch:
Repository: sanic-org/sanic

Issue:
Possible memory leak in websocket_handler function
Hey! It seems that I found a possible memory leak in `websocket_handler` function inside `Sanic.websocket` https://github.com/channelcat/sanic/blob/master/sanic/app.py#L301

If arbitrary exception occurred in websocket handler, it won't be catched down there and `fut` object will stay in `self.websocket_tasks` list. Little by little this list will become bigger and will consume more memory.

Probably it makes sense to catch all exceptions in `try: except:` block, not only `(CancelledError, ConnectionClosed)`?


Discussion:

Resolving patch:
diff --git a/sanic/app.py b/sanic/app.py
--- a/sanic/app.py
+++ b/sanic/app.py
@@ -303,7 +303,8 @@ async def websocket_handler(request, *args, **kwargs):
                     await fut
                 except (CancelledError, ConnectionClosed):
                     pass
-                self.websocket_tasks.remove(fut)
+                finally:
+                    self.websocket_tasks.remove(fut)
                 await ws.close()
 
             self.router.add(uri=uri, handler=websocket_handler,


Test patch:
Repository: sanic-org/sanic

Issue:
Pin versions for LTS release
I think that versions of (some) should be allowed to float but when we are ready for an LTS release, the versions should be pinned at that time.

@r0fls @ahopkins @seemethere @ashleysommer @yunstanford @ahopkins 


Discussion:
@sjsadowski if we pin `httptools` to be `>=0.0.10`, then we can tackle #1057 (I don't know if we re-open it or create another related issue) :wink:
@vltr I'm going to branch today for the LTS release, we can set pins there. I'm actually okay (if we can get enough interest) with pinning a minimum version of httptools in master as well.
@sjsadowski oh yes, pinning `httptools` would make a lot of developers happy around here ...
@vltr let's do it. I have not seen anything that suggest that should not be done. Can you get a PR in and we'll merge it after someone upchecks it. I'm hoping to get the other current PRs in this week after review and then merge them up to the 18.12 LTS branch.
@sjsadowski sure thing! Let me see if this will not conflict with #1310 (dumb one here forgot to create a branch for it ... :grimacing:)

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -56,7 +56,7 @@ def open_local(paths, mode='r', encoding='utf8'):
 uvloop = 'uvloop>=0.5.3' + env_dependency
 
 requirements = [
-    'httptools>=0.0.9',
+    'httptools>=0.0.10',
     uvloop,
     ujson,
     'aiofiles>=0.3.0',


Test patch:
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.

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__ = "18.12.0"
+__version__ = "19.03.0"
 
 __all__ = ["Sanic", "Blueprint"]


Test patch: