python对外提供接口将数据放入rabbitmq

  注意:1)并发量不太大的时候这样使用可以,如果并发较大建议还是用java进行实现。

     2)此处建议使用python3

# coding:utf-8
import json
import time
import pika
from flask import Flask, request

app = Flask(__name__)

MY_URL = '/knowledge/api/v1/'

def push_mess(param):
    connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
    channel = connection.channel()
    channel.basic_publish(exchange='',
                      routing_key='myquence',
                      body=param)
    print("[knowledge] Send "+param)
    connection.close()
resu = {"code": 200,"result":"success!"}
now = time.time()
# get
@app.route(MY_URL + 'get/tasks', methods=['GET'])
def get_task():
    param = request.args.to_dict()
    # print(param)  # request.args请求参数
    # print(type(param))
    # print(param)
      if len(param)<9:
       resu_other = {"code": 506,"result":"parameter missing!"}
       return json.dumps(resu_other, ensure_ascii=False)

    param.setdefault('logTime',int(now))
    push_mess(json.dumps(param,ensure_ascii=False))        
    return json.dumps(resu, ensure_ascii=False)


# post
@app.route(MY_URL + 'post/tasks', methods=['POST'])
def post_task():
    param = request.args.to_dict()
    # print(param)  # request.args请求参数
    # print(type(param)) 此处post仅支持一般使用方法
    # print(param)
      if len(param)<9:
       resu_other = {"code": 506,"result":"parameter missing!"}
       return json.dumps(resu_other, ensure_ascii=False)

    param.setdefault('logTime',int(now))
    push_mess(json.dumps(param,ensure_ascii=False))
    return json.dumps(resu, ensure_ascii=False)

    #解决请求跨域问题    
def after_request(resp):
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp

if __name__ == '__main__':
    app.after_request(after_request)
    app.run(debug=True, host='0.0.0.0', port=5000)
    # app.run(debug=True)  host 0.0.0.0设置是都可以进行访问,port为对应内网端口
# http://127.0.0.1:5000/knowledge/api/v1/get/tasks?keystr=服务器上架&topN=3

 

  注意导入相关类库,rabbitmq此处默认使用guest用户,密码也是初始状态。如果需要使用其他用户端口,可查看ConnectionParameters设置的相关参数介绍。mq队列相关设置建议先用ui界面设置好。

  后续采用ck订阅消费请查看:https://www.cnblogs.com/MrYang-11-GetKnow/p/16397055.html

其他:结合RSA加密数据代码

#!/usr/bin/env python3
# coding:utf-8

import json
import time
import pika
from flask import Flask, request
import base64
from Crypto import Random
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
from Crypto.PublicKey import RSA
from json.decoder import JSONDecodeError
import binascii
from flask_cors import CORS

def long_encrypt(msg):
    msg = msg.encode('utf-8')
    length = len(msg)
    default_length = 117
    # 公钥加密
    rsa_public_key = open('conf/public.pem').read()
    pubobj = Cipher_pkcs1_v1_5.new(RSA.importKey(rsa_public_key))
    # 长度不用分段
    if length < default_length:
        return base64.b64encode(pubobj.encrypt(msg))
    # 需要分段
    offset = 0
    res = []
    while length - offset > 0:
        if length - offset > default_length:
            res.append(pubobj.encrypt(msg[offset:offset + default_length]))
        else:
            res.append(pubobj.encrypt(msg[offset:]))
        offset += default_length
    byte_data = b''.join(res)
    return base64.b64encode(byte_data)


def long_decrypt(msg):
    msg = base64.b64decode(msg)
    length = len(msg)
    default_length = 128
    # 私钥解密
    rsa_private_key = open('conf/private.pem').read()
    priobj = Cipher_pkcs1_v1_5.new(RSA.importKey(rsa_private_key))
    # 长度不用分段
    if length < default_length:
        return b''.join(priobj.decrypt(msg, b'xyz'))
    # 需要分段
    offset = 0
    res = []
    while length - offset > 0:
        if length - offset > default_length:
            res.append(priobj.decrypt(msg[offset:offset + default_length], b'xyz'))
        else:
            res.append(priobj.decrypt(msg[offset:], b'xyz'))
        offset += default_length

    return b''.join(res).decode('utf8')
app = Flask(__name__)
CORS(app, supports_credentials=True)
MY_URL = '/1M2n3B4v/merMess/api/v1/'


def push_mess(param):
    connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
    channel = connection.channel()
    channel.basic_publish(exchange='',
                          routing_key='merloc_getmess',
                          body=param)
    connection.close()
resu = {"code": 200,"result":"success!"}

# get
@app.route(MY_URL + 'get/tasks', methods=['GET'])
def get_task():
    thMess = request.args.get('tradeMess')
    args_temp=long_decrypt(thMess)
    param = args_temp.to_dict()
    if len(param)<9:
        resu_other = {"code": 506,"result":"parameter missing!"}
        return json.dumps(resu_other, ensure_ascii=False)
    getnow = time.time()
    param.setdefault('logTime',int(getnow))
    push_mess(json.dumps(param,ensure_ascii=False))

    return json.dumps(resu, ensure_ascii=False)


# post
@app.route(MY_URL + 'post/tasks', methods=['POST'])
def post_task():
    try:
        thMess = request.json.get('tradeMess')
        if thMess is None:
            resu_other = {"code": 505,"result":"invalid parameter name!"}
            return json.dumps(resu_other, ensure_ascii=False)
        args_temp=long_decrypt(thMess)
        param = json.loads(args_temp)
        if len(param)<9:
            resu_other = {"code": 506,"result":"parameter missing!"}
            return json.dumps(resu_other, ensure_ascii=False)
        for value in param.values():
            if isinstance(value, str):
                continue
            else:
                resu_other = {"code": 509,"result":"invalid parameter type!"}
                return json.dumps(resu_other, ensure_ascii=False)
        postnow = time.time()
        param.setdefault('logTime',int(postnow))
        push_mess(json.dumps(param,ensure_ascii=False))
        print(param)
    except JSONDecodeError as e:
        resu_other = {"code": 507,"result":"parameter is illegal!"}
        return json.dumps(resu_other, ensure_ascii=False)
    except binascii.Error as err:
        resu_other = {"code": 508,"result":"encryption algorithm exception!"}
        return json.dumps(resu_other, ensure_ascii=False)
    else:
        print(request.json)

    return json.dumps(resu, ensure_ascii=False)

def after_request(resp):
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp

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

 

posted @ 2022-06-21 15:57  渐逝的星光  阅读(521)  评论(0编辑  收藏  举报