zoukankan      html  css  js  c++  java
  • python 调用百度翻译接口,使用flask 提供接口,实现线上翻译功能

    #conding=utf-8
    from flask import Flask, redirect, url_for, request, render_template, send_from_directory
    import json
    import requests
    import random
    import urllib
    import hashlib
    import time
    app = Flask(__name__)
    
    @app.route('/',methods=["POST"])
    def fanyi_interface():
        src = request.form
    
        from_lang = src["from_lang"]
        to_lang = src["to_lang"]
        msg = src["msg"]
        res = baidu_t(from_lang,to_lang,msg)
        return json.dumps(res)
    
    LAST_TIME = 0
    def baidu_t(from_lang,to_lang,msg):
        global LAST_TIME
        # Control QPS=1
        if round(time.time()) - LAST_TIME == 1:
            time.sleep(1)
        appid = '******'
        secret_key = '******'
        url = 'http://api.fanyi.baidu.com/api/trans/vip/translate'
        from_lang = from_lang  # 原文语种
        to_lang = to_lang  # 译文语种
        salt = random.randint(32768, 65536)
        sign = appid + msg + str(salt) + secret_key
        sign = hashlib.md5(sign.encode()).hexdigest()
    
        data = {
        "from":from_lang,
        "to": to_lang,
        "q": msg,
        "appid":appid,
        "salt":salt,
        "sign": sign,
    
        }
        headers = {
            "Content-Type": "application/x-www-form-urlencoded"
        }
        LAST_TIME = round(time.time())
        res = requests.post(url=url,data=data,headers=headers)
        print(res.json())
        return res.json()
    
    if __name__ == '__main__':
        # while True:
        #     main()
        # language is
        # 自动检测	auto
        # 中文	zh
        # 英语	en
        # 繁体中文	cht
        # baidu_t(from_lang="zh",to_lang="cht",msg="公鸡")
    
        app.run(debug=True)
    

      

  • 相关阅读:
    unittest learning
    C++类和对象
    Linux shell基础(十二)
    Linux shell基础(十一)
    Linux shell基础(十)
    Linux shell基础(九)
    Linux shell基础(八)
    Linux shell基础(六)
    Linux shell基础(七)
    Linux shell基础(五)
  • 原文地址:https://www.cnblogs.com/royfans/p/14554413.html
Copyright © 2011-2022 走看看