都是抄的api:https://sanic.readthedocs.io/en/latest/index.html
如果不想安装uvloop或者ujson,可以:
SANIC_NO_UVLOOP=true SANIC_NO_UJSON=true pip3 install --no-binary :all: sanic
from sanic import Sanic
from sanic.response import json
app = Sanic("hello_example")
@app.route("/")
async def test(request):
return json({"hello": "world"})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000)
直接run即可
Sanic在应用程序对象的config属性中保存配置。配置对象只是一个对象,可以修改,使用点符号或像一个字典(一般参数是大写的):
app = Sanic('myapp')
app.config.DB_NAME = 'appdb'
app.config['DB_USER'] = 'appuser'
db_settings = {
'DB_HOST': 'localhost',
'DB_NAME': 'appdb',
'DB_USER': 'appuser'
}
app.config.update(db_settings)
任何用SANIC_前缀定义的变量都会读到sanic配置中被应用。例如,SANIC_REQUEST_TIMEOUT的设置将被应用程序自动加载,并被输入到REQUEST_TIMEOUT配置变量中。也可以传递不同的前缀给Sanic:
app = Sanic(__name__, load_env='MYAPP_'),这样就使用MYAPP_这个前缀了
相应的不想从环境变量读:app = Sanic(__name__, load_env=False)
# my_config.py长得如下
A = 1
B = 2
读取方法:
app.update_config("/path/to/my_config.py")
文件路径可以用环境变量:
$ export my_path="/path/to"
app.update_config("${my_path}/my_config.py")
class C:
A = 1
B = 2
app.update_config(C)
app.update_config(C())
Variable | Default | Description |
REQUEST_MAX_SIZE | 100000000 | How big a request may be (bytes) |
REQUEST_BUFFER_QUEUE_SIZE | 100 | Request streaming buffer queue size |
REQUEST_TIMEOUT | 60 | How long a request can take to arrive (sec) |
RESPONSE_TIMEOUT | 60 | How long a response can take to process (sec) |
RESPONSE_TIMEOUT | True | Disables keep-alive when False |
KEEP_ALIVE_TIMEOUT | 5 | How long to hold a TCP connection open (sec) |
WEBSOCKET_MAX_SIZE | 2^20 | Maximum size for incoming messages (bytes) |
WEBSOCKET_MAX_QUEUE | 32 | Maximum length of the queue that holds incoming messages |
WEBSOCKET_READ_LIMIT | 2^16 | High-water limit of the buffer for incoming bytes |
WEBSOCKET_WRITE_LIMIT | 2^16 | High-water limit of the buffer for outgoing bytes |
WEBSOCKET_PING_INTERVAL | 20 | A Ping frame is sent every ping_interval seconds. |
WEBSOCKET_PING_TIMEOUT | 20 | Connection is closed when Pong is not received after ping_timeout seconds |
GRACEFUL_SHUTDOWN_TIMEOUT | 15.0 | How long to wait to force close non-idle connection (sec) |
ACCESS_LOG | True | Disable or enable access log |
FORWARDED_SECRET | None | Used to securely identify a specific proxy server (see below) |
PROXIES_COUNT | None | The number of proxy servers in front of the app (e.g. nginx; see below) |
FORWARDED_FOR_HEADER | “X-Forwarded-For” | The name of “X-Forwarded-For” HTTP header that contains client and proxy ip |
REAL_IP_HEADER | None | The name of “X-Real-IP” HTTP header that contains real client ip |
from sanic.log import logger
from sanic.response import text
app = Sanic('logging_example')
@app.route('/')
async def test(request):
logger.info('Here is your log')
return text('Hello World!')
if __name__ == "__main__":
app.run(debug=True, access_log=True)
使用logging.config.dictConfig或者用log_config配置日志:
app = Sanic('logging_example', log_config=LOGGING_CONFIG)
if __name__ == "__main__":
app.run(debug=False,access_log=False)
%(asctime)s - (%(name)s)[%(levelname)s][%(host)s]: %(request)s %(message)s %(status)d %(byte)d
from sanic.response import json
@app.route("/json")
def post_json(request):
return json({ "received": True, "message": request.json })
from sanic.response import json
@app.route("/query_string")
def query_string(request):
return json({ "parsed": True, "args": request.args, "url": request.url, "query_string": request.query_string })
@app.route("/form")
def post_json(request):
return json({ "received": True, "form_data": request.form, "test": request.form.get('test') })
from sanic.response import text
@app.route("/users", methods=["POST",])
def create_user(request):
return text("You are trying to create a user with the following POST: %s" % request.body)
from sanic import response
@app.route('/html')
def handle_request(request):
return response.html('<p>Hello world!</p>')
from sanic import response
@app.route('/json')
def handle_request(request):
return response.json({'message': 'Hello world!'})
from sanic import Sanic
from sanic.views import HTTPMethodView
from sanic.response import text
app = Sanic('some_name')
class SimpleView(HTTPMethodView):
def get(self, request):
return text('I am get method')
def post(self, request):
return text('I am post method')
def put(self, request):
return text('I am put method')
def patch(self, request):
return text('I am patch method')
def delete(self, request):
return text('I am delete method')
class SimpleAsyncView(HTTPMethodView):
async def get(self, request):
return text('I am async get method')
async def post(self, request):
return text('I am async post method')
async def put(self, request):
return text('I am async put method')
app.add_route(SimpleView.as_view(), '/')
app.add_route(SimpleAsyncView.as_view(), '/async')
if __name__ == '__main__':
app.run(host="0.0.0.0", port=8000, debug=True)
from sanic import Sanic
from sanic import response
app = Sanic(__name__)
@app.route('/')
def handle_request(request):
return response.redirect('/redirect')
@app.route('/redirect')
async def test(request):
return response.json({"Redirected": True})
if __name__ == '__main__':
app.run(host="0.0.0.0", port=8000)
from sanic import response
import logging
logging_format = "[%(asctime)s] %(process)d-%(levelname)s "
logging_format += "%(module)s::%(funcName)s():l%(lineno)d: "
logging_format += "%(message)s"
logging.basicConfig(
format=logging_format,
level=logging.DEBUG
)
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")
sanic.run(host="0.0.0.0", port=8000)from sanic import response
import logging
logging_format = "[%(asctime)s] %(process)d-%(levelname)s "
logging_format += "%(module)s::%(funcName)s():l%(lineno)d: "
logging_format += "%(message)s"
logging.basicConfig(
format=logging_format,
level=logging.DEBUG
)
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")
sanic.run(host="0.0.0.0", port=8000)
去学习一下py3.5的异步编程咯...