Skip to content

Commit

Permalink
Reformatted code to use spaces instead of tabs
Browse files Browse the repository at this point in the history
  • Loading branch information
channelcat committed Oct 15, 2016
1 parent 67db0bc commit 254861b
Show file tree
Hide file tree
Showing 21 changed files with 347 additions and 269 deletions.
6 changes: 4 additions & 2 deletions examples/simple_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@

app = Sanic(__name__)


@app.route("/")
async def test(request):
return json({ "test": True })
return json({"test": True})


app.run(host="0.0.0.0", port=8000)
app.run(host="0.0.0.0", port=8000)
28 changes: 19 additions & 9 deletions examples/try_everything.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,55 +5,65 @@

app = Sanic(__name__)


@app.route("/")
async def test_async(request):
return json({ "test": True })

return json({"test": True})


@app.route("/sync", methods=['GET', 'POST'])
def test_sync(request):
return json({ "test": True })
return json({"test": True})


@app.route("/dynamic/<name>/<id:int>")
def test_params(request, name, id):
return text("yeehaww {} {}".format(name, id))


@app.route("/exception")
def exception(request):
raise ServerError("It's dead jim")


# ----------------------------------------------- #
# Exceptions
# ----------------------------------------------- #

@app.exception(ServerError)
async def test(request, exception):
return json({ "exception": "{}".format(exception), "status": exception.status_code }, status=exception.status_code)
return json({"exception": "{}".format(exception), "status": exception.status_code}, status=exception.status_code)


# ----------------------------------------------- #
# Read from request
# ----------------------------------------------- #

@app.route("/json")
def post_json(request):
return json({ "received": True, "message": request.json })
return json({"received": True, "message": request.json})


@app.route("/form")
def post_json(request):
return json({ "received": True, "form_data": request.form, "test": request.form.get('test') })
return json({"received": True, "form_data": request.form, "test": request.form.get('test')})


@app.route("/query_string")
def query_string(request):
return json({ "parsed": True, "args": request.args, "url": request.url, "query_string": request.query_string })
return json({"parsed": True, "args": request.args, "url": request.url, "query_string": request.query_string})


# ----------------------------------------------- #
# Run Server
# ----------------------------------------------- #

def after_start(loop):
log.info("OH OH OH OH OHHHHHHHH")


def before_stop(loop):
log.info("TRIED EVERYTHING")

app.run(host="0.0.0.0", port=8000, debug=True, after_start=after_start, before_stop=before_stop)


