def upload_local_video(accessKeyId, accessKeySecret, file_path, file_title="", file_tags="", file_desc="", storageLocation=None): try: uploader = vodUploader(accessKeyId, accessKeySecret) uploadVideoRequest = UploadVideoRequest(file_path, file_title) uploadVideoRequest.setTags(file_tags) uploadVideoRequest.setDescription(file_desc) if storageLocation: uploadVideoRequest.setStorageLocation(storageLocation) # videoId = uploader.uploadLocalVideo(uploadVideoRequest) upload_info = uploader.uploadLocalVideo(uploadVideoRequest) # pprint(vars(uploadVideoRequest)) upload_address = upload_info['UploadAddress'] video_url = "{}/{}".format(video_host, upload_address['FileName']) # print(uploadInfo['UploadAddress'], uploadInfo['MediaId']) # print(video_url) return { 'video_url': video_url, 'media_id': upload_info['MediaId'], 'from_file': file_path, 'upload_info': upload_info } # print("file: %s, videoId: %s " % (uploadVideoRequest.filePath, uploadInfo['MediaId'])) except AliyunVodException as e: print("上传视频失败了———— {}".format(e)) raise response_code.ThirdERR(errmsg="上传视频失败了———— {}".format(e)) logger.error("filePath: {} exception: {}".format(file_path, e))
def get_access_token(self, code): """向QQ服务器获取access token""" url = "https://graph.qq.com/oauth2.0/token?" params = { "grant_type": "authorization_code", "code": code, "client_id": self.client_id, "redirect_uri": self.redirect_uri, "client_secret": self.client_secret } url += urllib.parse.urlencode(params) # 向QQ服务器发送请求 access_token # access_token=FE04************************CCE2&expires_in=7776000&refresh_token=88E4************************BE14 try: resp = urlopen(url) resp_byte = resp.read() # 为 byte 类型 resp_str = resp_byte.decode() # 转化为 str 类型 resp_dict = urllib.parse.parse_qs(resp_str) except Exception as e: current_app.logger.error('获取access_token异常: %s' % e) raise response_code.ThirdERR(errmsg="{}".format(e)) else: if not resp_dict: raise response_code.ParamERR(errmsg='code 失效') # access_token取出是一个列表 access_token_list = resp_dict.get('access_token') access_token = access_token_list[0] return access_token
def send_request_to_third(url): try: resp = urlopen(url) resp_byte = resp.read() # 为 byte 类型 resp_str = resp_byte.decode() # 转化为 str 类型 resp_dict = json.loads(resp_str) except Exception as e: current_app.logger.error('获取access_token异常: %s' % e) raise response_code.ThirdERR(errmsg="{}".format(e)) return resp_dict
def get_unionid(access_token): url = 'https://graph.qq.com/oauth2.0/me?access_token={}&unionid=1'.format( access_token) try: resp = urlopen(url) resp_byte = resp.read() resp_json = json.loads(resp_byte.decode()[10:-4]) unionid = resp_json.get('unionid') openid = resp_json.get('openid') except Exception as e: raise response_code.ThirdERR(errmsg="{}".format(e)) return unionid, openid
def get_user_info(access_token, openid): """ 获取用户信息 """ url = 'https://api.weixin.qq.com/sns/userinfo?access_token={}&openid={}'.format( access_token, openid) resp_dict = send_request_to_third(url) if 'errmsg' in resp_dict: raise response_code.ThirdERR(errmsg=resp_dict.get('errmsg', '')) else: nickname = resp_dict.get('nickname', '') headimgurl = resp_dict.get('headimgurl', '') unionid = resp_dict.get('unionid', '') gender = resp_dict.get('gender', "男") return nickname, headimgurl, unionid, gender
def check_save_user_token(access_token): """ 从flask生成的access_token取出token :param access_token: :return: """ serializer = TJSSerializer(secret_key=config.SECRET_KEY, expires_in=constants.SAVE_USER_TOKEN_EXPIRES) try: data = serializer.loads(access_token) except Exception as e: raise response_code.ThirdERR(errmsg='{}'.format(e)) else: return data['unionid'], data['type']
def get_access_token(self, code): """ 获取 access_token """ url = "https://api.weixin.qq.com/sns/oauth2/access_token?" params = { "appid": self.appid, "secret": self.secret_key, "code": code, "grant_type": "authorization_code" } url += urllib.parse.urlencode(params) resp_dict = send_request_to_third(url) if 'errmsg' in resp_dict: raise response_code.ThirdERR(errmsg=resp_dict.get('errmsg', '')) else: access_token = resp_dict.get('access_token', '') refresh_token = resp_dict.get('refresh_token', '') openid = resp_dict.get('openid', '') unionid = resp_dict.get('unionid', '') return access_token, openid, unionid, refresh_token
def get_openid(access_token): url = 'https://graph.qq.com/oauth2.0/me?access_token=' + access_token # 向QQ服务器发送请求 openid try: resp = urlopen(url) resp_byte = resp.read() resp_str = resp_byte.decode() # openid = callback( {"client_id":"YOUR_APPID","openid":"YOUR_OPENID"} ); # 字符串切割 resp_date = resp_str[10:-4] resp_dict = json.loads(resp_date) except Exception as e: raise response_code.ThirdERR(errmsg="{}".format(e)) else: openid = resp_dict.get('openid') return openid
def get_access_token(self, code): """向weibo服务器获取access token""" url = "https://api.weibo.com/oauth2/access_token?" params = { "client_id": self.appid, "client_secret": self.secret_key, "grant_type": "authorization_code", "redirect_uri": self.redirect_uri, "code": code } url += urllib.parse.urlencode(params) try: resp = requests.post(url).content.decode() resp_dict = json.loads(resp) except Exception as e: current_app.logger.error('获取access_token异常: %s' % e) raise response_code.ThirdERR(errmsg="{}".format(e)) else: if not resp_dict or resp_dict.get("error"): raise response_code.ParamERR(errmsg='code 失效 {}'.format( resp_dict.get("error_description"))) access_token = resp_dict.get('access_token') return access_token
def func_third_bind_mobile(self): """ 第一次登录绑定账号 :return: """ access_token = self.extra_data.get('access_token', "") mobile = self.extra_data.get('mobile', "") code = self.extra_data.get('code', "") refresh_token = None if access_token == "" or mobile == "" or code == "": raise response_code.ParamERR( '[access_token, mobile, code] can not be empty!') elif not mobile_re.match('{}'.format(mobile)): raise response_code.ParamERR(errmsg="Wrong phone number format!") sms_verify(mobile, code) now_time = time.time() unionid, third_type = check_save_user_token(access_token) if unionid is None: raise response_code.ReqERR(errmsg="access_token is wrong!") else: try: user_info = mongo.db.user.find_one( {"mobile": '{}'.format(mobile)}, { 'name': 1, 'headshot': 1 }) except Exception as e: raise response_code.DatabaseERR(errmsg="{}".format(e)) if user_info: try: _id = user_info.pop('_id') mongo.db.user.update_one({"mobile": '{}'.format(mobile)}, { '$set': { '{}_unionid'.format(third_type): unionid, "login_time": now_time } }) except Exception as e: raise response_code.DatabaseERR(errmsg="{}".format(e)) else: _id = get_user_id("id") try: name = redis_conn.get("unionid_name_%s" % unionid) headshot = redis_conn.get("unionid_photo_url_%s" % unionid) gender = redis_conn.get("unionid_gender_%s" % unionid) refresh_token = redis_conn.get("unionid_refresh_token_%s" % unionid) mongo.db.user.insert_one({ "gender": gender, "birthday": str(datetime.date.today()), "name": name, "mobile": '{}'.format(mobile), "_id": _id, '{}_unionid'.format(third_type): unionid, "headshot": headshot, "create_time": now_time, "login_time": now_time, "background": self.background_path, "introduction": self.introduction }) except Exception as error: current_app.logger.error(error) raise response_code.ThirdERR(errmsg="{}".format(error)) user_info = {'name': name, 'headshot': headshot} response = make_response(set_resjson(res_array=[user_info])) response.headers["Authorization"] = encode_auth_token( _id, refresh_token) return response