本文整理汇总了Python中sanic.Sanic.run方法的典型用法代码示例。如果您正苦于以下问题:Python Sanic.run方法的具体用法?Python Sanic.run怎么用?Python Sanic.run使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sanic.Sanic
的用法示例。
在下文中一共展示了Sanic.run方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from sanic import Sanic [as 别名]
# 或者: from sanic.Sanic import run [as 别名]
def __init__(self, daemon):
app = Sanic('ansible-api')
app.add_route(controller.Main.as_view(), '/')
app.add_route(controller.NonBlockTest.as_view(), '/test')
app.add_route(controller.Command.as_view(), '/command')
app.add_route(controller.Playbook.as_view(), '/playbook')
app.add_route(controller.FileList.as_view(), '/filelist')
app.add_route(controller.FileReadWrite.as_view(), '/fileitem')
app.add_route(controller.FileExist.as_view(), '/filexist')
app.add_route(controller.ParseVarsFromFile.as_view(), '/parsevars')
app.add_websocket_route(controller.Message.websocket, '/message', subprotocols=Config.get('ws_sub'))
app.config.update(dict(RESPONSE_TIMEOUT=Config.get('timeout'))) # timeout for waiting response
@app.middleware('request')
async def ip_ban(request):
if len(Config.get('allow_ip')) and request.ip not in Config.get('allow_ip'):
return text('Your IP (%s) is not allowed!' % request.ip, status=403)
# print config contents
config = Config().__dict__
config['sign_key'] = len(config['sign_key']) * '*' # mask signature key
Tool.LOGGER.debug("Config at start: %s" % json.dumps(config))
app.run(host=Config.get('host'), port=Config.get('port'), workers=Config.get('workers'), debug=not daemon)
示例2: test_register_system_signals
# 需要导入模块: from sanic import Sanic [as 别名]
# 或者: from sanic.Sanic import run [as 别名]
def test_register_system_signals():
"""Test if sanic register system signals"""
app = Sanic('test_register_system_signals')
@app.route('/hello')
async def hello_route(request):
return HTTPResponse()
app.run(HOST, PORT,
before_start=set_loop,
after_start=stop,
after_stop=after)
assert calledq.get() == True
示例3: test_dont_register_system_signals
# 需要导入模块: from sanic import Sanic [as 别名]
# 或者: from sanic.Sanic import run [as 别名]
def test_dont_register_system_signals():
"""Test if sanic don't register system signals"""
app = Sanic('test_register_system_signals')
@app.route('/hello')
async def hello_route(request):
return HTTPResponse()
app.listener('after_server_start')(stop)
app.listener('before_server_start')(set_loop)
app.listener('after_server_stop')(after)
app.run(HOST, PORT, register_sys_signals=False)
assert calledq.get() == False
示例4: test_bad_request_response
# 需要导入模块: from sanic import Sanic [as 别名]
# 或者: from sanic.Sanic import run [as 别名]
def test_bad_request_response():
app = Sanic('test_bad_request_response')
lines = []
async def _request(sanic, loop):
connect = asyncio.open_connection('127.0.0.1', 42101)
reader, writer = await connect
writer.write(b'not http')
while True:
line = await reader.readline()
if not line:
break
lines.append(line)
app.stop()
app.run(host='127.0.0.1', port=42101, debug=False, after_start=_request)
assert lines[0] == b'HTTP/1.1 400 Bad Request\r\n'
assert lines[-1] == b'Error: Bad Request'
示例5: test_multiprocessing
# 需要导入模块: from sanic import Sanic [as 别名]
# 或者: from sanic.Sanic import run [as 别名]
def test_multiprocessing():
"""Tests that the number of children we produce is correct"""
# Selects a number at random so we can spot check
num_workers = random.choice(range(2, multiprocessing.cpu_count() * 2 + 1))
app = Sanic('test_multiprocessing')
process_list = set()
def stop_on_alarm(*args):
for process in multiprocessing.active_children():
process_list.add(process.pid)
process.terminate()
signal.signal(signal.SIGALRM, stop_on_alarm)
signal.alarm(1)
app.run(HOST, PORT, workers=num_workers)
assert len(process_list) == num_workers
示例6: print
# 需要导入模块: from sanic import Sanic [as 别名]
# 或者: from sanic.Sanic import run [as 别名]
print('in task_func '+str(info))
return 'the result'
async def work(queue):
while True:
print("loop queue start ");
info = await queue.get()
size = queue.qsize()
print("info "+str(info)+" size: "+str(size))
await asyncio.sleep(1)
@app.listener('before_server_start')
async def setup_db(app, loop):
print("setup_db....")
queue = asyncio.Queue(maxsize=1000)
app.queue = queue
app.add_task(work(queue))
@app.listener('after_server_start')
async def notify_server_started(app, loop):
print("notify_server_started");
# app.add_task(loop.create_task(work(app.queue)))
@app.listener('before_server_stop')
async def notify_server_stopping(app, loop):
print('Server shutting down!')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000,return_asyncio_server=True)
示例7: Sanic
# 需要导入模块: from sanic import Sanic [as 别名]
# 或者: from sanic.Sanic import run [as 别名]
# -*- coding: utf-8 -*-
import asyncio
from sanic import Sanic
app = Sanic()
async def notify_server_started_after_five_seconds():
await asyncio.sleep(5)
print('Server successfully started!')
app.add_task(notify_server_started_after_five_seconds())
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000)
示例8: init
# 需要导入模块: from sanic import Sanic [as 别名]
# 或者: from sanic.Sanic import run [as 别名]
sem = None
@app.listener('before_server_start')
def init(sanic, loop):
global sem
concurrency_per_worker = 4
sem = asyncio.Semaphore(concurrency_per_worker, loop=loop)
async def bounded_fetch(session, url):
"""
Use session object to perform 'get' request on url
"""
async with sem, session.get(url) as response:
return await response.json()
@app.route("/")
async def test(request):
"""
Download and serve example JSON
"""
url = "https://api.github.com/repos/channelcat/sanic"
async with aiohttp.ClientSession() as session:
response = await bounded_fetch(session, url)
return json(response)
app.run(host="0.0.0.0", port=8000, workers=2)
示例9: Sanic
# 需要导入模块: from sanic import Sanic [as 别名]
# 或者: from sanic.Sanic import run [as 别名]
#!/usr/local/bin/python3
from sanic import Sanic
from sanic.response import text
app = Sanic()
@app.route("/")
async def test(request):
return text('Hello World!')
if __name__ == "__main__":
ssl = {'cert': "./keys/server.crt", 'key': "./keys/server.key"}
app.run(host="0.0.0.0", port=9000, ssl=ssl)
示例10: Sanic
# 需要导入模块: from sanic import Sanic [as 别名]
# 或者: from sanic.Sanic import run [as 别名]
from sanic import Sanic
from sanic.response import json, html
import os
from get_quake_data import get_quake_data
import settings
app = Sanic(__name__)
app.static('/static', settings.STATIC_DIR)
@app.route("/")
async def test(request):
template = open(os.getcwd() + "/project/index.html")
return html(template.read())
@app.route("/json")
async def test(request):
return json(get_quake_data())
app.run(host="127.0.0.1", port=8000, debug=True)
示例11: echo
# 需要导入模块: from sanic import Sanic [as 别名]
# 或者: from sanic.Sanic import run [as 别名]
from sanic import Sanic
async def echo(request, ws):
while True:
data = await ws.recv()
print(data)
if data == "close":
await ws.close()
else:
await ws.send(data + "/answer")
app = Sanic(__name__)
app.add_websocket_route(echo, "/ws")
app.run(host="0.0.0.0", port=8080, debug=True)
示例12: Sanic
# 需要导入模块: from sanic import Sanic [as 别名]
# 或者: from sanic.Sanic import run [as 别名]
from sanic import Sanic
from sanic import response
from pokereval import PokerEval
GAME = 'holdem'
ITERATIONS = 20000
app = Sanic()
pe = PokerEval()
@app.post('/')
async def post_handler(request):
data = request.json
equities = pe.poker_eval(
iterations=ITERATIONS,
game=GAME,
**data
)
return response.json(equities)
@app.get('/')
async def get_handler(request):
return response.text('https://github.com/minmax/pypoker-eval')
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5657)
示例13: Sanic
# 需要导入模块: from sanic import Sanic [as 别名]
# 或者: from sanic.Sanic import run [as 别名]
from sanic import Sanic
from sanic_cors import CORS
from sqlalchemy import create_engine
sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir))
from tune_manager.api import importer, catalog
from tune_manager import settings
from tune_manager import db
parser = argparse.ArgumentParser()
parser.add_argument("--host", default="0.0.0.0")
parser.add_argument("--port", default="8080")
parser.add_argument("--workers", type=int, default=1)
parser.add_argument("--debug", action="store_true")
args = parser.parse_args()
app = Sanic(__name__)
app.config.from_object(settings)
CORS(app)
# Setup the database and assign it on the app object
db.init(create_engine(app.config.DATABASE_PATH))
app.db_session = db.Session()
app.blueprint(importer.blueprint, url_prefix="/api")
app.blueprint(catalog.blueprint, url_prefix="/api/catalog")
if __name__ == "__main__":
app.run(host=args.host, port=args.port, workers=args.workers, debug=args.debug)
示例14: post_json
# 需要导入模块: from sanic import Sanic [as 别名]
# 或者: from sanic.Sanic import run [as 别名]
# ----------------------------------------------- #
@app.route("/json")
def post_json(request):
return json({"received": True, "message": request.json})
@app.route("/form")
def post_json(request):
return json({"received": True, "form_data": request.form, "test": request.form.get('test')})
@app.route("/query_string")
def query_string(request):
return json({"parsed": True, "args": request.args, "url": request.url, "query_string": request.query_string})
# ----------------------------------------------- #
# Run Server
# ----------------------------------------------- #
def after_start(app, loop):
log.info("OH OH OH OH OHHHHHHHH")
def before_stop(app, loop):
log.info("TRIED EVERYTHING")
app.run(host="0.0.0.0", port=8000, debug=True, after_start=after_start, before_stop=before_stop)
示例15: getuserkey
# 需要导入模块: from sanic import Sanic [as 别名]
# 或者: from sanic.Sanic import run [as 别名]
def getuserkey(uid):
return 'user:{}'.format(uid)
def getsessionkey(sid):
return 'session:{}'.format(sid)
async def getitems(indexes):
return await store.hgetall([getitemkey(index) for index in indexes])
async def getitem(index):
return await store.hgetall(getitemkey(index))
async def getitembyslug(slug):
index = await store.hget('items:slugs', slug)
return await getitem(index) if index is not None else None
def getitemkey(index):
return 'item:{}'.format(index)
app.static('/', './static')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000, debug=True)