app.run(host="0.0.0.0", port=8000, debug=True, after_start=after_start, before_stop=before_stop)
2 changes: 1 addition & 1 deletion sanic/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
from .sanic import Sanic
from .sanic import Sanic
4 changes: 2 additions & 2 deletions sanic/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,5 @@ class Config:
▌ ▐ ▀▀▄▄▄▀
▀▀▄▄▀
"""
REQUEST_MAX_SIZE = 100000000 # 100 megababies
REQUEST_TIMEOUT = 60 # 60 seconds
REQUEST_MAX_SIZE = 100000000 # 100 megababies
REQUEST_TIMEOUT = 60 # 60 seconds
74 changes: 41 additions & 33 deletions sanic/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,43 +1,51 @@
from .response import text
from traceback import format_exc


class SanicException(Exception):
def __init__(self, message, status_code=None):
super().__init__(message)
if status_code is not None:
self.status_code = status_code
def __init__(self, message, status_code=None):
super().__init__(message)
if status_code is not None:
self.status_code = status_code


class NotFound(SanicException):
status_code = 404
status_code = 404


class InvalidUsage(SanicException):
status_code = 400
status_code = 400


class ServerError(SanicException):
status_code = 500
status_code = 500


class Handler:
handlers = None
def __init__(self, sanic):
self.handlers = {}
self.sanic = sanic

def add(self, exception, handler):
self.handlers[exception] = handler

def response(self, request, exception):
"""
Fetches and executes an exception handler and returns a reponse object
:param request: Request
:param exception: Exception to handle
:return: Response object
"""
handler = self.handlers.get(type(exception), self.default)
response = handler(request=request, exception=exception)
return response

def default(self, request, exception):
if issubclass(type(exception), SanicException):
return text("Error: {}".format(exception), status=getattr(exception, 'status_code', 500))
elif self.sanic.debug:
return text("Error: {}\nException: {}".format(exception, format_exc()), status=500)
else:
return text("An error occurred while generating the request", status=500)
handlers = None

def __init__(self, sanic):
self.handlers = {}
self.sanic = sanic

def add(self, exception, handler):
self.handlers[exception] = handler

def response(self, request, exception):
"""
Fetches and executes an exception handler and returns a reponse object
:param request: Request
:param exception: Exception to handle
:return: Response object
"""
handler = self.handlers.get(type(exception), self.default)
response = handler(request=request, exception=exception)
return response

def default(self, request, exception):
if issubclass(type(exception), SanicException):
return text("Error: {}".format(exception), status=getattr(exception, 'status_code', 500))
elif self.sanic.debug:
return text("Error: {}\nException: {}".format(exception, format_exc()), status=500)
else:
return text("An error occurred while generating the request", status=500)
2 changes: 1 addition & 1 deletion sanic/log.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import logging

logging.basicConfig(level=logging.INFO, format="%(asctime)s: %(levelname)s: %(message)s")
log = logging.getLogger(__name__)
log = logging.getLogger(__name__)
6 changes: 3 additions & 3 deletions sanic/middleware.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
class Middleware:
def __init__(self, process_request=None, process_response=None):
self.process_request = process_request
self.process_response = process_response
def __init__(self, process_request=None, process_response=None):
self.process_request = process_request
self.process_response = process_response
15 changes: 11 additions & 4 deletions sanic/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,25 @@

from .log import log


class RequestParameters(dict):
"""
Hosts a dict with lists as values where get returns the first
value of the list and getlist returns the whole shebang
"""

def __init__(self, *args, **kwargs):
self.super = super()
self.super.__init__(*args, **kwargs)

def get(self, name, default=None):
values = self.super.get(name)
return values[0] if values else default

def getlist(self, name, default=None):
return self.super.get(name, default)


class Request:
__slots__ = (
'url', 'headers', 'version', 'method',
Expand Down Expand Up @@ -75,7 +80,7 @@ def form(self):
@property
def files(self):
if self.parsed_files is None:
_ = self.form # compute form to get files
_ = self.form # compute form to get files

return self.parsed_files

Expand All @@ -89,7 +94,10 @@ def args(self):

return self.parsed_args


File = namedtuple('File', ['type', 'body', 'name'])


def parse_multipart_form(body, boundary):
"""
Parses a request body and returns fields and files
Expand Down Expand Up @@ -117,7 +125,7 @@ def parse_multipart_form(body, boundary):

colon_index = form_line.index(':')
form_header_field = form_line[0:colon_index]
form_header_value, form_parameters = parse_header(form_line[colon_index+2:])
form_header_value, form_parameters = parse_header(form_line[colon_index + 2:])

if form_header_field == 'Content-Disposition':
if 'filename' in form_parameters:
Expand All @@ -126,11 +134,10 @@ def parse_multipart_form(body, boundary):
elif form_header_field == 'Content-Type':
file_type = form_header_value


post_data = form_part[line_index:-4]
if file_name or file_type:
files[field_name] = File(type=file_type, name=file_name, body=post_data)
else:
fields[field_name] = post_data.decode('utf-8')

return fields, files
return fields, files
28 changes: 18 additions & 10 deletions sanic/response.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
504: 'Gateway Timeout',
}


class HTTPResponse:
__slots__ = ('body', 'status', 'content_type', 'headers')

