Sanic框架入门案例jinja2作模版

Make sure you have both pip and at least version 3.6 of Python before starting. Sanic uses the new async/await syntax, so earlier versions of python won’t work.
特点就是快,采用的是异步IO,适合前后端分离的项目,必须要求python3.6以上

安装

C:\Users\Administrator>python --version
Python 3.7.3
C:\Users\Administrator>pip install sanic
Collecting sanic
  Downloading sanic-20.6.3-py3-none-any.whl (74 kB)
     |████████████████████████████████| 74 kB 163 kB/s
Collecting httptools>=0.0.10
  Downloading httptools-0.1.1-cp37-cp37m-win_amd64.whl (95 kB)
     |████████████████████████████████| 95 kB 392 kB/s
****************************************************************************
Successfully installed aiofiles-0.5.0 h11-0.9.0 h2-3.2.0 hpack-3.0.0 hstspreload-2020.7.7 httptools-0.1.1 httpx-0.11.1 hyperframe-5.2.0 rfc3986-1.4.0 sanic-20.6.3 sniffio-1.1.0 websockets-8.1
C:\Users\Administrator>pip install sanic_cors
Collecting sanic_cors
  Downloading Sanic_Cors-0.10.0.post3-py2.py3-none-any.whl (17 kB)
****************************************************************************
Installing collected packages: sanic-plugins-framework, sanic-cors
Successfully installed sanic-cors-0.10.0.post3 sanic-plugins-framework-0.9.2
C:\Users\Administrator>pip install sanic-jinja2
Collecting sanic-jinja2
  Downloading sanic_jinja2-0.8.0-py3-none-any.whl (3.6 kB)
****************************************************************************
Installing collected packages: sanic-jinja2
Successfully installed sanic-jinja2-0.8.0

案例代码

# web.py
from sanic import Sanic,views
from sanic.response import text,json,html,file,redirect
from sanic.views import HTTPMethodView
from sanic_jinja2 import SanicJinja2 as sj
from sanic_cors import CORS

app = Sanic(__name__) #创建一个app
tp = sj(app)
CORS(app) #解决跨域

#当请求为/的时候自动执行下面的函数
@app.route('/')
def index(req): #必须有第一个参数,req参数表示请求信息
    print('Hello Index')
    return text('Hello CSDN')
#list.html为模板
@app.route('/list')
@tp.template('list.html')
def mylist(request):
    res = [1,2,3,]
    # return {'data':res}
    return {
        'data':[
            {'name':'tom','age':11},
            dict(name='Jerry',age=20)
        ]
    }
@app.route('/login',methods=['POST'])
def login(req):
    username = req.form.get('username')#列表长度为1自动取得第一个值
    password = req.form.get('password')
    hobby = req.form.get('hobby')
    # 
    # 
    # https://www.w3school.com.cn/tiy/t.asp?f=html_form_submit
    print(req.form.getlist('hobby'))#得到列表值 form表单中容易出现一个参数多个值的情况
    if username == 'zycdn' and password == 'zycdn':
        return json({'result':'success'})
    else:
        return json({'result':'fail'})

# path参数  http://127.0.0.1:5000/page/1.html http://127.0.0.1:5000/page/2.html
@app.route('/page/.html')
def page(req,page:int):
    return html(f'

{page}

'
) @app.route('/redirection') async def refunc(request): url = app.url_for('post_handler',post_id=5) return redirect(url) @app.route('/posts/') async def post_handler(request,post_id): return text(f'Post-{post_id}') class SimpleView(HTTPMethodView): def get(self,request): # 接收请求参数 参数以?形式传递 return json(request.args) def post(self,request): return text('post method') class SimpleAsyncView(HTTPMethodView): async def get(self,request): return text('async get method') async def post(self,request): return text('async post method') app.add_route(SimpleView.as_view(),'/sv') app.add_route(SimpleAsyncView.as_view(),'/async') if __name__ == "__main__": app.static('/static', './static') app.run(host='0.0.0.0',port=5000,debug=True)


<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>列表title>
head>
<body>
    {{data}}

    {% for d in data %}
    <p>{{d.name}}-{{d.age}}p>
    {% endfor %}
    
    <img src='/static/1.png'/>
body>
html>

调试

Sanic框架入门案例jinja2作模版_第1张图片
Sanic框架入门案例jinja2作模版_第2张图片

// 在浏览器的console中调试
var jquery_url = 'https://libs.cdnjs.net/jquery/3.5.1/jquery.min.js';
var script = document.createElement('script');
script.src = jquery_url;
document.head.appendChild(script);
var url ='http://127.0.0.1:5000/login';
$.ajax({
    url: url,
    method: 'post',
    data: {
        'username': 'zycdn',
        'password': 'zycdn',
		'hobby': 'hobby1',
        'hobby': 'hobby2',
    },
    success: function(data) {
        if (data.result == 'success') {
            console.log('success')
                //windw.location.href="maim.html"
        } else {
            console.log('fail')
        }
    }
})

var url ='http://127.0.0.1:5000/sv';
$.ajax({
    url: url,
    method: 'get',
    data: {
        'username': 'zycdn',
        'password': 'zycdn',
		'hobby': 'hobby1',
        'hobby': 'hobby2',
    },
	success:function(data){
		console.log(data)
	}
})

Sanic框架入门案例jinja2作模版_第3张图片

帮助文档

sanic文档
Sanic框架初识
Sanic static() 方法/函数
Sanic入门到进阶

你可能感兴趣的:(Python,web)