当前位置: 首页 > 工具软件 > Sanic > 使用案例 >

sanic入门

尹何平
2023-12-01

都是抄的api:https://sanic.readthedocs.io/en/latest/index.html

 

安装:

  • pip3 install sanic
  • conda config --add channels conda-forge
    conda install sanic

如果不想安装uvloop或者ujson,可以:

SANIC_NO_UVLOOP=true SANIC_NO_UJSON=true pip3 install --no-binary :all: sanic

  

Demo:

 

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)

从文件、字典或者其他有__dict__属性的对象读取配置:

  • 从文件my_config.py:

# 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())

 

内置配置:

VariableDefaultDescription
REQUEST_MAX_SIZE100000000How big a request may be (bytes)
REQUEST_BUFFER_QUEUE_SIZE100Request streaming buffer queue size
REQUEST_TIMEOUT60How long a request can take to arrive (sec)
RESPONSE_TIMEOUT60How long a response can take to process (sec)
RESPONSE_TIMEOUTTrueDisables keep-alive when False
KEEP_ALIVE_TIMEOUT5How long to hold a TCP connection open (sec)
WEBSOCKET_MAX_SIZE2^20Maximum size for incoming messages (bytes)
WEBSOCKET_MAX_QUEUE32Maximum length of the queue that holds incoming messages
WEBSOCKET_READ_LIMIT2^16High-water limit of the buffer for incoming bytes
WEBSOCKET_WRITE_LIMIT2^16High-water limit of the buffer for outgoing bytes
WEBSOCKET_PING_INTERVAL20A Ping frame is sent every ping_interval seconds.
WEBSOCKET_PING_TIMEOUT20Connection is closed when Pong is not received after ping_timeout seconds
GRACEFUL_SHUTDOWN_TIMEOUT15.0How long to wait to force close non-idle connection (sec)
ACCESS_LOGTrueDisable or enable access log
FORWARDED_SECRETNoneUsed to securely identify a specific proxy server (see below)
PROXIES_COUNTNoneThe 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_HEADERNoneThe name of “X-Real-IP” HTTP header that contains real client ip

 

 

日志

demo: 

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

 

获取请求数据:

 

json (any) - JSON body

from sanic.response import json

@app.route("/json")
def post_json(request):
  return json({ "received": True, "message": request.json })

 args (dict) - Query string variables. A query string is the section of a URL that resembles ?key1=value1&key2=value2.

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 })

 form (dict) - Posted form variables

@app.route("/form")
def post_json(request):
  return json({ "received": True, "form_data": request.form, "test": request.form.get('test') })

 body (bytes) - Posted raw body

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)

 

创造响应值Response

html

from sanic import response

@app.route('/html')
def handle_request(request):
    return response.html('<p>Hello world!</p>')

 json

from sanic import response

@app.route('/json')
def handle_request(request):
    return response.json({'message': 'Hello world!'})

 一些demo:

  Simple App with Sanic Views

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)

 

URL Redirect

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)

 

Logging Enhancements

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的异步编程咯... 

 类似资料: