文章目录

一、Flask

Flask 简单请求功能
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import Flask,request
import os,sys,commands
reload(sys)
sys.setdefaultencoding('utf-8')

app = Flask(__name__)

@app.route('/')
def hello_world():
return "Hello World!"


@app.route('/buildInterface/<string:task_id>',methods=['POST'])
def create_app(task_id):
if task_id == "b06815c5078b99fa83da57b04bd8c25bd8cfef4b" :
print (request.headers)
print (request.form)
print (request.form['app_name'])
print (request.form['version'])
print (request.form['hashcode'])
app_name=request.form['app_name']
version = request.form['version']
hashcode =request.form['hashcode']

#os.environ['app_name']=str(app_name)
#os.environ['version']=str(version)
#os.environ['hashcode']=str(hashcode)

doshell = 'python /home/weblogic/rc_module.py %s %s %s' %(app_name,version,hashcode)
status,output=commands.getstatusoutput(doshell)
print (output )
return ("脚本完毕")


if __name__ == "__main__":
app.run(
host = '0.0.0.0',
port = 82,
debug = True
)

或者使用:

from flask import Flask,request
import os
from flask_restful import Resource, Api
from . import image_ocr

app = Flask(__name__)
api = Api(app)



todos = {}

class TodoSimple(Resource):
def get(self,todo_id):
result = {todo_id:todos[todo_id]}
return result
def put(self,todo_id)
todos[todo_id] = request.form['data']
if todo_id == "ocr":
ocr = image_ocr.OCR() # 文件名.类名
result = ocr.main(todos[todo_id])
else:
result = 'ocr failed'
return result

api.add_resource(TodoSimple,"/<string:todo_id>")


if __name__ == '__main__':
port = int(os.environ.get('PORT',5000))
app.run(host='0.0.0.0',port=port)

# image_ocr.py是进行OCR识别的,识别结果result=json.dumps({"field":"result"})
POST功能的简单接口
from flask import Flask, request, jsonify
import json

app = Flask(__name__)
app.debug = True

@app.route('/add/student/',methods=['post'])
def add_stu():
if not request.data: #检测是否有数据
return ('fail')
student = request.data.decode('utf-8')
#获取到POST过来的数据,因为我这里传过来的数据需要转换一下编码。根据晶具体情况而定
student_json = json.loads(student)
#把区获取到的数据转为JSON格式。
return jsonify(student_json)
#返回JSON数据。

if __name__ == '__main__':
app.run(host='192.168.1.154',port=1234)
#这里指定了地址和端口号。

实现了POST上传的功能,接来我们,就需要来测试一下这个功能是否完好实现了。

import requests,json

data = {
'id':1,
'name':'lily',
'age':11,
'birthplace':'san',
'grade':123
}
url = 'http://192.168.1.154:1234/add/student/'

r = requests.post(url,data=json.dumps(data))
print(r.json())

python web框架 flask与 sanic_html


快速入门:​​https://flask-restful.readthedocs.io/en/latest/quickstart.html​​​ 拓展Flask: ​​https://flask-restful.readthedocs.io/en/latest/extending.html​

Flask的API文档:​​https://flask-restful.readthedocs.io/en/latest/api.html​

二、sanic

类似Flask语法的异步框架sanic。
官方文档: ​​​https://www.osgeo.cn/sanic/sanic/getting_started.html​​ 仅支持:macOS/linux 且 python 3.6+

推荐使用Anaconda 安装​​pip install sanic​

简单的例子

from sanic import Sanic
from sanic.response import text
from sanic.exceptions import NotFound


app = Sanic(name="pyapp")

@app.route('/')
async def test(request):
return text('Hello World!')


if __name__ == '__main__':
app.error_handler.add(
NotFound,
lambda r, e: sanic.response.empty(status=404)
)
app.run(host='0.0.0.0', port=8000)

​$ curl -X GET http://127.0.0.1:8000/​​ 输出:Hello World!

请求阻塞test.py

from time import sleep

app = Sanic(name="pyapp")

