优化代码

dependabot/npm_and_yarn/fir_admin/axios-0.21.2
MMXX 3 years ago
parent d15b583804
commit fc1963c8a9
  1. 2
      fir_client/package.json
  2. 20
      fir_client/src/components/FirDownload.vue
  3. 15
      fir_client/src/components/FirLogin.vue
  4. 3
      fir_client/src/components/FirRegist.vue
  5. 3
      fir_client/src/components/FirResetPwd.vue
  6. 20
      fir_client/src/components/ShortDownload.vue
  7. 15
      fir_client/src/components/user/FirUserOrders.vue
  8. 3
      fir_client/src/components/user/FirUserProfileCertification.vue
  9. 14
      fir_client/src/components/user/FirUserProfileInfo.vue
  10. 42
      fir_client/src/restful/download.js
  11. 15
      fir_client/src/restful/index.js
  12. 65
      fir_client/src/utils/base/utils.js
  13. 62
      fir_client/src/utils/index.js
  14. 42
      fir_ser/api/views/login_wx.py
  15. 14
      fir_ser/api/views/order.py
  16. 18
      fir_ser/common/base/magic.py
  17. 12
      fir_ser/common/cache/storage.py
  18. 81
      fir_ser/common/utils/pending.py
  19. 14
      fir_ser/config.py
  20. 2
      fir_ser/fir_ser/settings.py
  21. 10
      fir_ser/xsign/views/receiveudids.py

@ -11,7 +11,7 @@
"dependencies": {
"ali-oss": "^6.5.1",
"app-info-parser": "^0.3.9",
"axios": "^0.19.0",
"axios": "^0.22.0",
"core-js": "^3.4.4",
"element-ui": "^2.13.0",
"js-base64": "^2.5.2",

@ -352,16 +352,8 @@
<script>
import QRCode from 'qrcodejs2'
import {
appReport,
checkEmail,
checkphone,
geetest,
getAuthTokenFun,
getdownloadurl,
getShortAppinfo,
gettask
} from '@/restful/download'
import {appReport, geetest, getAuthTokenFun, getdownloadurl, getShortAppinfo, gettask} from '@/restful/download'
import {checkEmail, checkphone, getRandomStr} from "@/utils/base/utils";
export default {
name: "FirDownload",
@ -425,7 +417,7 @@ export default {
mobileprovision: '',
ad_info: {ad_pic: '', ad_uri: ''},
task_spend_time: 0,
task_msg: ''
task_msg: '执行中'
}
},
beforeDestroy() {
@ -552,7 +544,7 @@ export default {
duration: 0
});
},
loop_check_task(c_count = 1, loop_t) {
loop_check_task(c_count = 1, loop_t, unique_key = getRandomStr()) {
if (c_count === 1) {
// eslint-disable-next-line no-unused-vars
loop_t = window.setInterval(res => {
@ -583,12 +575,12 @@ export default {
this.task_msg = data.msg;
}
if (data.code === 1001) {
this.loop_check_task(c_count, loop_t)
this.loop_check_task(c_count, loop_t, unique_key)
}
}
}, {
"short": this.$route.params.short,
data: {"task_id": this.$route.query.task_id}
data: {"task_id": this.$route.query.task_id, "unique_key": unique_key}
})
},
jiaocheng(act) {

@ -104,7 +104,8 @@
<script>
import {loginFun, set_auth_token, wxLoginFun} from "@/restful";
import {checkEmail, checkphone, geetest} from "@/utils";
import {geetest} from "@/utils";
import {checkEmail, checkphone, getRandomStr} from "@/utils/base/utils";
export default {
name: "FirLogin",
@ -126,6 +127,7 @@ export default {
wx_login_qr_url: '',
wx_visible: false,
loop_flag: false,
unique_key: ''
}
},
methods: {
@ -139,7 +141,7 @@ export default {
set_auth_token();
this.$router.push({name: 'FirApps'})
},
loop_get_wx_info(wx_login_ticket, c_count = 1) {
loop_get_wx_info(wx_login_ticket, c_count = 1, unique_key = getRandomStr()) {
if (wx_login_ticket && wx_login_ticket.length < 3) {
this.$message.error("获取登陆码失败,请稍后再试");
return
@ -162,12 +164,14 @@ export default {
type: 'error',
duration: 30000
});
} else if (data.code === 1004) {
this.loop_flag = false;
} else if (data.code === 1006) {
return this.loop_get_wx_info(wx_login_ticket, c_count)
return this.loop_get_wx_info(wx_login_ticket, c_count, unique_key)
}
}, {
"methods": "POST",
data: {"ticket": wx_login_ticket}
data: {"ticket": wx_login_ticket, "unique_key": unique_key}
})
// }, 3000)
@ -187,7 +191,7 @@ export default {
this.loop_flag = false;
}
}, {
"methods": "GET",
"methods": "GET", "data": {"unique_key": this.unique_key}
})
} else {
this.loop_flag = false;
@ -337,6 +341,7 @@ export default {
},
mounted() {
this.get_auth_code();
this.unique_key = getRandomStr();
}, created() {
}
}

