#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"
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)