aiohttp web服務端(server)樣例 (非client)

python版本 python3.6 (其餘版本須要小改,版本>python3.4)html

參考網址:https://www.cnblogs.com/ameile/p/5589808.html  asyncio建立協程解析——分析廖雪峯的Python教程之建立WEB服務python

本實例接收 字符串類型值 ;web

客戶端發送過來的數據類型都是字符串,不能爲二進制流(折衷方式可base64編碼成字符串)。json

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()
相關文章
相關標籤/搜索