Expand All @@ -43,18 +44,25 @@ def output(self, version="1.1", keep_alive=False, keep_alive_timeout=None):
additional_headers.append('{}: {}\r\n'.format(name, value).encode('utf-8'))

return b''.join([
'HTTP/{} {} {}\r\n'.format(version, self.status, STATUS_CODES.get(self.status, 'FAIL')).encode(),
b'Content-Type: ', self.content_type.encode(), b'\r\n',
b'Content-Length: ', str(len(self.body)).encode(), b'\r\n',
b'Connection: ', ('keep-alive' if keep_alive else 'close').encode(), b'\r\n',
] + additional_headers + [
b'\r\n',
self.body,
])
'HTTP/{} {} {}\r\n'.format(version, self.status,
STATUS_CODES.get(self.status, 'FAIL')).encode(),
b'Content-Type: ', self.content_type.encode(), b'\r\n',
b'Content-Length: ', str(len(self.body)).encode(), b'\r\n',
b'Connection: ', ('keep-alive' if keep_alive else 'close').encode(), b'\r\n',
] + additional_headers + [
b'\r\n',
self.body,
])


def json(body, status=200, headers=None):
return HTTPResponse(ujson.dumps(body), headers=headers, status=status, content_type="application/json; charset=utf-8")
return HTTPResponse(ujson.dumps(body), headers=headers, status=status,
content_type="application/json; charset=utf-8")


def text(body, status=200, headers=None):
return HTTPResponse(body, status=status, headers=headers, content_type="text/plain; charset=utf-8")


def html(body, status=200, headers=None):
return HTTPResponse(body, status=status, headers=headers, content_type="text/html; charset=utf-8")
return HTTPResponse(body, status=status, headers=headers, content_type="text/html; charset=utf-8")
15 changes: 10 additions & 5 deletions sanic/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
Route = namedtuple("Route", ['handler', 'methods', 'pattern', 'parameters'])
Parameter = namedtuple("Parameter", ['name', 'cast'])


class Router:
"""
Router supports basic routing with parameters and method checks
Expand Down Expand Up @@ -42,9 +43,10 @@ def add(self, uri, methods, handler):
"""

# Dict for faster lookups of if method allowed
methods_dict = { method: True for method in methods } if methods else None
methods_dict = {method: True for method in methods} if methods else None

parameters = []

def add_parameter(match):
# We could receive NAME or NAME:PATTERN
parts = match.group(1).split(':')
Expand Down Expand Up @@ -93,11 +95,13 @@ def get(self, request):

if route:
if route.methods and not request.method in route.methods:
raise InvalidUsage("Method {} not allowed for URL {}".format(request.method, request.url), status_code=405)
raise InvalidUsage("Method {} not allowed for URL {}".format(request.method, request.url),
status_code=405)
return route.handler, args, kwargs
else:
raise NotFound("Requested URL {} not found".format(request.url))


class SimpleRouter:
"""
Simple router records and reads all routes from a dictionary
Expand All @@ -110,14 +114,15 @@ def __init__(self):

def add(self, uri, methods, handler):
# Dict for faster lookups of method allowed
methods_dict = { method: True for method in methods } if methods else None
methods_dict = {method: True for method in methods} if methods else None
self.routes[uri] = Route(handler=handler, methods=methods_dict, pattern=uri, parameters=None)

def get(self, request):
route = self.routes.get(request.url)
if route:
if route.methods and not request.method in route.methods:
raise InvalidUsage("Method {} not allowed for URL {}".format(request.method, request.url), status_code=405)
raise InvalidUsage("Method {} not allowed for URL {}".format(request.method, request.url),
status_code=405)
return route.handler, [], {}
else:
raise NotFound("Requested URL {} not found".format(request.url))
raise NotFound("Requested URL {} not found".format(request.url))
Loading

0 comments on commit 254861b

Please sign in to comment.