@ -88,7 +88,8 @@
<script>
import {getAuthTokenFun, registerFun} from "@/restful";
import {checkEmail, checkphone, geetest} from "@/utils";
import {geetest} from "@/utils";
import {checkEmail, checkphone} from "@/utils/base/utils";
export default {
name: "FirRegist",

@ -72,7 +72,8 @@
<script>
import {loginFun} from "@/restful";
import {checkEmail, checkphone, geetest} from "@/utils";
import {geetest} from "@/utils";
import {checkEmail, checkphone} from "@/utils/base/utils";
export default {
name: "FirResetPwd",

@ -339,16 +339,8 @@
<script>
import QRCode from 'qrcodejs2'
import {
appReport,
checkEmail,
checkphone,
geetest,
getAuthTokenFun,
getdownloadurl,
getShortAppinfo,
gettask
} from '@/restful/download'
import {appReport, geetest, getAuthTokenFun, getdownloadurl, getShortAppinfo, gettask} from '@/restful/download'
import {checkEmail, checkphone, getRandomStr} from "@/utils/base/utils";
export default {
name: "ShortDownload",
@ -414,7 +406,7 @@ export default {
mobileprovision: '',
ad_info: {ad_pic: '', ad_uri: ''},
task_spend_time: 0,
task_msg: ''
task_msg: '执行中'
}
},
beforeDestroy() {
@ -518,7 +510,7 @@ export default {
this.msg = msg;
alert(this.msg)
},
loop_check_task(c_count = 1, loop_t) {
loop_check_task(c_count = 1, loop_t, unique_key = getRandomStr()) {
if (c_count === 1) {
// eslint-disable-next-line no-unused-vars
loop_t = window.setInterval(res => {
@ -548,12 +540,12 @@ export default {
this.task_msg = data.msg;
}
if (data.code === 1001) {
this.loop_check_task(c_count, loop_t)
this.loop_check_task(c_count, loop_t, unique_key)
}
}
}, {
"short": this.$route.params.short,
data: {"task_id": this.$route.query.task_id}
data: {"task_id": this.$route.query.task_id, "unique_key": unique_key}
})
},
jiaocheng(act) {

@ -250,6 +250,7 @@
import {my_order, order_sync} from "@/restful";
import {format_choices, getUserInfoFun} from '@/utils'
import VueQr from 'vue-qr';
import {getRandomStr} from "@/utils/base/utils";
export default {
name: "FirUserOrders",
@ -279,6 +280,7 @@ export default {
show_order_info: false,
current_order_info: {},
loading: false,
unique_key: ''
}
},
methods: {
@ -298,10 +300,11 @@ export default {
})
},
loop_get_order_info(order_number, c_count = 1) {
loop_get_order_info(order_number, c_count = 1, unique_key = getRandomStr()) {
if (!this.wx_pay) {
return
}
this.unique_key = unique_key;
order_sync(data => {
c_count += 1;
if (c_count > 30) {
@ -311,12 +314,17 @@ export default {
this.$message.success(data.msg);
this.get_data_from_tabname();
this.wx_pay = false;
} else if (data.code === 1004) {
this.loop_flag = false;
if (this.unique_key === unique_key) {
this.wx_pay = false;
}
} else if (data.code === 1001) {
return this.loop_get_order_info(order_number, c_count)
return this.loop_get_order_info(order_number, c_count, unique_key)
}
}, {
"methods": "POST",
data: {"order_number": order_number}
data: {"order_number": order_number, 'unique_key': unique_key}
})
},
@ -454,6 +462,7 @@ export default {
this.order_id_seach = out_trade_no;
}
this.get_data_from_tabname();
this.unique_key = getRandomStr();
}, filters: {}
}
</script>

@ -222,7 +222,8 @@
<script>
import {changeInfoFun, getAuthcTokenFun, user_certification} from "@/restful";
import {AvatarUploadUtils, checkphone, geetest, getUserInfoFun} from "@/utils";
import {AvatarUploadUtils, geetest, getUserInfoFun} from "@/utils";
import {checkphone} from "@/utils/base/utils";
export default {
name: "FirUserProfileCertification",

@ -305,6 +305,7 @@
import {changeInfoFun, getAuthcTokenFun, userinfos, wxBindFun, wxLoginFun, wxutils, wxWebScanFun} from '@/restful'
import {deepCopy, geetest} from "@/utils";
import VueQr from 'vue-qr';
import {getRandomStr} from "@/utils/base/utils";
export default {
name: "FirUserProfileInfo",
@ -340,6 +341,7 @@ export default {
wx_web_login_url: '',
wx_user_list: [],
pagination: {"currentPage": 1, "total": 0, "pagesize": 999},
unique_key: ''
}
}, methods: {
wx_web_login_fun() {
@ -397,7 +399,7 @@ export default {
}
})
},
loop_get_wx_info(wx_login_ticket, c_count = 1) {
loop_get_wx_info(wx_login_ticket, c_count = 1, unique_key = getRandomStr()) {
if (wx_login_ticket && wx_login_ticket.length < 3) {
this.$message.error("获取登陆码失败,请稍后再试");
return
@ -421,12 +423,14 @@ export default {
type: 'error',
duration: 30000
});
} else if (data.code === 1004) {
this.loop_flag = false;
} else if (data.code === 1006) {
return this.loop_get_wx_info(wx_login_ticket, c_count)
return this.loop_get_wx_info(wx_login_ticket, c_count, unique_key)
}
}, {
"methods": "POST",
data: {"ticket": wx_login_ticket}
data: {"ticket": wx_login_ticket, "unique_key": unique_key}
})
},
wxLogin() {
@ -442,7 +446,7 @@ export default {
this.wx_visible = false;
}
}, {
"methods": "POST",
"methods": "POST", "data": {"unique_key": this.unique_key}
})
}
},
@ -615,7 +619,7 @@ export default {
// this.updateUserInfo({"methods":false});
this.userinfo = this.$store.state.userinfo;
this.orguserinfo = deepCopy(this.$store.state.userinfo);
this.unique_key = getRandomStr();
}, watch: {
'$store.state.userinfo': function () {

@ -1,4 +1,5 @@
import Axios from 'axios'
import {geetestbase} from "@/utils/base/utils";
Axios.defaults.withCredentials = true;
@ -150,46 +151,11 @@ export function getAuthTokenFun(callBack, params) {
);
}
export function checkEmail(email) {
let re = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
return re.test(email);
}
export function checkphone(email) {
let re = /^1\d{10}$/;
return re.test(email);
}
export function geetest(self, uid, params, callback) {
loginFun(res => {
if (res.code === 1000) {
let data = res.data;
// eslint-disable-next-line no-undef
initGeetest({
gt: data.gt,
challenge: data.challenge,
new_captcha: data.new_captcha, // 用于宕机时表示是新验证码的宕机
offline: !data.success, // 表示用户后台检测极验服务器是否宕机,一般不需要关注
product: "float", // 产品形式,包括:float,popup
width: "100%"
}, (captchaObj) => {
self.$refs.captcha.innerHTML = '';
captchaObj.appendTo("#captcha");
captchaObj.onReady(() => {
}).onSuccess(() => {
params.geetest = captchaObj.getValidate();
callback(params);
}).onError(() => {
captchaObj.destroy();
});
});
} else {
alert(res.msg);
}
}, {
"methods": "PUT",
"data": {user_id: uid}
});
return geetestbase(self, loginFun, uid, params, callback, res => {
alert(res.msg);
})
}
/** 超级签名************************************************相关api */

@ -8,6 +8,11 @@ Axios.defaults.withCredentials = true;
// Axios.defaults.httpsAgent = new https.Agent({
// keepAlive: true
// });
const controller = new AbortController();
export function requestAbort() {
controller.abort();
}
// eslint-disable-next-line no-console
console.log("flyapps js version:" + process.env.base_env.version);
@ -138,7 +143,7 @@ function getData(methods, url, params = {}, callBack, load, isCode = false) {
if (methods === "DELETE") {
Axios
.delete(url, {params: params})
.delete(url, {params: params, signal: controller.signal})
.then(function (response) {
if (isCode) {
callBack(response.data);
@ -153,7 +158,7 @@ function getData(methods, url, params = {}, callBack, load, isCode = false) {
} else if (methods === "PUT") {
Axios
.put(url, params)
.put(url, params, {signal: controller.signal})
.then(function (response) {
if (isCode) {
callBack(response.data);
@ -168,7 +173,7 @@ function getData(methods, url, params = {}, callBack, load, isCode = false) {
} else if (methods === 'POST') {
Axios
.post(url, params)
.post(url, params, {signal: controller.signal})
.then(function (response) {
if (isCode) {
callBack(response.data);
@ -183,7 +188,7 @@ function getData(methods, url, params = {}, callBack, load, isCode = false) {
});
} else if (methods === 'FILE') {
Axios
.get(url, {params: params, responseType: 'blob'})
.get(url, {params: params, responseType: 'blob', signal: controller.signal})
.then(function (response) {
convertRes2Blob(response)
})
@ -193,7 +198,7 @@ function getData(methods, url, params = {}, callBack, load, isCode = false) {
});
} else {
Axios
.get(url, {params: params})
.get(url, {params: params, signal: controller.signal})
.then(function (response) {
callBack(response.data);
})

@ -0,0 +1,65 @@
export function GetRandomNum(Min, Max) {
const Range = Max - Min;
const Rand = Math.random();
return (Min + Math.round(Rand * Range));
}
export function getRandomStr(str_length = 32) {
const SIGNING_v1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'//36
// const SIGNING_v2 ='ABCDEFGHJKMNPQRSTUVWXYZ23456789'//31
// const SIGNING_v3 ='1234567890'//10
// const SIGNING_v4 ='ABCDEFGHIJKLMNOPQRSTUVWXYZ'//26
const SIGNING_v5 = 'abcdefghigklmnopqrstuvwxyz'//26
let random_str = SIGNING_v1 + SIGNING_v5
let random_code = ''
str_length -= 1
for (let i = 0; i < str_length; i++) {
random_code = random_code + random_str[GetRandomNum(0, str_length)]
}
return random_code
}
export function checkEmail(email) {
let re = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
return re.test(email);
}
export function checkphone(email) {
let re = /^1\d{10}$/;
return re.test(email);
}
export function geetestbase(func, self, uid, params, callback, errback, readyback) {
func(res => {
if (res.code === 1000) {
let data = res.data;
// eslint-disable-next-line no-undef
initGeetest({
gt: data.gt,
challenge: data.challenge,
new_captcha: data.new_captcha, // 用于宕机时表示是新验证码的宕机
offline: !data.success, // 表示用户后台检测极验服务器是否宕机,一般不需要关注
product: "float", // 产品形式,包括:float,popup
width: "100%"
}, (captchaObj) => {
self.$refs.captcha.innerHTML = '';
captchaObj.appendTo("#captcha");
captchaObj.onReady(() => {
readyback()
}).onSuccess(() => {
params.geetest = captchaObj.getValidate();
callback(params);
}).onError(() => {
captchaObj.destroy();
});
});
} else {
errback(res)
}
}, {
"methods": "PUT",
"data": {user_id: uid}
});
}

@ -1,5 +1,8 @@
//滚动条在Y轴上的滚动距离
import {geetestbase} from "@/utils/base/utils";
import {getuploadurl, loginFun, uploadimgs, uploadstorage, userinfos} from '@/restful'
export function getScrollTop() {
let scrollTop = 0, bodyScrollTop = 0, documentScrollTop = 0;
if (document.body) {
@ -234,16 +237,14 @@ export function uploadaliyunoss(file, certinfo, app, successcallback, processcal
}
import {getuploadurl, loginFun, uploadimgs, uploadstorage, userinfos} from '@/restful'
export function uploadlocalstorage(file, certinfo, app, successcallback, processcallback) {
uploadstorage(certinfo, file, successcallback, processcallback)
}
export function removeAaary(_arr, _obj) {
var length = _arr.length;
for (var i = 0; i < length; i++) {
let length = _arr.length;
for (let i = 0; i < length; i++) {
if (_arr[i] == _obj) {
if (i == 0) {
_arr.shift(); //删除并返回数组的第一个元素
@ -326,15 +327,6 @@ export function deepCopy(data) {
return obj;
}
export function checkEmail(email) {
let re = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
return re.test(email);
}
export function checkphone(email) {
let re = /^1\d{10}$/;
return re.test(email);
}
export function ImgToBase64(url, callback) {
let Img = new Image(),
@ -359,41 +351,15 @@ export function geetest(self, uid, params, callback) {
text: 'Loading',
spinner: 'el-icon-loading',
});
loginFun(res => {
if (res.code === 1000) {
let data = res.data;
// eslint-disable-next-line no-undef
initGeetest({
gt: data.gt,
challenge: data.challenge,
new_captcha: data.new_captcha, // 用于宕机时表示是新验证码的宕机
offline: !data.success, // 表示用户后台检测极验服务器是否宕机,一般不需要关注
product: "float", // 产品形式,包括:float,popup
width: "100%"
}, (captchaObj) => {
self.$refs.captcha.innerHTML = '';
captchaObj.appendTo("#captcha");
captchaObj.onReady(() => {
loading.close()
}).onSuccess(() => {
params.geetest = captchaObj.getValidate();
callback(params);
}).onError(() => {
captchaObj.destroy();
});
});
} else {
self.$message({
message: res.msg,
type: 'error'
});
}
}, {
"methods": "PUT",
"data": {user_id: uid} //self.form.email
});
return geetestbase(self, loginFun, uid, params, callback, res => {
self.$message({
message: res.msg,
type: 'error'
});
// eslint-disable-next-line no-unused-vars
}, _ => {
loading.close()
})
}
export function format_money(s, n = 2) {

@ -8,12 +8,13 @@ from api.utils.response import BaseResponse
from api.utils.serializer import UserInfoSerializer
from api.utils.utils import set_user_token
from common.base.baseutils import get_real_ip_address
from common.base.magic import get_pending_result
from common.cache.storage import WxLoginBindCache
from common.core.auth import ExpiringTokenAuthentication
from common.core.sysconfig import Config
from common.core.throttle import VisitRegister1Throttle, VisitRegister2Throttle
from common.libs.mp.wechat import make_wx_login_qrcode, show_qrcode_url, WxWebLogin
from common.utils.caches import set_wx_ticket_login_info_cache, get_wx_ticket_login_info_cache
from common.utils.pending import get_pending_result
logger = logging.getLogger(__name__)
@ -42,19 +43,37 @@ class WeChatLoginView(APIView):
def get(self, request):
ret = BaseResponse()
if Config.LOGIN.get("login_type").get('third', '').get('wxp'):
code, qr_info = make_wx_login_qrcode()
return wx_qr_code_response(ret, code, qr_info, get_real_ip_address(request))
unique_key = request.query_params.get('unique_key')
if unique_key:
cache_obj = WxLoginBindCache(unique_key)
cache_data = cache_obj.get_storage_cache()
if cache_data:
code, qr_info = cache_data
else:
code, qr_info = cache_data = make_wx_login_qrcode()
cache_obj.set_storage_cache(cache_data, qr_info.get('expire_seconds', 600))
return wx_qr_code_response(ret, code, qr_info, get_real_ip_address(request))
return Response(ret.dict)
class WeChatBindView(APIView):
authentication_classes = [ExpiringTokenAuthentication, ]
throttle_classes = [VisitRegister1Throttle, VisitRegister2Throttle]
def post(self, request):
ret = BaseResponse()
uid = request.user.uid
code, qr_info = make_wx_login_qrcode(f"web.bind.{uid}")
return wx_qr_code_response(ret, code, qr_info, get_real_ip_address(request))
unique_key = request.data.get('unique_key')
if unique_key:
cache_obj = WxLoginBindCache(unique_key)
cache_data = cache_obj.get_storage_cache()
if cache_data:
code, qr_info = cache_data
else:
code, qr_info = cache_data = make_wx_login_qrcode(f"web.bind.{uid}")
cache_obj.set_storage_cache(cache_data, qr_info.get('expire_seconds', 600))
return wx_qr_code_response(ret, code, qr_info, get_real_ip_address(request))
return Response(ret.dict)
def expect_func(result, *args, **kwargs):
@ -67,10 +86,16 @@ class WeChatLoginCheckView(APIView):
if not Config.LOGIN.get("login_type").get('third', '').get('wxp'):
return Response(ret.dict)
ticket = request.data.get("ticket")
if ticket:
status, wx_ticket_data = get_pending_result(get_wx_ticket_login_info_cache, expect_func, ticket=ticket,
locker_key=ticket)
unique_key = request.data.get("unique_key")
if ticket and unique_key:
status, result = get_pending_result(get_wx_ticket_login_info_cache, expect_func, ticket=ticket,
locker_key=ticket, unique_key=unique_key, run_func_count=1)
if status:
if result.get('err_msg'):
ret.msg = result.get('err_msg')
ret.code = 1004
return Response(ret.dict)
wx_ticket_data = result.get('data', {})
if wx_ticket_data.get('pk', -1) == -1:
ret.msg = "还未绑定用户,请通过手机或者邮箱登录账户之后进行绑定"
ret.code = 1005
@ -94,6 +119,7 @@ class WeChatLoginCheckView(APIView):
class WeChatWebLoginView(APIView):
throttle_classes = [VisitRegister1Throttle, VisitRegister2Throttle]
def get(self, request):
logger.error(request.query_params)

@ -14,10 +14,10 @@ from api.utils.modelutils import PageNumber
from api.utils.response import BaseResponse
from api.utils.serializer import PriceSerializer, OrdersSerializer
from common.base.baseutils import get_order_num, get_choices_dict
from common.base.magic import get_pending_result
from common.core.auth import ExpiringTokenAuthentication
from common.libs.pay.util import get_pay_obj_form_name, get_enable_pay_choices, get_payment_type
from common.utils.caches import update_order_status
from common.utils.pending import get_pending_result
logger = logging.getLogger(__name__)
@ -134,12 +134,18 @@ class OrderSyncView(APIView):
def post(self, request):
res = BaseResponse()
order_number = request.data.get("order_number", None)
unique_key = request.data.get("unique_key", None)
if order_number:
status, result = get_pending_result(get_order_obj, expect_func, order_number=order_number,
locker_key=order_number, user_obj=request.user)
status, result = get_pending_result(get_order_obj, expect_func, order_number=order_number, run_func_count=1,
locker_key=order_number, unique_key=unique_key, user_obj=request.user)
if not status and result:
res.code = 1001
res.msg = result.get_status_display()
if status and result.get('err_msg'):
res.code = 1004
if result.get('err_msg'):
res.msg = result.get('err_msg')
else:
res.msg = result.get('data', {}).get_status_display()
return Response(res.dict)

@ -63,21 +63,3 @@ def call_function_try_attempts(try_attempts=3, sleep_time=2, failed_callback=Non
return wrapper
return decorator
def get_pending_result(func, expect_func, loop_count=10, sleep_time=3, *args, **kwargs):
try:
with cache.lock("%s_%s" % ('get_pending_result', kwargs.get('locker_key')), timeout=loop_count * sleep_time):
count = 1
del kwargs['locker_key']
while True:
result = func(*args, **kwargs)
if expect_func(result, *args, **kwargs):
return True, result
time.sleep(sleep_time)
if loop_count < count:
return False, result
count += 1
except Exception as e:
logger.warning(f'get pending result exception: {e}')
return False, result

@ -215,3 +215,15 @@ class TaskStateCache(RedisCacheBase):
def __init__(self, app_pk, task_id):
self.cache_key = f"{CACHE_KEY_TEMPLATE.get('task_state_key')}_{app_pk}_{task_id}"
super().__init__(self.cache_key)
class PendingStateCache(RedisCacheBase):
def __init__(self, locker_key):
self.cache_key = f"{CACHE_KEY_TEMPLATE.get('pending_state_key')}_{locker_key}"
super().__init__(self.cache_key)
class WxLoginBindCache(RedisCacheBase):
def __init__(self, unique_key):
self.cache_key = f"{CACHE_KEY_TEMPLATE.get('wx_login_bind_key')}_{unique_key}"
super().__init__(self.cache_key)

@ -0,0 +1,81 @@
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# project: 3月
# author: NinEveN
# date: 2022/3/15
import logging
import time
from django.core.cache import cache
from common.cache.storage import PendingStateCache
logger = logging.getLogger(__name__)
def set_pending_cache(unique_key, cache_data, cache_obj, timeout):
if unique_key in cache_data:
cache_data.remove(unique_key)
logger.warning(f'return unique_key:{unique_key} cache_data: {cache_data} ')
cache_obj.set_storage_cache(cache_data, timeout)
def get_pending_result(func, expect_func, loop_count=10, sleep_time=3, unique_key='default_key',
run_func_count=2, pop_first=True, *args, **kwargs):
"""
:param func: 将要运行的函数对象
:param expect_func: 期待的运行结果函数
:param loop_count: 执行次数
:param sleep_time: 执行循环等待时间
:param unique_key: 11请求唯一标识用与函数并发请求
:param run_func_count: 11函数并发请求数超过该次数会自动移除多余等待
:param pop_first: 11超出是否自动移除最老的请求True: 移除最老的 False: 移除最新的
:param args:
:param kwargs:
:return:
"""
locker_key = kwargs.pop('locker_key')
cache_timeout = loop_count * sleep_time * (run_func_count + 1)
cache_obj = PendingStateCache(locker_key)
cache_data = cache_obj.get_storage_cache()
is_pop = False
if cache_data and isinstance(cache_data, list):
if unique_key not in cache_data:
cache_data.append(unique_key)
if len(cache_data) > run_func_count and len(cache_data) > 0:
is_pop = True
if pop_first:
cache_data.pop(0)
else:
cache_data.pop()
else:
cache_data = [unique_key]
cache_obj.set_storage_cache(cache_data, cache_timeout)
if not pop_first and len(cache_data) == run_func_count and is_pop:
logger.warning(f'unique_key:{unique_key} cache_data: {cache_data} ')
return True, {'err_msg': '请求重复,请稍后再试'}
try:
with cache.lock(f"get_pending_result_{locker_key}", timeout=loop_count * sleep_time):
count = 1
while True:
cache_data = cache_obj.get_storage_cache()
logger.warning(f'unique_key:{unique_key} cache_data: {cache_data} ')
if cache_data and isinstance(cache_data, list) and unique_key in cache_data:
result = func(*args, **kwargs)
if expect_func(result, *args, **kwargs):
set_pending_cache(unique_key, cache_data, cache_obj, cache_timeout)
return True, {'data': result}
time.sleep(sleep_time)
if loop_count < count:
set_pending_cache(unique_key, cache_data, cache_obj, cache_timeout)
return False, {'err_msg': '请求超时'}
count += 1
else:
set_pending_cache(unique_key, cache_data, cache_obj, cache_timeout)
return True, {'err_msg': '请求重复,请稍后再试'}
except Exception as e:
logger.warning(f'get pending result exception: {e}')
set_pending_cache(unique_key, cache_data, cache_obj, cache_timeout)
return False, {'err_msg': '内部错误'}

@ -73,12 +73,12 @@ class THIRDLOGINCONF(object):
wx_official = {
'name': 'wx_official',
'auth': {
'app_id': 'we6',
'app_secret': '5bfb678',
'token': 'f0ae1b879b8',
'encoding_aes_key': '7b9URovp83gG',
'app_id': 'wx390e5985fd3699e6',
'app_secret': '5b1796722172a902d019f43e4a2fb678',
'token': 'f0ae76c1559cacf72a99db6a41b879b8',
'encoding_aes_key': '7b9U60tCXk3f4yOFideTN5ithh4Y8X3Xl9pRovp83gG',
},
'active': False
'active': True
}
@ -119,8 +119,8 @@ class AUTHCONF(object):
}
REPORT = {
"enable": True,
"captcha": True, # 是否开启注册字母验证码
"geetest": False, # 是否开启geetest验证,如要开启请先配置geetest
"captcha": False, # 是否开启注册字母验证码
"geetest": True, # 是否开启geetest验证,如要开启请先配置geetest
"report_type": {
'sms': False, # 短信举报
'email': True, # 邮件举报

@ -261,6 +261,8 @@ CORS_ALLOW_HEADERS = (
CACHE_KEY_TEMPLATE = {
'sysconfig_key': 'sysconfig',
'task_state_key': 'task_state',
'pending_state_key': 'pending_state',
'wx_login_bind_key': 'wx_login_bind',
'user_can_download_key': 'user_can_download',
'download_times_key': 'app_download_times',
'make_token_key': 'make_token',

@ -16,11 +16,11 @@ from api.utils.modelutils import get_redirect_server_domain, add_remote_info_fro
get_app_download_uri
from api.utils.response import BaseResponse
from common.base.baseutils import get_real_ip_address, make_random_uuid, get_server_domain_from_request
from common.base.magic import get_pending_result
from common.cache.storage import TaskStateCache
from common.core.sysconfig import Config
from common.core.throttle import ReceiveUdidThrottle1, ReceiveUdidThrottle2
from common.utils.caches import check_app_permission
from common.utils.pending import get_pending_result
from fir_ser.celery import app
from xsign.tasks import run_sign_task
from xsign.utils.supersignutils import udid_bytes_to_dict, make_sign_udid_mobile_config
@ -108,12 +108,14 @@ class TaskView(APIView):
def get(self, request, short):
res = BaseResponse()
task_id = request.query_params.get('task_id', None)
if task_id:
unique_key = request.query_params.get('unique_key', task_id)
if task_id and unique_key:
app_info = Apps.objects.filter(short=short).first()
if app_info:
status, result = get_pending_result(task_func, expect_func, task_id=task_id,
locker_key=task_id, app_info=app_info)
if status:
locker_key=task_id, app_info=app_info, unique_key=unique_key)
if status and result.get('data'):
result = result.get('data')
if result.successful():
res.msg = result.get(propagate=False)
return Response(res.dict)

Loading…
Cancel
Save