aiohttp web服务端(server)样例 (非client)

时间:2022-09-05 13:12:02

python版本 python3.6 (其他版本需要小改,版本>python3.4)

参考网址:https://www.cnblogs.com/ameile/p/5589808.html  asyncio创建协程解析——分析廖雪峰的Python教程之创建WEB服务

本实例接收 字符串类型值 ;

客户端发送过来的数据类型都是字符串,不能为二进制流(折衷方式可base64编码成字符串)。

import os
import re
import sys
import time
import json
import socket
import base64
import logging
import asyncio
import aiohttp
import datetime
from config import *
from aiohttp import web
from urllib.request import urlopen
from mlogging import TimedRotatingFileHandler_MP

ip = str(sys.argv[2])
conn = aiohttp.TCPConnector(limit=1000)
session = aiohttp.ClientSession(connector=conn)

log_name = os.path.join('./log','log_http.log')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh = TimedRotatingFileHandler_MP('./log/log_http.log', 'D', 1, CYCLE_TIME)
fh.setFormatter(formatter)
log = logging.getLogger('http_recv')
log.setLevel(logging.DEBUG)
log.addHandler(fh)

def b2base(b):
b = base64.b64encode(b)
b = str(b)
b = b[2:len(b)-1]
return b
async def downloadurl(dic):
try:
Prior = str(dic['Prior'])
FileId = str(dic['FileId'])
AppId = str(dic['AppID'])
except:
return 400
if len(Prior.strip()) == 0 or len(FileId.strip()) == 0 or len(AppId.strip()) == 0:
return 401
try:
if len(dic['FileUrl'].strip()) > 0 and len(dic['File'].strip()) > 0:
return 402
except:
pass
try:
if len(dic['FileUrl'].strip()) > 0:
try:
Resp = urlopen(dic['FileUrl'],timeout=5)
File = Resp.read()
except socket.timeout as e:
return 404
except:
return 403
except:
return 400
AppId = AppId + str(datetime.datetime.now().strftime('%Y-%m-%d'))
FileName = FileId + '_' + AppId + '_'
return FileName + b2base(File)

async def deal_error(code):
if code == 400:
return json.dumps({ "code":400,"errMessage":"请求参数不正确." }, ensure_ascii=False).encode('utf-8')
elif code == 401:
return json.dumps({ "code":404,"errMessage":"图片下载超时." }, ensure_ascii=False).encode('utf-8')
elif code == 402:
return json.dumps({ "code":402,"errMessage":"同时传入了要求是二选一或者多选一的参数." }, ensure_ascii=False).encode('utf-8')
elif code == 403:
return json.dumps({ "code":403,"errMessage":"无法从指定的FileUrl下载图片,图片URL错误或者无效." }, ensure_ascii=False).encode('utf-8')
elif code == 404:
return json.dumps({ "code":404,"errMessage":"图片下载超时." }, ensure_ascii=False).encode('utf-8')
else:
return json.dumps({ "code":500,"errMessage":"其他错误." }, ensure_ascii=False).encode('utf-8')

async def FileDealPost(request):
info = request.message
log.info("info_post = %s",info)
try:
info = await request.text()
log.info("info = %s",info)
reg = 'name="([a-zA-Z]*)".*?\r\n\r\n\W*(\S*)-*'
li = re.findall(reg,info,re.S)
dic = dict(li)
data_base64 = await downloadurl(dic)
except Exception as e:
log.info("error_post = %s",e)
if data_base64 in [400,401,402,403,404]:
result = await deal_error(data_base64)
return web.Response(body = result)
#async with session.post('http://'+ip+':1218/?name=ocr_image_indb&opt=put',data=data_base64,timeout = 0) as resp:
async with session.post('http://'+ip+':1218/?name=image&opt=put',data=data_base64,timeout = 0) as resp:
result = await resp.text()
if result == 'HTTPSQS_PUT_OK':
return web.Response(body = json.dumps({ "code":0,"errMessage":"成功" }, ensure_ascii=False).encode('utf-8'))
elif result == 'HTTPSQS_PUT_END':
return web.Response(body = json.dumps({ "code":-1,"errMessage":"请求已达上限,稍微再试." }, ensure_ascii=False).encode('utf-8'))
else:
return web.Response(body = json.dumps({ "code":-2,"errMessage":"入消息队列失败." }, ensure_ascii=False).encode('utf-8'))

async def FileDealGet(request):
info = request.message
log.info("info_get = %s",info)
try:
info = request.message.path
reg = '[?&]([a-zA-Z]*)=([^&]*)'
li = re.findall(reg,info)
dic = dict(li)
data_base64 = await downloadurl(dic)
except Exception as e:
log.info("error_get = %s",e)
if data_base64 in [400,401,402,403,404]:
result = await deal_error(data_base64)
return web.Response(body = result)
#async with session.post('http://'+ip+':1218/?name=ocr_image_indb&opt=put',data=data_base64,timeout = 0) as resp:
async with session.post('http://'+ip+':1218/?name=image&opt=put',data=data_base64,timeout = 0) as resp:
result = await resp.text()
if result == 'HTTPSQS_PUT_OK':
return web.Response(body = json.dumps({ "code":0,"errMessage":"成功" }, ensure_ascii=False).encode('utf-8'))
elif result == 'HTTPSQS_PUT_END':
return web.Response(body = json.dumps({ "code":-1,"errMessage":"请求已达上限,稍微再试." }, ensure_ascii=False).encode('utf-8'))
else:
return web.Response(body = json.dumps({ "code":-2,"errMessage":"入消息队列失败." }, ensure_ascii=False).encode('utf-8'))

async def init(loop):
app = web.Application(loop=loop)
app.router.add_route('POST', '/file', FileDealPost)
app.router.add_route('GET', '/file', FileDealGet)
srv = await loop.create_server(app.make_handler(),'10.10.11.32', int(sys.argv[1]))
return srv

loop = asyncio.get_event_loop()
loop.run_until_complete(init(loop))
loop.run_forever()