@app.route('/')
async def test(request):
sleep(5)
return json({'hello': 'world'})
...

重启服务,通过浏览器发送请求,我们发现请求耗时5秒,这显然对用户就不能忍受的。

异步非堵塞
import asyncio
from sanic import Sanic
from sanic.response import json
from sanic.exceptions import NotFound
from time import sleep, ctime

app = Sanic(name="pyapp")

async def task_sleep():
print('sleep before', ctime())
await asyncio.sleep(5)
print('sleep after', ctime())


@app.route('/')
async def test(request):
myLoop = request.app.loop
myLoop.create_task(task_sleep())
return json({'hello': 'world'})


if __name__ == '__main__':
app.error_handler.add(
NotFound,
lambda r, e: sanic.response.empty(status=404)
)
app.run(host='0.0.0.0', port=8000)

​https://www.ucloud.cn/yun/41614.html​

请求参数

要指定一个参数,可以用像这样的角引号​​<PARAM>​​包围它。请求参数将作为关键字参数传递给路线处理程序函数。

实例:

from sanic import Sanic
from sanic.response import text

app = Sanic()


@app.route("/")
async def index(request):
return text('Hello World!')

@app.router('/tag/<tag>')
async def tag_handler(request, tag):
return text('Tag - {}'.format(tag))


if __name__ == "__main__":
app.run(host="0.0.0.0", port=9000)
$ curl

为参数指定类型,
在参数名后面添加(:类型)。如果参数不匹配指定的类型,Sanic将抛出一个不存在的异常,导致一个404页面

@app.route('/number/<integer_arg:int>')
async def integer_handler(request, integer_arg):
return text('Integer - {}'.format(integer_arg))


@app.route('/number/<number_arg:number>')
async def number_handler(request, number_arg):
return text('Number - {}'.format(number_arg))


@app.route('/person/<name:[A-z]+>')
async def person_handler(request, name):
return text('Person - {}'.format(name))


@app.route('/folder/<folder_id:[A-z0-9]{0,4}>')
async def folder_handler(request, folder_id):
return text('Folder - {}'.format(folder_id))
$ curl -X GET http://127.0.0.1:9000/number/1
Integer - 1
$ curl -X GET http://127.0.0.1:9000/number/asds
Error: Requested URL /number/asds not found
$ curl -X GET http://127.0.0.1:9000/number/12.0
Number - 12.0
$ curl -X GET http://127.0.0.1:9000/person/junxi
Person - junxi
$ curl -X GET http://127.0.0.1:9000/person/123
Error: Requested URL /person/123 not found
$ curl -X GET http://127.0.0.1:9000/folder/img
Folder - img
$ curl -X GET http://127.0.0.1:9000/folder/img1
Folder - img1
$ curl -X GET http://127.0.0.1:9000/folder/images
Error: Requested URL /folder/images not found
$ curl -X GET http://127.0.0.1:9000/folder/2018
Folder - 2018

路由装饰器接受一个可选的参数,方法,它允许处理程序函数与列表中的任何HTTP方法一起工作。

@app.route('/post1', methods=['POST'])
async def post_handler(request):
return text('POST request - {}'.format(request.json))


@app.route('/get1', methods=['GET'])
async def get_handler(request):
return text('GET request - {}'.format(request.args))
$ curl -X GET http://127.0.0.1:9000/get1?name=junxi
GET request - {'name': ['junxi']}

$ curl -H "Content-type: application/json" -X POST -d '{"name":"junxi", "gender":"male"}' http://127.0.0.1:9000/post1
POST request - {'name': 'junxi', 'gender': 'male'}

更多的sanic示例:
​​​https://www.osgeo.cn/sanic/sanic/examples.html​​​​https://www.ucloud.cn/yun/41614.html​

sanic异步框架之中文文档
官方文档:​​​https://www.osgeo.cn/sanic/sanic/​​​​https://sanicframework.org/zh/​​​​https://www.zhihu.com/question/372401741/answer/1021575465​​​​https://www.jianshu.com/p/0cad84188df4​​​​https://www.jianshu.com/p/bc95b1e90129​