Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def setUp(self):
self.app = Sanic(__name__)
@self.app.route('/defaults', methods=['GET', 'POST', 'HEAD', 'OPTIONS'])
@cross_origin(self.app)
def defaults(request):
return text('Should only return headers on pre-flight OPTIONS request')
@self.app.route('/test_methods_defined', methods=['POST', 'OPTIONS'])
@cross_origin(self.app, methods=['POST'])
def test_get(request):
return text('Only allow POST')
def test_jwt_crypto_very_long_path():
app = Sanic("sanic-jwt-test")
n = 16 * 1024
Initialize(
app,
authenticate=authenticate,
public_key=str(binascii.hexlify(os.urandom(n)), "utf-8"),
private_key=str(binascii.hexlify(os.urandom(n)), "utf-8"),
algorithm="RS256",
)
@app.route("/protected")
@protected()
async def protected_request(request):
return json({"protected": True})
_, response = app.test_client.post(
def nlg_app(base_url="/"):
app = Sanic(__name__)
@app.route(base_url, methods=["POST"])
async def generate(request):
"""Simple HTTP NLG generator, checks that the incoming request
is format according to the spec."""
nlg_call = request.json
jsonschema.validate(nlg_call, nlg_request_format_spec())
if nlg_call.get("template") == "utter_greet":
response_dict = {"text": "Hey there!"}
else:
response_dict = {"text": "Sorry, didn't get that."}
return response.json(response_dict)
async def test_request_class_custom():
class MyCustomRequest(Request):
pass
app = Sanic(request_class=MyCustomRequest)
@app.get("/custom")
def custom_request(request):
return text(request.__class__.__name__)
_, response = await app.asgi_client.get("/custom")
assert response.body == b"MyCustomRequest"
def test_static_content_range_correct(file_name, static_file_directory):
app = Sanic('test_static')
app.static(
'/testing.file', get_file_path(static_file_directory, file_name),
use_content_range=True)
bp = Blueprint('test_bp_static', url_prefix='/bp')
bp.static('/testing.file', get_file_path(static_file_directory, file_name),
use_content_range=True)
app.blueprint(bp)
headers = {
'Range': 'bytes=12-19'
}
uri = app.url_for('static')
assert uri == '/testing.file'
assert uri == app.url_for('static', name='static')
assert uri == app.url_for('static', name='static', filename='any')
from sanic import Sanic
from sanic.response import json, text
import logging
try:
# The typical way to import sanic-cors
from sanic_cors import cross_origin
except ImportError:
# Path hack allows examples to be run without installation.
import os
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.sys.path.insert(0, parentdir)
from sanic_cors import cross_origin
app = Sanic('SanicCorsViewBasedExample')
logging.basicConfig(level=logging.INFO)
@app.route("/", methods=['GET', 'OPTIONS'])
@cross_origin(app, automatic_options=True)
def hello_world(request):
'''
This view has CORS enabled for all domains, representing the simplest
configuration of view-based decoration. The expected result is as
follows:
$ curl --include -X GET http://127.0.0.1:5000/ \
--header Origin:www.examplesite.com
>> HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
from sanic import Sanic
app = Sanic()
from sanic import Sanic, Blueprint
from sanic.response import json
from sanic_transmute import describe, add_route, add_swagger, APIException
from sanic.exceptions import ServerError
from schematics.models import Model
from schematics.types import IntType
class User(Model):
points = IntType()
app = Sanic()
bp = Blueprint("test_blueprints", url_prefix="/blueprint")
@describe(paths="/api/v1/user/{user}/", methods="GET")
async def test_transmute(request, user: str, env: str=None, group: [str]=None):
"""
API Description: Transmute Get. This will show in the swagger page (localhost:8000/api/v1/).
"""
return {
"user": user,
"env": env,
"group": group,
}
@describe(paths="/killme")
from sanic import Sanic
from sanic_openapi import swagger_blueprint
from blueprints.car import blueprint as car_blueprint
from blueprints.driver import blueprint as driver_blueprint
from blueprints.garage import blueprint as garage_blueprint
from blueprints.manufacturer import blueprint as manufacturer_blueprint
app = Sanic()
app.blueprint(swagger_blueprint)
app.blueprint(car_blueprint)
app.blueprint(driver_blueprint)
app.blueprint(garage_blueprint)
app.blueprint(manufacturer_blueprint)
app.config.API_VERSION = '1.0.0'
app.config.API_TITLE = 'Car API'
app.config.API_TERMS_OF_SERVICE = 'Use with caution!'
app.config.API_CONTACT_EMAIL = 'channelcat@gmail.com'
app.run(host="0.0.0.0", debug=True)