Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 5 additions & 102 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,6 @@ Note that this example assumes that the

# examples/things_advanced.py

import json
import logging
import uuid
from wsgiref import simple_server
Expand Down Expand Up @@ -533,45 +532,6 @@ Note that this example assumes that the
)


class JSONTranslator:
# NOTE: Normally you would simply use req.media and resp.media for
# this particular use case; this example serves only to illustrate
# what is possible.

def process_request(self, req, resp):
# req.stream corresponds to the WSGI wsgi.input environ variable,
# and allows you to read bytes from the request body.
#
# See also: PEP 3333
if req.content_length in (None, 0):
# Nothing to do
return

body = req.bounded_stream.read()
if not body:
raise falcon.HTTPBadRequest(
title='Empty request body',
description='A valid JSON document is required.',
)

try:
req.context.doc = json.loads(body.decode('utf-8'))

except (ValueError, UnicodeDecodeError):
description = (
'Could not decode the request body. The '
'JSON was incorrect or not encoded as '
'UTF-8.'
)

raise falcon.HTTPBadRequest(title='Malformed JSON', description=description)

def process_response(self, req, resp, resource, req_succeeded):
if not hasattr(resp.context, 'result'):
return

resp.text = json.dumps(resp.context.result)


def max_body(limit):
def hook(req, resp, resource, params):
Expand Down Expand Up @@ -613,24 +573,14 @@ Note that this example assumes that the
title='Service Outage', description=description, retry_after=30
)

# NOTE: Normally you would use resp.media for this sort of thing;
# this example serves only to demonstrate how the context can be
# used to pass arbitrary values between middleware components,
# hooks, and resources.
resp.context.result = result
resp.media = result

resp.set_header('Powered-By', 'Falcon')
resp.status = falcon.HTTP_200

@falcon.before(max_body(64 * 1024))
def on_post(self, req, resp, user_id):
try:
doc = req.context.doc
except AttributeError:
raise falcon.HTTPBadRequest(
title='Missing thing',
description='A thing must be submitted in the request body.',
)
doc = req.get_media()

proper_thing = self.db.add_thing(doc)

Expand All @@ -643,7 +593,6 @@ Note that this example assumes that the
middleware=[
AuthMiddleware(),
RequireJSON(),
JSONTranslator(),
]
)

Expand All @@ -661,7 +610,7 @@ Note that this example assumes that the
sink = SinkAdapter()
app.add_sink(sink, r'/search/(?P<engine>ddg|y)\Z')

# Useful for debugging problems in your API; works with pdb.set_trace(). You
# Useful for debugging problems in your App; works with pdb.set_trace(). You
# can also use Gunicorn to host your app. Gunicorn can be configured to
# auto-restart workers when it detects a code change, and it also works
# with pdb.
Expand Down Expand Up @@ -708,7 +657,6 @@ Here's the ASGI version of the app from above. Note that it uses the

# examples/things_advanced_asgi.py

import json
import logging
import uuid

Expand Down Expand Up @@ -799,41 +747,6 @@ Here's the ASGI version of the app from above. Note that it uses the
href='http://docs.examples.com/api/json')


class JSONTranslator:
# NOTE: Normally you would simply use req.get_media() and resp.media for
# this particular use case; this example serves only to illustrate
# what is possible.

async def process_request(self, req, resp):
# NOTE: Test explicitly for 0, since this property could be None in
# the case that the Content-Length header is missing (in which case we
# can't know if there is a body without actually attempting to read
# it from the request stream.)
if req.content_length == 0:
# Nothing to do
return

body = await req.stream.read()
if not body:
raise falcon.HTTPBadRequest(title='Empty request body',
description='A valid JSON document is required.')

try:
req.context.doc = json.loads(body.decode('utf-8'))

except (ValueError, UnicodeDecodeError):
description = ('Could not decode the request body. The '
'JSON was incorrect or not encoded as '
'UTF-8.')

raise falcon.HTTPBadRequest(title='Malformed JSON',
description=description)

async def process_response(self, req, resp, resource, req_succeeded):
if not hasattr(resp.context, 'result'):
return

resp.text = json.dumps(resp.context.result)


def max_body(limit):
Expand Down Expand Up @@ -874,23 +787,14 @@ Here's the ASGI version of the app from above. Note that it uses the
description=description,
retry_after=30)

# NOTE: Normally you would use resp.media for this sort of thing;
# this example serves only to demonstrate how the context can be
# used to pass arbitrary values between middleware components,
# hooks, and resources.
resp.context.result = result
resp.media = result

resp.set_header('Powered-By', 'Falcon')
resp.status = falcon.HTTP_200

@falcon.before(max_body(64 * 1024))
async def on_post(self, req, resp, user_id):
try:
doc = req.context.doc
except AttributeError:
raise falcon.HTTPBadRequest(
title='Missing thing',
description='A thing must be submitted in the request body.')
doc = await req.get_media()

proper_thing = await self.db.add_thing(doc)

