Improve example
This commit is contained in:
parent
220396018b
commit
e31de53e2f
|
@ -1,7 +1,9 @@
|
||||||
"""
|
"""
|
||||||
Example intercepting uncaught exceptions using Sanic's error handler framework.
|
Example intercepting uncaught exceptions using Sanic's error handler framework.
|
||||||
|
|
||||||
This may be useful for developers wishing to use Sentry, Airbrake, etc.
|
This may be useful for developers wishing to use Sentry, Airbrake, etc.
|
||||||
or a custom system to log and monitor unexpected errors in production.
|
or a custom system to log and monitor unexpected errors in production.
|
||||||
|
|
||||||
First we create our own class inheriting from Handler in sanic.exceptions,
|
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
|
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
|
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 Sanic
|
||||||
from sanic import response
|
from sanic.response import json
|
||||||
|
|
||||||
app = Sanic(__name__)
|
app = Sanic(__name__)
|
||||||
|
|
||||||
|
@ -50,7 +52,7 @@ async def test(request):
|
||||||
# Here, something occurs which causes an unexpected exception
|
# Here, something occurs which causes an unexpected exception
|
||||||
# This exception will flow to our custom handler.
|
# This exception will flow to our custom handler.
|
||||||
1 / 0
|
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)
|
||||||
|
|
|
@ -2,7 +2,7 @@
|
||||||
# the project
|
# the project
|
||||||
|
|
||||||
from sanic import Sanic
|
from sanic import Sanic
|
||||||
from sanic import response
|
from sanic.response import html
|
||||||
from jinja2 import Environment, PackageLoader, select_autoescape
|
from jinja2 import Environment, PackageLoader, select_autoescape
|
||||||
|
|
||||||
app = Sanic(__name__)
|
app = Sanic(__name__)
|
||||||
|
@ -22,7 +22,7 @@ template = template_env.get_template("example_template.html")
|
||||||
async def test(request):
|
async def test(request):
|
||||||
rendered_template = await template.render_async(
|
rendered_template = await template.render_async(
|
||||||
knights='that say nih; asynchronously')
|
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)
|
||||||
|
|
|
@ -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)
|
|
|
@ -1,5 +1,5 @@
|
||||||
from sanic import Sanic
|
from sanic import Sanic
|
||||||
from sanic import response
|
from sanic.response import text
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
logging_format = "[%(asctime)s] %(process)d-%(levelname)s "
|
logging_format = "[%(asctime)s] %(process)d-%(levelname)s "
|
||||||
|
@ -14,9 +14,12 @@ log = logging.getLogger()
|
||||||
|
|
||||||
# Set logger to override default basicConfig
|
# Set logger to override default basicConfig
|
||||||
sanic = Sanic()
|
sanic = Sanic()
|
||||||
|
|
||||||
|
|
||||||
@sanic.route("/")
|
@sanic.route("/")
|
||||||
def test(request):
|
def test(request):
|
||||||
log.info("received request; responding with 'hey'")
|
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)
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
import asyncio
|
import asyncio
|
||||||
from sanic import Sanic
|
from sanic import Sanic
|
||||||
from sanic import response
|
from sanic.response import text
|
||||||
from sanic.config import Config
|
from sanic.config import Config
|
||||||
from sanic.exceptions import RequestTimeout
|
from sanic.exceptions import RequestTimeout
|
||||||
|
|
||||||
|
@ -11,11 +11,12 @@ app = Sanic(__name__)
|
||||||
@app.route('/')
|
@app.route('/')
|
||||||
async def test(request):
|
async def test(request):
|
||||||
await asyncio.sleep(3)
|
await asyncio.sleep(3)
|
||||||
return response.text('Hello, world!')
|
return text('Hello, world!')
|
||||||
|
|
||||||
|
|
||||||
@app.exception(RequestTimeout)
|
@app.exception(RequestTimeout)
|
||||||
def timeout(request, exception):
|
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)
|
||||||
|
|
|
@ -5,7 +5,7 @@ motor==1.1
|
||||||
sanic==0.2.0
|
sanic==0.2.0
|
||||||
"""
|
"""
|
||||||
from sanic import Sanic
|
from sanic import Sanic
|
||||||
from sanic import response
|
from sanic.response import json
|
||||||
|
|
||||||
|
|
||||||
app = Sanic('motor_mongodb')
|
app = Sanic('motor_mongodb')
|
||||||
|
@ -25,7 +25,7 @@ async def get(request):
|
||||||
for doc in docs:
|
for doc in docs:
|
||||||
doc['id'] = str(doc['_id'])
|
doc['id'] = str(doc['_id'])
|
||||||
del doc['_id']
|
del doc['_id']
|
||||||
return response.json(docs)
|
return json(docs)
|
||||||
|
|
||||||
|
|
||||||
@app.route('/post', methods=['POST'])
|
@app.route('/post', methods=['POST'])
|
||||||
|
@ -34,8 +34,8 @@ async def new(request):
|
||||||
print(doc)
|
print(doc)
|
||||||
db = get_db()
|
db = get_db()
|
||||||
object_id = await db.test_col.save(doc)
|
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__":
|
if __name__ == "__main__":
|
||||||
app.run(host='0.0.0.0', port=8000, debug=True)
|
app.run(host='127.0.0.1', port=8000)
|
||||||
|
|
|
@ -1,12 +1,12 @@
|
||||||
from sanic import Sanic
|
from sanic import Sanic
|
||||||
from sanic import response
|
from sanic.response import json
|
||||||
|
|
||||||
app = Sanic(__name__)
|
app = Sanic(__name__)
|
||||||
|
|
||||||
|
|
||||||
@app.route("/")
|
@app.route("/")
|
||||||
async def test(request):
|
async def test(request):
|
||||||
return response.json({"test": True})
|
return json({"test": True})
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
|
|
@ -2,7 +2,7 @@ import os
|
||||||
|
|
||||||
from sanic import Sanic
|
from sanic import Sanic
|
||||||
from sanic.log import log
|
from sanic.log import log
|
||||||
from sanic import response
|
from sanic.response import json, text, file
|
||||||
from sanic.exceptions import ServerError
|
from sanic.exceptions import ServerError
|
||||||
|
|
||||||
app = Sanic(__name__)
|
app = Sanic(__name__)
|
||||||
|
@ -10,32 +10,34 @@ app = Sanic(__name__)
|
||||||
|
|
||||||
@app.route("/")
|
@app.route("/")
|
||||||
async def test_async(request):
|
async def test_async(request):
|
||||||
return response.json({"test": True})
|
return json({"test": True})
|
||||||
|
|
||||||
|
|
||||||
@app.route("/sync", methods=['GET', 'POST'])
|
@app.route("/sync", methods=['GET', 'POST'])
|
||||||
def test_sync(request):
|
def test_sync(request):
|
||||||
return response.json({"test": True})
|
return json({"test": True})
|
||||||
|
|
||||||
|
|
||||||
@app.route("/dynamic/<name>/<id:int>")
|
@app.route("/dynamic/<name>/<id:int>")
|
||||||
def test_params(request, name, id):
|
def test_params(request, name, id):
|
||||||
return response.text("yeehaww {} {}".format(name, id))
|
return text("yeehaww {} {}".format(name, id))
|
||||||
|
|
||||||
|
|
||||||
@app.route("/exception")
|
@app.route("/exception")
|
||||||
def exception(request):
|
def exception(request):
|
||||||
raise ServerError("It's dead jim")
|
raise ServerError("It's dead jim")
|
||||||
|
|
||||||
|
|
||||||
@app.route("/await")
|
@app.route("/await")
|
||||||
async def test_await(request):
|
async def test_await(request):
|
||||||
import asyncio
|
import asyncio
|
||||||
await asyncio.sleep(5)
|
await asyncio.sleep(5)
|
||||||
return response.text("I'm feeling sleepy")
|
return text("I'm feeling sleepy")
|
||||||
|
|
||||||
|
|
||||||
@app.route("/file")
|
@app.route("/file")
|
||||||
async def test_file(request):
|
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)
|
@app.exception(ServerError)
|
||||||
async def test(request, exception):
|
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")
|
@app.route("/json")
|
||||||
def post_json(request):
|
def post_json(request):
|
||||||
return response.json({"received": True, "message": request.json})
|
return json({"received": True, "message": request.json})
|
||||||
|
|
||||||
|
|
||||||
@app.route("/form")
|
@app.route("/form")
|
||||||
def post_json(request):
|
def form(request):
|
||||||
return response.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")
|
@app.route("/query_string")
|
||||||
def query_string(request):
|
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})
|
||||||
|
|
||||||
|
|
||||||
# ----------------------------------------------- #
|
# ----------------------------------------------- #
|
||||||
|
|
|
@ -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)
|
|
|
@ -1,4 +1,4 @@
|
||||||
from sanic import response
|
from sanic.response import text
|
||||||
from sanic import Sanic
|
from sanic import Sanic
|
||||||
from sanic.blueprints import Blueprint
|
from sanic.blueprints import Blueprint
|
||||||
|
|
||||||
|
@ -11,25 +11,30 @@ from sanic.blueprints import Blueprint
|
||||||
app = Sanic()
|
app = Sanic()
|
||||||
bp = Blueprint("bp", host="bp.example.com")
|
bp = Blueprint("bp", host="bp.example.com")
|
||||||
|
|
||||||
|
|
||||||
@app.route('/', host=["example.com",
|
@app.route('/', host=["example.com",
|
||||||
"somethingelse.com",
|
"somethingelse.com",
|
||||||
"therestofyourdomains.com"])
|
"therestofyourdomains.com"])
|
||||||
async def hello(request):
|
async def hello1(request):
|
||||||
return response.text("Some defaults")
|
return text("Some defaults")
|
||||||
|
|
||||||
|
|
||||||
@app.route('/', host="sub.example.com")
|
@app.route('/', host="sub.example.com")
|
||||||
async def hello(request):
|
async def hello2(request):
|
||||||
return response.text("42")
|
return text("42")
|
||||||
|
|
||||||
|
|
||||||
@bp.route("/question")
|
@bp.route("/question")
|
||||||
async def hello(request):
|
async def hello3(request):
|
||||||
return response.text("What is the meaning of life?")
|
return text("What is the meaning of life?")
|
||||||
|
|
||||||
|
|
||||||
@bp.route("/answer")
|
@bp.route("/answer")
|
||||||
async def hello(request):
|
async def hello4(request):
|
||||||
return response.text("42")
|
return text("42")
|
||||||
|
|
||||||
|
|
||||||
app.blueprint(bp)
|
app.blueprint(bp)
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
app.run(host="0.0.0.0", port=8000)
|
app.run(host="127.0.0.1", port=8000)
|
||||||
|
|
Loading…
Reference in New Issue
Block a user