Improve example

This commit is contained in:
38elements 2017-05-13 23:01:35 +09:00
parent 220396018b
commit e31de53e2f
14 changed files with 53 additions and 84 deletions

View File

@ -1,7 +1,9 @@
"""
Example intercepting uncaught exceptions using Sanic's error handler framework.
This may be useful for developers wishing to use Sentry, Airbrake, etc.
or a custom system to log and monitor unexpected errors in production.
First we create our own class inheriting from Handler in sanic.exceptions,
and pass in an instance of it when we create our Sanic instance. Inside this
class' default handler, we can do anything including sending exceptions to
@ -37,7 +39,7 @@ server's error_handler to an instance of our CustomHandler
"""
from sanic import Sanic
from sanic import response
from sanic.response import json
app = Sanic(__name__)
@ -50,7 +52,7 @@ async def test(request):
# Here, something occurs which causes an unexpected exception
# This exception will flow to our custom handler.
1 / 0
return response.json({"test": True})
return json({"test": True})
app.run(host="0.0.0.0", port=8000, debug=True)
app.run(host="127.0.0.1", port=8000, debug=True)

View File

@ -2,7 +2,7 @@
# the project
from sanic import Sanic
from sanic import response
from sanic.response import html
from jinja2 import Environment, PackageLoader, select_autoescape
app = Sanic(__name__)
@ -22,7 +22,7 @@ template = template_env.get_template("example_template.html")
async def test(request):
rendered_template = await template.render_async(
knights='that say nih; asynchronously')
return response.html(rendered_template)
return html(rendered_template)
app.run(host="0.0.0.0", port=8080, debug=True)
app.run(host="127.0.0.1", port=8080)

View File

@ -1,26 +0,0 @@
"""
Modify header or status in response
"""
from sanic import Sanic
from sanic import response
app = Sanic(__name__)
@app.route('/')
def handle_request(request):
return response.json(
{'message': 'Hello world!'},
headers={'X-Served-By': 'sanic'},
status=200
)
@app.route('/unauthorized')
def handle_request(request):
return response.json(
{'message': 'You are not authorized'},
headers={'X-Served-By': 'sanic'},
status=404
)
app.run(host="0.0.0.0", port=8000, debug=True)

View File

@ -1,5 +1,5 @@
from sanic import Sanic
from sanic import response
from sanic.response import text
import logging
logging_format = "[%(asctime)s] %(process)d-%(levelname)s "
@ -14,9 +14,12 @@ log = logging.getLogger()
# Set logger to override default basicConfig
sanic = Sanic()
@sanic.route("/")
def test(request):
log.info("received request; responding with 'hey'")
return response.text("hey")
return text("hey")
sanic.run(host="0.0.0.0", port=8000)
sanic.run(host="127.0.0.1", port=8000)

View File

@ -1,6 +1,6 @@
import asyncio
from sanic import Sanic
from sanic import response
from sanic.response import text
from sanic.config import Config
from sanic.exceptions import RequestTimeout
@ -11,11 +11,12 @@ app = Sanic(__name__)
@app.route('/')
async def test(request):
await asyncio.sleep(3)
return response.text('Hello, world!')
return text('Hello, world!')
@app.exception(RequestTimeout)
def timeout(request, exception):
return response.text('RequestTimeout from error_handler.', 408)
return text('RequestTimeout from error_handler.', 408)
app.run(host='0.0.0.0', port=8000)
app.run(host='127.0.0.1', port=8000)

View File