Expand All @@ -902,7 +806,6 @@ Here's the ASGI version of the app from above. Note that it uses the
app = falcon.asgi.App(middleware=[
# AuthMiddleware(),
RequireJSON(),
JSONTranslator(),
])

db = StorageEngine()
Expand Down
56 changes: 2 additions & 54 deletions examples/things_advanced.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
# examples/things_advanced.py

import json
import logging
import uuid
from wsgiref import simple_server
Expand Down Expand Up @@ -92,46 +91,6 @@ def process_request(self, req, resp):
)


class JSONTranslator:
# NOTE: Normally you would simply use req.media and resp.media for
# this particular use case; this example serves only to illustrate
# what is possible.

def process_request(self, req, resp):
# req.stream corresponds to the WSGI wsgi.input environ variable,
# and allows you to read bytes from the request body.
#
# See also: PEP 3333
if req.content_length in (None, 0):
# Nothing to do
return

body = req.bounded_stream.read()
if not body:
raise falcon.HTTPBadRequest(
title='Empty request body',
description='A valid JSON document is required.',
)

try:
req.context.doc = json.loads(body.decode('utf-8'))

except (ValueError, UnicodeDecodeError):
description = (
'Could not decode the request body. The '
'JSON was incorrect or not encoded as '
'UTF-8.'
)

raise falcon.HTTPBadRequest(title='Malformed JSON', description=description)

def process_response(self, req, resp, resource, req_succeeded):
if not hasattr(resp.context, 'result'):
return

resp.text = json.dumps(resp.context.result)


def max_body(limit):
def hook(req, resp, resource, params):
length = req.content_length
Expand Down Expand Up @@ -172,24 +131,14 @@ def on_get(self, req, resp, user_id):
title='Service Outage', description=description, retry_after=30
)

# NOTE: Normally you would use resp.media for this sort of thing;
# this example serves only to demonstrate how the context can be
# used to pass arbitrary values between middleware components,
# hooks, and resources.
resp.context.result = result
resp.media = result

resp.set_header('Powered-By', 'Falcon')
resp.status = falcon.HTTP_200

@falcon.before(max_body(64 * 1024))
def on_post(self, req, resp, user_id):
try:
doc = req.context.doc
except AttributeError:
raise falcon.HTTPBadRequest(
title='Missing thing',
description='A thing must be submitted in the request body.',
)
doc = req.get_media()

proper_thing = self.db.add_thing(doc)

Expand All @@ -202,7 +151,6 @@ def on_post(self, req, resp, user_id):
middleware=[
AuthMiddleware(),
RequireJSON(),
JSONTranslator(),
]
)

Expand Down
56 changes: 2 additions & 54 deletions examples/things_advanced_asgi.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
# examples/things_advanced_asgi.py

import json
import logging
import uuid

Expand Down Expand Up @@ -94,46 +93,6 @@ async def process_request(self, req, resp):
)


class JSONTranslator:
# NOTE: Normally you would simply use req.get_media() and resp.media for
# this particular use case; this example serves only to illustrate
# what is possible.

async def process_request(self, req, resp):
# NOTE: Test explicitly for 0, since this property could be None in
# the case that the Content-Length header is missing (in which case we
# can't know if there is a body without actually attempting to read
# it from the request stream.)
if req.content_length == 0:
# Nothing to do
return

body = await req.stream.read()
if not body:
raise falcon.HTTPBadRequest(
title='Empty request body',
description='A valid JSON document is required.',
)

try:
req.context.doc = json.loads(body.decode('utf-8'))

except (ValueError, UnicodeDecodeError):
description = (
'Could not decode the request body. The '
'JSON was incorrect or not encoded as '
'UTF-8.'
)

raise falcon.HTTPBadRequest(title='Malformed JSON', description=description)

async def process_response(self, req, resp, resource, req_succeeded):
if not hasattr(resp.context, 'result'):
return

resp.text = json.dumps(resp.context.result)


def max_body(limit):
async def hook(req, resp, resource, params):
length = req.content_length
Expand Down Expand Up @@ -174,24 +133,14 @@ async def on_get(self, req, resp, user_id):
title='Service Outage', description=description, retry_after=30
)

# NOTE: Normally you would use resp.media for this sort of thing;
# this example serves only to demonstrate how the context can be
# used to pass arbitrary values between middleware components,
# hooks, and resources.
resp.context.result = result
resp.media = result

resp.set_header('Powered-By', 'Falcon')
resp.status = falcon.HTTP_200

@falcon.before(max_body(64 * 1024))
async def on_post(self, req, resp, user_id):
try:
doc = req.context.doc
except AttributeError:
raise falcon.HTTPBadRequest(
title='Missing thing',
description='A thing must be submitted in the request body.',
)
doc = await req.get_media()

proper_thing = await self.db.add_thing(doc)

Expand All @@ -204,7 +153,6 @@ async def on_post(self, req, resp, user_id):
middleware=[
AuthMiddleware(),
RequireJSON(),
JSONTranslator(),
]
)

Expand Down