本文整理汇总了Python中sanic.Sanic类的典型用法代码示例。如果您正苦于以下问题:Python Sanic类的具体用法?Python Sanic怎么用?Python Sanic使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Sanic类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: test_bp_strict_slash
def test_bp_strict_slash():
app = Sanic('test_route_strict_slash')
bp = Blueprint('test_text')
@bp.get('/get', strict_slashes=True)
def handler(request):
return text('OK')
@bp.post('/post/', strict_slashes=True)
def handler(request):
return text('OK')
app.blueprint(bp)
request, response = app.test_client.get('/get')
assert response.text == 'OK'
assert response.json == None
request, response = app.test_client.get('/get/')
assert response.status == 404
request, response = app.test_client.post('/post/')
assert response.text == 'OK'
request, response = app.test_client.post('/post')
assert response.status == 404
开发者ID:penelopeia,项目名称:sanic,代码行数:26,代码来源:test_blueprints.py
示例2: test_bp_with_host
def test_bp_with_host():
app = Sanic('test_bp_host')
bp = Blueprint('test_bp_host', url_prefix='/test1', host="example.com")
@bp.route('/')
def handler(request):
return text('Hello')
@bp.route('/', host="sub.example.com")
def handler(request):
return text('Hello subdomain!')
app.blueprint(bp)
headers = {"Host": "example.com"}
request, response = app.test_client.get(
'/test1/',
headers=headers)
assert response.text == 'Hello'
headers = {"Host": "sub.example.com"}
request, response = app.test_client.get(
'/test1/',
headers=headers)
assert response.text == 'Hello subdomain!'
开发者ID:penelopeia,项目名称:sanic,代码行数:25,代码来源:test_blueprints.py
示例3: test_remove_unhashable_route
def test_remove_unhashable_route():
app = Sanic('test_remove_unhashable_route')
async def handler(request, unhashable):
return text('OK')
app.add_route(handler, '/folder/<unhashable:[A-Za-z0-9/]+>/end/')
request, response = app.test_client.get('/folder/test/asdf/end/')
assert response.status == 200
request, response = app.test_client.get('/folder/test///////end/')
assert response.status == 200
request, response = app.test_client.get('/folder/test/end/')
assert response.status == 200
app.remove_route('/folder/<unhashable:[A-Za-z0-9/]+>/end/')
request, response = app.test_client.get('/folder/test/asdf/end/')
assert response.status == 404
request, response = app.test_client.get('/folder/test///////end/')
assert response.status == 404
request, response = app.test_client.get('/folder/test/end/')
assert response.status == 404
开发者ID:penelopeia,项目名称:sanic,代码行数:27,代码来源:test_routes.py
示例4: blueprint_app
def blueprint_app():
app = Sanic('blueprints')
first_print = Blueprint('first', url_prefix='/first')
second_print = Blueprint('second', url_prefix='/second')
@first_print.route('/foo')
def foo():
return text('foo from first')
@first_print.route('/foo/<param>')
def foo_with_param(request, param):
return text(
'foo from first : {}'.format(param))
@second_print.route('/foo') # noqa
def foo():
return text('foo from second')
@second_print.route('/foo/<param>') # noqa
def foo_with_param(request, param):
return text(
'foo from second : {}'.format(param))
app.blueprint(first_print)
app.blueprint(second_print)
return app
开发者ID:penelopeia,项目名称:sanic,代码行数:28,代码来源:test_url_building.py
示例5: test_with_middleware_response
def test_with_middleware_response():
app = Sanic('test_with_middleware_response')
results = []
@app.middleware('request')
async def process_response(request):
results.append(request)
@app.middleware('response')
async def process_response(request, response):
results.append(request)
results.append(response)
class DummyView(HTTPMethodView):
def get(self, request):
return text('I am get method')
app.add_route(DummyView.as_view(), '/')
request, response = sanic_endpoint_test(app)
assert response.text == 'I am get method'
assert type(results[0]) is Request
assert type(results[1]) is Request
assert isinstance(results[2], HTTPResponse)
开发者ID:blurrcat,项目名称:sanic,代码行数:27,代码来源:test_views.py
示例6: test_bp_exception_handler
def test_bp_exception_handler():
app = Sanic('test_middleware')
blueprint = Blueprint('test_middleware')
@blueprint.route('/1')
def handler_1(request):
raise InvalidUsage("OK")
@blueprint.route('/2')
def handler_2(request):
raise ServerError("OK")
@blueprint.route('/3')
def handler_3(request):
raise NotFound("OK")
@blueprint.exception(NotFound, ServerError)
def handler_exception(request, exception):
return text("OK")
app.blueprint(blueprint)
request, response = sanic_endpoint_test(app, uri='/1')
assert response.status == 400
request, response = sanic_endpoint_test(app, uri='/2')
assert response.status == 200
assert response.text == 'OK'
request, response = sanic_endpoint_test(app, uri='/3')
assert response.status == 200
开发者ID:blurrcat,项目名称:sanic,代码行数:32,代码来源:test_blueprints.py
示例7: test_url_attributes_with_ssl
def test_url_attributes_with_ssl(path, query, expected_url):
app = Sanic('test_url_attrs_with_ssl')
current_dir = os.path.dirname(os.path.realpath(__file__))
context = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)
context.load_cert_chain(
os.path.join(current_dir, 'certs/selfsigned.cert'),
keyfile=os.path.join(current_dir, 'certs/selfsigned.key'))
async def handler(request):
return text('OK')
app.add_route(handler, path)
request, response = app.test_client.get(
'https://{}:{}'.format(HOST, PORT) + path + '?{}'.format(query),
server_kwargs={'ssl': context})
assert request.url == expected_url.format(HOST, PORT)
parsed = urlparse(request.url)
assert parsed.scheme == request.scheme
assert parsed.path == request.path
assert parsed.query == request.query_string
assert parsed.netloc == request.host
开发者ID:rezaprimasatya,项目名称:sanic,代码行数:25,代码来源:test_requests.py
示例8: test_methods
def test_methods(method):
app = Sanic('test_methods')
class DummyView(HTTPMethodView):
def get(self, request):
return text('', headers={'method': 'GET'})
def post(self, request):
return text('', headers={'method': 'POST'})
def put(self, request):
return text('', headers={'method': 'PUT'})
def head(self, request):
return text('', headers={'method': 'HEAD'})
def options(self, request):
return text('', headers={'method': 'OPTIONS'})
def patch(self, request):
return text('', headers={'method': 'PATCH'})
def delete(self, request):
return text('', headers={'method': 'DELETE'})
app.add_route(DummyView.as_view(), '/')
request, response = sanic_endpoint_test(app, method=method)
assert response.headers['method'] == method
开发者ID:blurrcat,项目名称:sanic,代码行数:30,代码来源:test_views.py
示例9: create_app
def create_app(ignore_exceptions=None, debug=False, **config):
import os
app = Sanic(__name__)
for key, value in config.items():
app.config[key] = value
app.debug = debug
if ignore_exceptions:
app.config['RAVEN_IGNORE_EXCEPTIONS'] = ignore_exceptions
@app.route('/an-error/', methods=['GET', 'POST'])
def an_error(request):
raise ValueError('hello world')
@app.route('/log-an-error/', methods=['GET'])
def log_an_error(request):
logger = logging.getLogger('random-logger')
logger.error('Log an error')
return response.text('Hello')
@app.route('/capture/', methods=['GET', 'POST'])
def capture_exception(request):
try:
raise ValueError('Boom')
except Exception:
request.app.extensions['sentry'].captureException()
return response.text('Hello')
@app.route('/message/', methods=['GET', 'POST'])
def capture_message(request):
request.app.extensions['sentry'].captureMessage('Interesting')
return response.text('World')
return app
开发者ID:ehfeng,项目名称:raven-python,代码行数:35,代码来源:tests.py
示例10: test_methods
def test_methods(method):
app = Sanic('test_methods')
class DummyView(HTTPMethodView):
async def get(self, request):
assert request.stream is None
return text('', headers={'method': 'GET'})
def post(self, request):
return text('', headers={'method': 'POST'})
async def put(self, request):
return text('', headers={'method': 'PUT'})
def head(self, request):
return text('', headers={'method': 'HEAD'})
def options(self, request):
return text('', headers={'method': 'OPTIONS'})
async def patch(self, request):
return text('', headers={'method': 'PATCH'})
def delete(self, request):
return text('', headers={'method': 'DELETE'})
app.add_route(DummyView.as_view(), '/')
assert app.is_request_stream is False
request, response = getattr(app.test_client, method.lower())('/')
assert response.headers['method'] == method
开发者ID:penelopeia,项目名称:sanic,代码行数:32,代码来源:test_views.py
示例11: test_request_stream_composition_view
def test_request_stream_composition_view():
'''for self.is_request_stream = True'''
app = Sanic('test_request_stream__composition_view')
def get_handler(request):
assert request.stream is None
return text('OK')
async def post_handler(request):
assert isinstance(request.stream, asyncio.Queue)
result = ''
while True:
body = await request.stream.get()
if body is None:
break
result += body.decode('utf-8')
return text(result)
view = CompositionView()
view.add(['GET'], get_handler)
view.add(['POST'], post_handler, stream=True)
app.add_route(view, '/composition_view')
assert app.is_request_stream is True
request, response = app.test_client.get('/composition_view')
assert response.status == 200
assert response.text == 'OK'
request, response = app.test_client.post('/composition_view', data=data)
assert response.status == 200
assert response.text == data
开发者ID:penelopeia,项目名称:sanic,代码行数:33,代码来源:test_request_stream.py
示例12: test_request_stream_method_view
def test_request_stream_method_view():
'''for self.is_request_stream = True'''
app = Sanic('test_request_stream_method_view')
class SimpleView(HTTPMethodView):
def get(self, request):
assert request.stream is None
return text('OK')
@stream_decorator
async def post(self, request):
assert isinstance(request.stream, asyncio.Queue)
result = ''
while True:
body = await request.stream.get()
if body is None:
break
result += body.decode('utf-8')
return text(result)
app.add_route(SimpleView.as_view(), '/method_view')
assert app.is_request_stream is True
request, response = app.test_client.get('/method_view')
assert response.status == 200
assert response.text == 'OK'
request, response = app.test_client.post('/method_view', data=data)
assert response.status == 200
assert response.text == data
开发者ID:penelopeia,项目名称:sanic,代码行数:33,代码来源:test_request_stream.py
示例13: test_bp_listeners
def test_bp_listeners():
app = Sanic('test_middleware')
blueprint = Blueprint('test_middleware')
order = []
@blueprint.listener('before_server_start')
def handler_1(sanic, loop):
order.append(1)
@blueprint.listener('after_server_start')
def handler_2(sanic, loop):
order.append(2)
@blueprint.listener('after_server_start')
def handler_3(sanic, loop):
order.append(3)
@blueprint.listener('before_server_stop')
def handler_4(sanic, loop):
order.append(5)
@blueprint.listener('before_server_stop')
def handler_5(sanic, loop):
order.append(4)
@blueprint.listener('after_server_stop')
def handler_6(sanic, loop):
order.append(6)
app.blueprint(blueprint)
request, response = sanic_endpoint_test(app, uri='/')
assert order == [1,2,3,4,5,6]
开发者ID:blurrcat,项目名称:sanic,代码行数:35,代码来源:test_blueprints.py
示例14: test_static_file
def test_static_file(static_file_directory, file_name):
app = Sanic('test_static')
app.static(
'/testing.file', get_file_path(static_file_directory, file_name))
request, response = app.test_client.get('/testing.file')
assert response.status == 200
assert response.body == get_file_content(static_file_directory, file_name)
开发者ID:penelopeia,项目名称:sanic,代码行数:8,代码来源:test_static.py
示例15: test_static_directory
def test_static_directory(file_name, base_uri, static_file_directory):
app = Sanic('test_static')
app.static(base_uri, static_file_directory)
request, response = app.test_client.get(
uri='{}/{}'.format(base_uri, file_name))
assert response.status == 200
assert response.body == get_file_content(static_file_directory, file_name)
开发者ID:penelopeia,项目名称:sanic,代码行数:9,代码来源:test_static.py
示例16: test_all_listeners
def test_all_listeners():
random_name_app = Sanic(''.join(
[choice(ascii_letters) for _ in range(choice(range(5, 10)))]))
output = list()
for listener_name in AVAILABLE_LISTENERS:
listener = create_listener(listener_name, output)
random_name_app.listener(listener_name)(listener)
start_stop_app(random_name_app)
for listener_name in AVAILABLE_LISTENERS:
assert random_name_app.name + listener_name == output.pop()
开发者ID:penelopeia,项目名称:sanic,代码行数:10,代码来源:test_server_events.py
示例17: test_single_listener
def test_single_listener(listener_name):
"""Test that listeners on their own work"""
random_name_app = Sanic(''.join(
[choice(ascii_letters) for _ in range(choice(range(5, 10)))]))
output = list()
# Register listener
random_name_app.listener(listener_name)(
create_listener(listener_name, output))
start_stop_app(random_name_app)
assert random_name_app.name + listener_name == output.pop()
开发者ID:penelopeia,项目名称:sanic,代码行数:10,代码来源:test_server_events.py
示例18: test_remove_static_route
def test_remove_static_route():
app = Sanic('test_remove_static_route')
async def handler1(request):
return text('OK1')
async def handler2(request):
return text('OK2')
app.add_route(handler1, '/test')
app.add_route(handler2, '/test2')
request, response = sanic_endpoint_test(app, uri='/test')
assert response.status == 200
request, response = sanic_endpoint_test(app, uri='/test2')
assert response.status == 200
app.remove_route('/test')
app.remove_route('/test2')
request, response = sanic_endpoint_test(app, uri='/test')
assert response.status == 404
request, response = sanic_endpoint_test(app, uri='/test2')
assert response.status == 404
开发者ID:blurrcat,项目名称:sanic,代码行数:26,代码来源:test_routes.py
示例19: test_remove_route_without_clean_cache
def test_remove_route_without_clean_cache():
app = Sanic('test_remove_static_route')
async def handler(request):
return text('OK')
app.add_route(handler, '/test')
request, response = app.test_client.get('/test')
assert response.status == 200
app.remove_route('/test', clean_cache=True)
request, response = app.test_client.get('/test')
assert response.status == 404
app.add_route(handler, '/test')
request, response = app.test_client.get('/test')
assert response.status == 200
app.remove_route('/test', clean_cache=False)
request, response = app.test_client.get('/test')
assert response.status == 200
开发者ID:penelopeia,项目名称:sanic,代码行数:25,代码来源:test_routes.py
示例20: test_remove_static_route
def test_remove_static_route():
app = Sanic('test_remove_static_route')
async def handler1(request):
return text('OK1')
async def handler2(request):
return text('OK2')
app.add_route(handler1, '/test')
app.add_route(handler2, '/test2')
request, response = app.test_client.get('/test')
assert response.status == 200
request, response = app.test_client.get('/test2')
assert response.status == 200
app.remove_route('/test')
app.remove_route('/test2')
request, response = app.test_client.get('/test')
assert response.status == 404
request, response = app.test_client.get('/test2')
assert response.status == 404
开发者ID:penelopeia,项目名称:sanic,代码行数:26,代码来源:test_routes.py
注:本文中的sanic.Sanic类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论