def post(self): target_name = request.json.get("target_name") target_type = request.json.get("target_type") ''' TODO 用户输入为空,重定向 ''' # if not all[target_name]: # return jsonify(re_code=RET.NODATA, msg="用户没有输入") user_id = g.user_id #限制用户在一分钟内使用三次搜索功能 visit_limit = limit_user_visit(user_id) if visit_limit == True: if target_type == "image": save_search_history_to_redis(user_id, target_name) result = crawl.get_result_url(target_name, target_type) count = [i for i in range(len(result))] json_result = json.dumps(dict(zip(count, result))) if result: current_app.info("user %s get search info s success, result is %s", user_id, target_name) return jsonify(re_code = RET.OK, result_url = json_result) else: current_app.error("user %s get search info is failed, target_name is %s", user_id, target_name) return jsonify(re_code = RET.NODATA, msg = "爬虫没有获取结果") elif target_type == "text": save_search_history_to_redis(user_id, target_name) result = crawl.get_result_url(target_name, target_type) json_result = json.dumps(result) if json_result: current_app.info("user %s get search info s success, result is %s", user_id, target_name) return jsonify(re_code = RET.OK, text_result = json_result) else: current_app.error("user %s get search info is failed, target_name is %s", user_id, target_name) return jsonify(re_code = RET.NODATA, msg = "爬虫没有获取结果") else: return jsonify(msg = "一分钟内最多访问三次")
def set_user_auth(): """保存实名认证信息""" user_id = g.user_id # 获取参数 req_data = request.get_json() if not req_data: return jsonify(errno=RET.PARAMERR, errmsg="参数错误") real_name = req_data.get("real_name") id_card = req_data.get("id_card") if not all([real_name, id_card]): return jsonify(errno=RET.PARAMERR, errmsg="参数错误") try: User.query.filter_by(id=user_id, real_name=None, id_card=None).update({ "real_name": real_name, "id_card": id_card }) db.session.commit() except Exception as ex: current_app.error(ex) db.session.rollback() return jsonify(errno=RET.DBERR, errmsg="保存用户实名信息失败") return jsonify(errno=RET.OK, errmsg="OK")
def authentication_oauth_post(): is_webview = request.form.get('webview') app.reset_authentication() redirect_uri = request.form.get('redirect_uri') if not redirect_uri: return app.error('Please provide redirect_url', HTTPStatus.BAD_REQUEST) try: access, refresh = AuthenticationManager.parse_redirect_url(redirect_uri) app.authentication_mgr.access_token = access app.authentication_mgr.refresh_token = refresh app.authentication_mgr.authenticate(do_refresh=False) app.authentication_mgr.dump(app.token_file) except Exception as e: if is_webview: return render_template('auth_result.html', title='Login fail', result='Login failed', message='Error message: {0}'.format(str(e)), link_path='/auth/login', link_title='Try again') else: return app.error('Login failed, error: {0}'.format(str(e))) if is_webview: return render_template('auth_result.html', title='Login success', result='Login succeeded', message='Welcome {}!'.format(app.logged_in_gamertag), link_path='/auth/logout', link_title='Logout') else: return app.success(message='Login success', gamertag=app.logged_in_gamertag)
def authentication_login_post(): is_webview = request.form.get('webview') email_address = request.form.get('email') password = request.form.get('password') if app.authentication_mgr.authenticated: return app.error( 'An account is already signed in.. please logout first', HTTPStatus.BAD_REQUEST) elif not email_address or not password: return app.error('No email or password parameter provided', HTTPStatus.BAD_REQUEST) app.authentication_mgr.email_address = email_address app.authentication_mgr.password = password try: app.authentication_mgr.authenticate() app.authentication_mgr.dump(app.token_file) except AuthenticationException as e: if is_webview: return render_template('auth_result.html', title='Login fail', result='Login failed', message='Error: {0}!'.format(str(e)), link_path='/auth/login', link_title='Try again') else: return app.error('Login failed! Error: {0}'.format(str(e)), two_factor_required=False) except TwoFactorAuthRequired: if is_webview: return render_template( 'auth_result.html', title='Login fail', result='Login failed, 2FA required', message= 'Please click the following link to authenticate via OAUTH', link_path='/auth/oauth', link_title='Login via OAUTH') else: return app.error('Login failed, 2FA required!', two_factor_required=True) if is_webview: return render_template('auth_result.html', title='Login success', result='Login succeeded', message='Welcome {}!'.format( app.logged_in_gamertag), link_path='/auth/logout', link_title='Logout') else: return app.success(message='Login success', gamertag=app.logged_in_gamertag)
def download_title_info(client, title_id): try: resp = client.titlehub.get_title_info(title_id, 'image').json() return jsonify(resp['titles'][0]) except KeyError: return app.error('Cannot find titles-node json response') except IndexError: return app.error('No info for requested title not found') except Exception as e: return app.error('Download of titleinfo failed, error: {0}'.format(e))
def authentication_store_on_disk(): if not app.authentication_mgr.authenticated: return app.error('Sorry, no valid authentication for saving was found', HTTPStatus.BAD_REQUEST) try: app.authentication_mgr.dump(app.token_file) except Exception as e: return app.error('Failed to save tokens to \'{0}\'. Error: {1}'.format(app.token_file, str(e))) return app.success()
def teardown(exception=None): # print("before tear down sessiion:{0}".format(str(db.session))) if exception: current_app.logger.error("teardown with error, error message: {0}".format(exception)) current_app.error("teardown_request - rolling back active database sessions.") db.session.rollback() db.session.close() db.session.remove()
def decorated_function(*args, **kwargs): liveid = kwargs.get('liveid') console = app.console_cache.get(liveid) if not console: return app.error('Console {0} is not alive'.format(liveid), HTTPStatus.FORBIDDEN) elif not console.connected: return app.error('Console {0} is not connected'.format(liveid), HTTPStatus.FORBIDDEN) del kwargs['liveid'] kwargs['console'] = console return f(*args, **kwargs)
def force_connect(console): try: userhash = '' xtoken = '' if app.authentication_mgr.authenticated and not request.args.get('anonymous'): userhash = app.authentication_mgr.userinfo.userhash xtoken = app.authentication_mgr.xsts_token.jwt state = console.connect(userhash, xtoken) except Exception as e: return app.error(str(e)) if state != enum.ConnectionState.Connected: return app.error('Connection failed', connection_state=state.name) return app.success(connection_state=state.name)
def decorated_function(*args, **kwargs): if not app.authentication_mgr.authenticated: return app.error('Not authenticated for Xbox Live', HTTPStatus.UNAUTHORIZED) kwargs['client'] = app.xbl_client return f(*args, **kwargs)
def authentication_load_from_disk(): try: app.authentication_mgr.load(app.token_file) except FileNotFoundError as e: return app.error('Failed to load tokens from \'{0}\'. Error: {1}'.format(e.filename, e.strerror), HTTPStatus.NOT_FOUND) return app.success()
def media_command(console, command): cmd = console.media_commands.get(command) if not cmd: return app.error('Invalid command passed, command: {0}'.format(command), HTTPStatus.BAD_REQUEST) console.send_media_command(cmd) return app.success()
def input_send_button(console, button): btn = console.input_keys.get(button) if not btn: return app.error('Invalid button passed, button: {0}'.format(button), HTTPStatus.BAD_REQUEST) console.send_gamepad_button(btn) return app.success()
def infrared_available_keys(console, device_id): stump_config = console.stump_config for device_config in stump_config.params: if device_config.device_id != device_id: continue button_links = {} for button in device_config.buttons: button_links[button] = { 'url': '/device/{0}/ir/{1}/{2}'.format(console.liveid, device_config.device_id, button), 'value': device_config.buttons[button] } return app.success(device_type=device_config.device_type, device_brand=device_config.device_brand, device_model=device_config.device_model, device_name=device_config.device_name, device_id=device_config.device_id, buttons=button_links) return app.error('Device Id \'{0}\' not found'.format(device_id), HTTPStatus.BAD_REQUEST)
def authentication_refresh(): try: app.authentication_mgr.authenticate(do_refresh=True) except Exception as e: return app.error(str(e)) return app.success()
def download_title_history(client): try: max_items = request.args.get('max_items') or 5 resp = client.titlehub.get_title_history(app.xbl_client.xuid, max_items=max_items).json() return jsonify(resp) except Exception as e: return app.error( 'Download of titlehistory failed, error: {0}'.format(e))
def store_db_table(name): status = {} account = Account.query.filter_by(name=name).first_or_404() status['transactions_before'] = account.total_transactions_count dbtransactions = [ dbtransaction.to_dict() for dbtransaction in account.dbtransactions ] status['dbtransactions_to_be_added'] = len(dbtransactions) dbcnt = 0 for i in range(len(dbtransactions)): new_transaction = Transaction( date=dbtransactions[i]['date'].date(), amount=dbtransactions[i]['amount'], type=dbtransactions[i]['type'], description=dbtransactions[i]['description'] + " " + dbtransactions[i]['beneficiary'], category=" ", subcategory=" ", tag=" ", status=True, accountid=account.id, payee="not provided") try: new_transaction.save() DbTransaction.query.get(dbtransactions[i]['tid']).delete() dbcnt = dbcnt + 1 status['dbtransactions_added'] = dbcnt status['transactions_after'] = account.total_transactions_count except: current_app.error("Error occured while storing DB transaction") return render_template('upload.html', account=account, status=report) report = "Added %d DB Transactions to %d previous Transactions!" % ( status['dbtransactions_added'], status['transactions_before']) return render_template('upload.html', account=account, status=report)
def registerUser(): try: _registerUser = request.get_json(force=True) _username = _registerUser['username'] _password = _registerUser['password'] _email = _registerUser['email'] _newId = mongo.db.UserInfo.count() + 1 # First check if user already registered _user = mongo.db.UserInfo.find_one({'username': _username}) ## current_app.logger.debug(_user) if not _user: current_app.logger.info( "Register User info not exist in Database, ready to insert") _registerUser2DB = { "username": _username, "password": _password, "email": _email, "userId": _newId } # check if insertion succeed _id = mongo.db.UserInfo.insert_one(_registerUser2DB) if not _id: current_app.logger.info( "New user registration failed, return fail status code 203" ) return Response(status=203, mimetype="application/json") else: current_app.logger.info( "New user registration succeed, return status code 200") return Response(status=200, mimetype="application/json") else: current_app.logger.info("Register User already exist in database!") return Response(status=203, mimetype="application/json") except Exception as e: current_app.error(e) return Response(status=203, mimetype="application/json")
def login(): """ login api need mobile and passworld """ # get parmas and detemine if there is a value data = request.json mobile = data.get('mobile') password = data.get('password') # verify params if not all([mobile, password]): return jsonify(error=RET.PARAMERR, errmsg='参数不全') # find user from database of user table try: user = User.query.filter_by(mobile=mobile).first() except Exception as e: current_app.logger.info(e) return jsonify(error=RET.DATAERR, errmsg='用户查询错误') # if not have user if not user: return jsonify(error=RET.DATAEXIST, errmsg='用户不存在') # verify password if not user.check_passowrd(password): return jsonify(error=RET.PWDERR, errmsg='用户名或密码错误') # login success save user infomations in session session['user_id'] = user.id session['nick_name'] = user.nick_name session['mobile'] = user.mobile # recording last login time user.last_login = datetime.now() # submit user infomations update try: db.session.commit() except Exception as e: current_app.error(e) return jsonify(error=RET.DATAERR, errmsg='用户数据更新错误') return jsonify(error=RET.OK, errmsg='ok')
def validate(self, record, identifier=None, client=None, provider=None, **kwargs): """Validate the attributes of the identifier. :returns: A tuple (success, errors). The first specifies if the validation was passed successfully. The second one is an array of error messages. """ if client: current_app.error("Configuration error: client attribute not " f"supported for provider {self.name}") raise # configuration error success, errors = super().validate(record, identifier, provider, client, **kwargs) return (True, []) if not errors else (False, errors)
def news_review(): """返回待审核新闻列表""" page = request.args.get("p", 1) keywords = request.args.get("keywords", "") try: page = int(page) except Exception as e: current_app.logger.error(e) page = 1 news_list = list() current_page = 1 total_page = 1 try: filters = [News.status != 0] # 如果有关键词 if keywords: # 添加关键字检索选项 filters.append(News.title.contains(keywords)) paginate = News.query.filter(*filters)\ .order_by(News.create_time.desc())\ .paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False) news_list = paginate.items current_page = paginate.page total_page = paginate.pages except Exception as e: current_app.error(e) news_dict_list = list() for news in news_list: news_dict_list.append(news.to_review_dict()) data = { "total_page": total_page, "current_page": current_page, "news_list": news_dict_list } return render_template("admin/news_review.html", data=data)
def gamedvr_record(console): """ Default to record last 60 seconds Adjust with start/end query parameter (delta time in seconds) """ try: start_delta = request.args.get('start', -60) end_delta = request.args.get('end', 0) console.dvr_record(int(start_delta), int(end_delta)) except Exception as e: return app.error('GameDVR failed, error: {0}'.format(e)) return app.success()
def is_available(cls, pid, view_code, raise_exception=False): """Get availability for document.""" from ..holdings.api import Holding holding_pids = [] if view_code != current_app.config.get( 'RERO_ILS_SEARCH_GLOBAL_VIEW_CODE'): view_id = Organisation.get_record_by_viewcode(view_code)['pid'] holding_pids = Holding.get_holdings_pid_by_document_pid_by_org( pid, view_id) else: holding_pids = Holding.get_holdings_pid_by_document_pid(pid) for holding_pid in holding_pids: holding = Holding.get_record_by_pid(holding_pid) if holding: if holding.available: return True else: msg = f'No holding: {holding_pid} in DB ' \ f'for document: {pid}' current_app.error(msg) if raise_exception: raise ValueError(msg) return False
def wrapper(*args, **kwargs): # 1.获取用户id user_id = session.get("user_id", None) if user_id is None: return render_template("login.html") from oms.models import Users user = None # type: Users if user_id: try: user = Users.query.get(user_id) except Exception as e: current_app.error(e) return jsonify(errno=RET.DBERR, errmsg="操作失败!") # 使用全局的临时g对象存储user对象 # 只要请求还未结束,就能获取到g对象中的内容 g.user = user # 2.原有视图函数功能再次调用执行 result = view_func(*args, **kwargs) return result
def poweroff(console): if not console.power_off(): return app.error("Failed to power off") else: return app.success()
def create_schema(self, schema_file): def getXSVal(element_name): # replace prefix namespace if "}" in element_name: for k, nsp in schema_data.namespaces.items(): if nsp in element_name: if k == "": k = self.rootname.split( ":")[-1] if ":" in self.rootname else self.rootname return element_name.replace("{" + nsp + "}", k + ":") return element_name def get_namespace(namespaces): pix = tg = '' for k, nsp in namespaces.items(): if k == '': tg = nsp break for k, nsp in namespaces.items(): if tg == nsp and k != '': pix = k break return pix, tg def get_element_type(type): typd = OrderedDict() if isinstance(type, XsdAtomicRestriction): rstr = typd['restriction'] = OrderedDict() for va in type.validators: if isinstance(va, XsdEnumerationFacet): rstr.update(OrderedDict(enumeration=va.enumeration)) if isinstance(va, XsdSingleFacet): sf = OrderedDict() vn = va.elem.tag.split( '}')[-1] if "}" in va.elem.tag else va.elem.tag sf[vn] = va.value rstr.update(sf) if isinstance(type.patterns, XsdPatternsFacet): plst = [] for pat in type.patterns.patterns: plst.append(pat.pattern) rstr.update(OrderedDict(patterns=plst)) elif isinstance(type, XsdAtomicBuiltin): pass elif isinstance(type, XsdUnion): for mt in type.member_types: typd.update(get_element_type(mt)) elif isinstance(type, XsdGroup): pass else: atrlst = [] if hasattr(type, 'attributes'): for atrb in type.attributes._attribute_group.values(): attrd = OrderedDict( name=getXSVal( atrb.name), ref=atrb.ref, use=atrb.use) if 'lang' not in atrb.name: attrd.update(get_element_type(atrb.type)) atrlst.append(attrd) if len(atrlst): typd['attributes'] = atrlst if hasattr(type, 'content_type'): typd.update(get_element_type(type.content_type)) pass return typd def get_elements(element): chdsm = OrderedDict() for chd in element.iterchildren(): if not isinstance(chd, XsdAnyElement): ctp = OrderedDict() chn = getXSVal(chd.name) ctp["type"] = OrderedDict( minOccurs=chd.min_occurs, maxOccurs=chd.max_occurs if chd.max_occurs else 'unbounded') ctp["type"].update(get_element_type(chd.type)) chdsm[chn] = ctp chdsm[chn].update(get_elements(chd)) return chdsm # get elements as below try: schema_file = open(schema_file, encoding='utf-8') schema_data = xmlschema.XMLSchema(schema_file) except Exception as ex: current_app.error(ex) abort( 400, "Error creating Schema: Can not open xsd file. Please check it!") # namespace nsp, tagns = get_namespace(schema_data.namespaces) # create the xsd json schema schema = OrderedDict() try: # get elements by root name path = self.rootname + "/*" if ':' in self.rootname \ else '{%s}%s/*' % (tagns, nsp if nsp else self.rootname) elements = schema_data.findall(path) elements = schema_data.findall( '*/*') if len(elements) < 1 else elements except Exception: abort(400, "Error creating Schema: Can not find element") else: if len(elements) > 0: for ems in elements: ename = getXSVal(ems.name) tp = OrderedDict() tp["type"] = OrderedDict( minOccurs=ems.min_occurs, maxOccurs=ems.max_occurs if ems.max_occurs else 'unbounded') tp["type"].update(get_element_type(ems.type)) schema[ename] = tp for pae in schema_data.parent_map: if ems.name == pae.name: schema[ename].update(get_elements(pae)) else: abort(400, "Error creating Schema: No xsd element") return schema, schema_data.namespaces
def news_post(lang='is'): if '.com' in request.url: lang = 'en' form = PostForm() form.category.choices = [(0, 'Almenn frétt')] form.created.data = datetime.utcnow() categories = Category.get_all_active() if lang == 'is': lang = None active = Category.get_all_active() form.category.choices.extend([(n + 1, i.name) for n, i in enumerate(active)]) if form.validate_on_submit(): name = form.category.choices[int(form.category.data)][1] category = Category.get_by_name(name) post = Post(title=form.title.data, body=remove_html_tags(form.post.data), body_html=form.post.data, language=lang or 'is', timestamp=form.created.data, author=current_user, category=category) db.session.add(post) db.session.commit() flash("Fréttin hefur verið vistuð!") if form.facebook.data: try: fn = os.path.basename(get_all_imgs(form.post.data)[0]) fn = current_app.config['UPLOADS_DEFAULT_DEST'] + '/imgs/' + fn except IndexError: fn = url_for('static', filename='imgs/facebook.png') if not os.path.isfile(fn): fn = url_for('static', filename='imgs/facebook.png') else: fn = imgs.url(os.path.basename(fn)) session['link'] = url_for('aflafrettir.post', title=slugify(post.title), pid=post.id, _external=True) session['body'] = form.facebook.data session['picture'] = fn session['name'] = form.title.data session['caption'] = truncate(form.post.data) current_app.logger.debug('Preparing data for Facebook') current_app.logger.debug(session) if current_user.fb_token: return redirect(url_for('admin.post_to_fb')) else: current_app.error("Need to get authentication") return redirect(url_for('admin.news_index', lang=lang)) return render_template('admin/post.html', categories=categories, form=form, lang=lang)
def download_pins(client): try: resp = client.lists.get_items(app.xbl_client.xuid, {}).json() return jsonify(resp) except Exception as e: return app.error('Download of pins failed, error: {0}'.format(e))
try: secret = client.get_secret_value(SecretId=secret_name) except botocore.exceptions.ClientError as err: if err.response["Error"]["Code"] in ( "DecryptionFailureException", "InternalServiceErrorException", "InvalidParameterException", "InvalidRequestException", "ResourceNotFoundException"): current_app.logger.error(err.response["Error"]["Code"]) else: return secret.get("SecretString", b64decode(secret["SecretBinary"])) except botocore.exceptions.ParamValidationError as error: current_app.error(f"invalid parameter: {error}") def Main(environ, start_response): password = get_secret("mysql-password") username = get_secret("mysql-username") instance = Eve(logger=Logger(), settings=Settings(), validator=ValidatorSQL, data=SQL) instance.on_post_GET += log_get instance.register_blueprint(get_swagger_blueprint()) healthcheck = EveHealthCheck(instance, "/healthcheck") database = instance.data.driver Base.metadata.bind = database.engine database.Model = Base database.create_all()
def infrared_send(console, device_id, button): if not console.send_stump_key(device_id, button): return app.error('Failed to send button') return app.success(sent_key=button, device_id=device_id)