@ -5,7 +5,7 @@ motor==1.1
sanic==0.2.0
"""
from sanic import Sanic
from sanic import response
from sanic.response import json
app = Sanic('motor_mongodb')
@ -25,7 +25,7 @@ async def get(request):
for doc in docs:
doc['id'] = str(doc['_id'])
del doc['_id']
return response.json(docs)
return json(docs)
@app.route('/post', methods=['POST'])
@ -34,8 +34,8 @@ async def new(request):
print(doc)
db = get_db()
object_id = await db.test_col.save(doc)
return response.json({'object_id': str(object_id)})
return json({'object_id': str(object_id)})
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8000, debug=True)
app.run(host='127.0.0.1', port=8000)

View File

@ -1,12 +1,12 @@
from sanic import Sanic
from sanic import response
from sanic.response import json
app = Sanic(__name__)
@app.route("/")
async def test(request):
return response.json({"test": True})
return json({"test": True})
if __name__ == '__main__':

View File

@ -2,7 +2,7 @@ import os
from sanic import Sanic
from sanic.log import log
from sanic import response
from sanic.response import json, text, file
from sanic.exceptions import ServerError
app = Sanic(__name__)
@ -10,32 +10,34 @@ app = Sanic(__name__)
@app.route("/")
async def test_async(request):
return response.json({"test": True})
return json({"test": True})
@app.route("/sync", methods=['GET', 'POST'])
def test_sync(request):
return response.json({"test": True})
return json({"test": True})
@app.route("/dynamic/<name>/<id:int>")
def test_params(request, name, id):
return response.text("yeehaww {} {}".format(name, id))
return text("yeehaww {} {}".format(name, id))
@app.route("/exception")
def exception(request):
raise ServerError("It's dead jim")
@app.route("/await")
async def test_await(request):
import asyncio
await asyncio.sleep(5)
return response.text("I'm feeling sleepy")
return text("I'm feeling sleepy")
@app.route("/file")
async def test_file(request):
return await response.file(os.path.abspath("setup.py"))
return await file(os.path.abspath("setup.py"))
# ----------------------------------------------- #
@ -44,7 +46,7 @@ async def test_file(request):
@app.exception(ServerError)
async def test(request, exception):
return response.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)
# ----------------------------------------------- #
@ -53,17 +55,17 @@ async def test(request, exception):
@app.route("/json")
def post_json(request):
return response.json({"received": True, "message": request.json})
return json({"received": True, "message": request.json})
@app.route("/form")
def post_json(request):
return response.json({"received": True, "form_data": request.form, "test": request.form.get('test')})
def form(request):
return json({"received": True, "form_data": request.form, "test": request.form.get('test')})
@app.route("/query_string")
def query_string(request):
return response.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})
# ----------------------------------------------- #

View File

@ -1,18 +0,0 @@
from sanic import Sanic
from sanic import response
app = Sanic(__name__)
@app.route('/')
async def index(request):
# generate a URL for the endpoint `post_handler`
url = app.url_for('post_handler', post_id=5)
# the URL is `/posts/5`, redirect to it
return response.redirect(url)
@app.route('/posts/<post_id>')
async def post_handler(request, post_id):
return response.text('Post - {}'.format(post_id))
if __name__ == '__main__':
app.run(host="0.0.0.0", port=8000, debug=True)

View File

@ -1,4 +1,4 @@
from sanic import response
from sanic.response import text
from sanic import Sanic
from sanic.blueprints import Blueprint
@ -11,25 +11,30 @@ from sanic.blueprints import Blueprint
app = Sanic()
bp = Blueprint("bp", host="bp.example.com")
@app.route('/', host=["example.com",
"somethingelse.com",
"therestofyourdomains.com"])
async def hello(request):
return response.text("Some defaults")
async def hello1(request):
return text("Some defaults")
@app.route('/', host="sub.example.com")
async def hello(request):
return response.text("42")
async def hello2(request):
return text("42")
@bp.route("/question")
async def hello(request):
return response.text("What is the meaning of life?")
async def hello3(request):
return text("What is the meaning of life?")
@bp.route("/answer")
async def hello(request):
return response.text("42")
async def hello4(request):
return text("42")
app.blueprint(bp)
if __name__ == '__main__':
app.run(host="0.0.0.0", port=8000)
app.run(host="127.0.0.1", port=8000)