def add_carouse(): """ 增加轮播图 :arg {"type":0, "imgId":1,"status":1,"content":"", "url":"http://www.google.com/", "token": "zwoqgqod-c392-ingy-6cyl-stvk7nadyrpe"} :arg {"type":1, "imgId":1,"status":1,"content":"123", "url":"","token": "zwoqgqod-c392-ingy-6cyl-stvk7nadyrpe"} :return: json """ carouse_info = request.get_json() url = carouse_info.get("url") type = carouse_info.get("type") img_id = carouse_info.get("imgId") status = carouse_info.get("status") content = carouse_info.get("content") create_date = get_current_time() # 参数校验,如果type为0,url不能为空;如果如果为1,content不能为空 if type != None and type == 0: paras = [type, img_id, status, url] else: paras = [type, img_id, status, content] if not _admin_parameters_filter(paras): return json(get_json(code=-200, msg="操作失败,参数有误!")) # 构造sql并执行 insert_anno_sql = "INSERT into tbl_carouse " \ "values(NULL, %d, %d, %d, '%s', '%s', '%s')" % (type, img_id, status, content, url, create_date) if excute(insert_anno_sql): return json(get_json(msg="添加成功!")) return json(get_json(code=-100, msg="添加失败,请检查数据库链接!"))
def article_collect(): """ 收藏文章 :arg {"articleId":1,"token": "xx13v9wp-t4gl-gsxn-mnd6-ftnhx6gnp3r0"} :return: json """ article_info = request.get_json() article_id = article_info.get("articleId") # 参数校验 if not _parameters_filter([article_id]): return json(get_json(code=-200, msg="参数存在空值,请检查参数!")) # 检查是否已经收藏过文章 user_id = session.get("user").get("id") query_article_collect_detail = "select * from tbl_article_collect as a " \ "where a.userId=%d and a.articleId=%d and a.status=1" % (user_id, article_id) if query(query_article_collect_detail): return json(get_json(code=-100, msg="您已经收藏过此文章了!")) # 检查是否存在文章 query_article_sql = "select * from tbl_article where id=%d and status=1" % article_id if not query(query_article_sql): return json(get_json(code=-100, msg="文章不在了...!")) # 增加文章收藏记录 insert_article_collect_sql = "insert into tbl_article_collect " \ "values(NULL, %d, %d, 1, '%s', NULL )" % (user_id, article_id, get_current_time()) if excute(insert_article_collect_sql): return json(get_json(msg="收藏文章成功!")) return json(get_json(code=-100, msg="操作失败,请检查数据库链接!"))
def cancel_article_like(): """ 取消文章点赞 :arg {"articleId":1,"token": "xx13v9wp-t4gl-gsxn-mnd6-ftnhx6gnp3r0"} :return: """ article_info = request.get_json() article_id = article_info.get("articleId") # 参数校验 if not _parameters_filter([article_id]): return json(get_json(code=-200, msg="参数存在空值,请检查参数!")) # 检查是否已经赞过了 user_id = session.get("user").get("id") query_article_like_detail = "select * from tbl_article_like as a " \ "where a.userId=%d and a.articleId=%d and a.status=1" % (user_id, article_id) if not query(query_article_like_detail): return json(get_json(code=-100, msg="您还没有赞过此文章!")) # 修改状态 update_article_like_sql = "update tbl_article_like as a set " \ "a.status=0 where a.userId=%d and a.articleId=%d" % (user_id, article_id) if excute(update_article_like_sql): return json(get_json(msg="成功取消此文章的点赞!")) return json(get_json(code=-100, msg="操作失败,请检查数据库链接!"))
def update_carouse(): """ 修改轮播图 :arg {"id":1, "type":0, "imgId":1,"status":1,"content":"", "url":"http://www.google.com/","token": "zwoqgqod-c392-ingy-6cyl-stvk7nadyrpe"} :arg {"id":1, "type":1, "imgId":1,"status":1,"content":"123", "url":"","token": "zwoqgqod-c392-ingy-6cyl-stvk7nadyrpe"} :return: """ carouse_info = request.get_json() id = carouse_info.get("id") url = carouse_info.get("url") type = carouse_info.get("type") img_id = carouse_info.get("imgId") status = carouse_info.get("status") content = carouse_info.get("content") # 参数校验,如果type为0,url不能为空;如果如果为1,content不能为空 if type != None and type == 0: paras = [type, img_id, status, url] else: paras = [type, img_id, status, content] if not _admin_parameters_filter(paras): return json(get_json(code=-200, msg="操作失败,参数有误!")) # 更新轮播图信息 update_carouse_sql = "update tbl_carouse set type=%d, imgId=%d, status=%d, content='%s', url='%s' where id=%d" % \ (type, img_id, status, content, url, id) if excute(update_carouse_sql): return json(get_json()) return json(get_json(code=-100, msg="添加失败,请检查数据库链接!"))
def reply_comment(): """ 回复评论 :arg {"articleId":1, "commentId":5, "commentContent":"test","token": "xx13v9wp-t4gl-gsxn-mnd6-ftnhx6gnp3r0"} :return: json """ comments_info = request.get_json() article_id = comments_info.get("articleId") comment_id = comments_info.get("commentId") comment_content = comments_info.get("commentContent") # 参数校验 if not _parameters_filter([article_id, comment_id, comment_content]): return json(get_json(code=-200, msg="参数存在空值,请检查参数!")) # 文章下是否有此评论,这里有bug todo # 增加文章评论 user_id = session.get("user").get("id") insert_reply_comment_sql = "insert into tbl_article_comment values" \ "(NULL, %d, %d, '%s', 1, '%s', NULL, %d)" % \ (user_id, article_id, comment_content, get_current_time(), comment_id) if excute(insert_reply_comment_sql): return json(get_json()) return json(get_json(code=-100, msg="操作失败,请检查数据库链接!"))
def add_article(): """ 新增文章 :arg { "title":"title", "imgId":1,"type":2, "content":"test", "source":"123","token": "6gax71xs-z38o-8178-3a2t-6c3jjcm2cn18" } :return: json """ article_info = request.get_json() type = article_info.get("type") title = article_info.get("title") img_id = article_info.get("imgId") source = article_info.get("source") content = article_info.get("content") user_id = _get_admin_session()["adminInfo"]["id"] # 参数校验 if not _admin_parameters_filter([title, img_id, type, content, source]): return json(get_json(code=-200, msg="操作失败,参数有误!")) # 插入文章记录 insert_article_sql = "INSERT INTO tbl_article VALUES" \ "(NULL, '%s', %d, %d, '%s', '%s', 0, 0, 1, %d, '%s', NULL)" % \ (title, img_id, type, content, source, user_id, get_current_time()) if excute(insert_article_sql): return json(get_json()) return json(get_json(code=-100, msg="操作失败,请检查数据库链接!"))
def upload(): """ 公共上传资源接口 :arg file:上传文件格式;source:图片资源,详细请求数据参见uploadDemo.html :return: """ # 检验来源 file_source = request.form.get("source") if not _parameters_filter([file_source]): return json(get_json(code=-200, msg="参数存在空值,请检查参数!")) # 保存图片文件到服务器 file = request.files['file'] file_name = create_token() + "." + file.filename.split(".")[1] if _upload_files(file, file_name): # 执行插入数据库操作 insert_img_source_sql = "INSERT INTO tbl_image_sources " \ "values(NULL, '%s', 1, '%s', NULL)" % (file_name, get_current_time()) # 执行成功返回该img信息 if excute(insert_img_source_sql): query_img_sql = "select * from tbl_image_sources where path='%s'" % file_name datas = {"imgInfo": query(query_img_sql)} return json(get_json(data=datas)) return json(get_json(code=-100, msg="操作失败!"))
def add_user(): """ 新增用户 :arg {"username":"******", "password":"******", "nickname":"nickname", "token": "4cmhr7a8-t0zw-sskr-3e5i-o9sdxv48878p"} :return: json """ user_info = request.get_json() nickname = user_info.get("nickname") username = user_info.get("username") password = user_info.get("password") create_date = get_current_time() # 参数校验 if not _admin_parameters_filter([username, password, nickname]): return json(get_json(code=-200, msg="参数存在空值,请检查参数!")) # 判断用户名是否已被占用 query_user_sql = "select * from tbl_user where username='******'" % username if query(query_user_sql): return json(get_json(code=-300, msg="用户名已存在!")) # 没被占用,进行注册 user_reg_sql = "insert into tbl_user values" \ "(NULL, '%s', '%s', '%s',NULL,1,'','','',NULL,'','','','',NULL,'','%s',NULL)" \ % (username, password, nickname, create_date) print(user_reg_sql) if excute(user_reg_sql): return json(get_json(msg="新增用户成功!")) return json(get_json(code=-100, msg="新增用户失败!"))
def update_article(): """ 更新文章 :arg { "id":1, "type":1, "title":"title_test", "source":"1", "status":1, "content":"test_test", "imgId":1,"token": "75wglrvu-uiol-ifza-73c9-d9vu4e5sql0m" } :return: """ article_info = request.get_json() id = article_info.get("id") type = article_info.get("type") title = article_info.get("title") img_id = article_info.get("imgId") source = article_info.get("source") status = article_info.get("status") content = article_info.get("content") # 参数校验 if not _admin_parameters_filter( [id, status, title, type, content, source, img_id]): return json(get_json(code=-200, msg="操作失败,参数有误!")) # 更新文章 update_article_sql = "update tbl_article set " \ "title='%s', type=%d, source='%s', status=%d, content='%s', updateDate='%s', imgId='%d'" \ "where id=%d" % (title, type, source, status, content, get_current_time(), img_id, id) if excute(update_article_sql): return json(get_json(msg="更新成功!")) return json(get_json(code=-100, msg="操作失败,请检查数据库链接!"))
def request_form(): header = request.headers form = request.get_json() user = dict(name=form.get('name'), phone=form.get('phone'), email=form.get('email'), device_id=header.get('X-Device-Id'), created_at=datetime.now().strftime('%Y-%m-%d %H:%M:%S')) keys = user.keys() values = list(map(lambda k: user[k], keys)) values_str = "\'" + "\', \'".join(values) + "\'" sql = f"INSERT INTO users ({', '.join(keys)}) VALUES ({values_str})" DBFetcher().execute(sql) success = json(token=guid().hex), 200 error404 = json( code=404, message= "Проблемы сервака с кодом 404. Для проверки накидываю еще текстик" ), 404 return choice([success, success, success, error404])
def request_url_ls_services(ls=None): sql = """ SELECT id, name, image_url, type, code_in_billing FROM atom_services WHERE type LIKE '{}' ORDER BY id ASC""" array = list() standart = AtomDB().execute(sql.format('standart')) for x in range(randint(1, 5)): name = standart[x].get('name') image = standart[x].get('image_url') array.append(Service().element(name, 'standart', True, image, None)) smart_home = AtomDB().execute(sql.format('smart_home')) for x in range(len(smart_home)): name = smart_home[x].get('name') image = smart_home[x].get('image_url') billing = smart_home[x].get('code_in_billing') array.append(Service().element(name, 'smart_home', True, image, billing)) success = {"result": True, "data": array} return choice([ (json(success), 200), (json(success), 200), (error(401), 401) ]) # if randint(0, 10) != 5 else (error(9050), 500)
async def processGoogleActionRequest(request): logging.info("Received POST request from google assistant") # Check if data provided if request.json == None: return json({ 'fulfillmentText': 'We did not receive a complaint, could you repeat that?' }) some_json = request.json if some_json.get('queryResult') == None: logging.info("Empty message text") return json({ 'fulfillmentText': 'We did not receive a complaint, could you repeat that?' }) queryResult = some_json.get('queryResult') if queryResult.get('queryText') == None: logging.info("Empty message text") return json({ 'fulfillmentText': 'We did not receive a complaint, could you repeat that?' }) complaint = queryResult.get('queryText') logging.info("received: ", complaint) sr = save({'description': complaint}) return json({ 'fulfillmentText': "Thank you, your complaint " + sr + " has been recorded and is being processed" })
def update_user(id): username = request.json['username'] password = request.json['password'] name = request.json['name'] email = request.json['email'] user = Users.query.get(id) if not user: return json({'message': 'user do not exist', 'data': {}}), 404 password_hash = generate_password_hash(password) try: user.username = username user.password = password_hash user.name = name user.email = email db.session.commit() result = user_schema.dump(user) return json({'message': 'successfully updated', 'data': result}), 201 except: return json({'message': 'unable to update', 'data': {}}), 500
def user_regist(): """ 用户注册 :arg {"username":"******", "password":"******", "nickname":"nickname"} :return json """ user_info = request.get_json() nickname = user_info.get("nickname") username = user_info.get("username") password = user_info.get("password") create_date = get_current_time() # 参数校验 if not _parameters_filter([username, password, nickname]): return json(get_json(code=-200, msg="参数存在空值,请检查参数!")) # 判断用户名是否已被占用 query_user_sql = "select * from t_user where username='******'" % username if query(query_user_sql): return json(get_json(code=-300, msg="用户名已存在!")) # 没被占用,进行注册 user_reg_sql = "insert into t_user values(NULL, '%s', '%s', '%s'," \ "NULL, 1,'','','',NULL,'','','','',NULL,'','%s',NULL)" % (username, password, nickname, create_date) if excute(user_reg_sql): return json(get_json(msg="注册成功!")) return get_json(code=-100, msg="注册失败,用户名可能已经存在了!")
def get_users(): users = Users.query.all() if users: result = users_schema.dump(users) return json({'message': 'successfully fetched', 'data': result}), 201 return json({'message': 'nothing found', 'data': {}})
def get_user(id): user = Users.query.get(id) if user: result = user_schema.dump(user) return json({'message': 'successfully fetched', 'data': result}), 201 return json({'message': 'user do not exit', 'data': {}}), 500
def wrapper(*args, **kwargs): token = request.get_json().get("token") if token is not None and token != ""\ and token == session.get("admin_token"): try: return func(*args, **kwargs) except: print(traceback.print_exc()) return json(get_json(code=500, msg="内部错误,请检查参数是否正确!")) return json(get_json(code=-300, msg="权限错误,请先登录!"))
def article_detailes(): """ 查询文章详情和评论 :arg: {"articleId":1} :return: """ article_info = request.get_json() article_id = article_info.get("id") # id为空不允许 if not _parameters_filter([article_id]): return json(get_json(code=-200, msg="参数存在空值,请检查参数!")) # -1:未登录用户 user = session.get("user") if user: user_id = user.get("id") else: user_id = -1 # 首先默认请求此接口为浏览了该文章 try: # 增加浏览数量,如果没有浏览,则增加一条浏览数据,否则修改浏览时间 query_article_sql = "select * from tbl_article_browsing_history " \ "as a where a.userId=%d and a.articleId=%d and a.status=1" % (user_id, article_id) if query(query_article_sql): article_browsing_sql = "update tbl_article_browsing_history set updateDate='%s'" % get_current_time( ) excute(article_browsing_sql) else: article_browsing_sql = "INSERT INTO tbl_article_browsing_history " \ "VALUES (NULL, %d, %d, 1, '%s',NULL)" % (user_id, article_id, get_current_time()) excute(article_browsing_sql) # 查询article阅读总数 query_article_readcount_sql = "select * from tbl_article where id=%d" % article_id read_counts = query(query_article_readcount_sql)[0].get( "readCount") + 1 # 更新readCount总数 update_article_browsing_count = "update tbl_article set readCount=%d, " \ "updateDate='%s' where id=%d" % (read_counts, get_current_time(), article_id) excute(update_article_browsing_count) except Exception as e: print(e) pass # 查询文章和对应的评论 query_article_sql = "select * from tbl_article where id=%s and status=1" % article_id query_comments_sql = "select * from tbl_article_comment where articleId=%s and status=1" % article_id results = { "article": query(query_article_sql), "comments": query(query_comments_sql) } return json(get_json(data=results))
def signup(): name = request.form['name'] email = request.form['email'] password = request.form['password'] if len(name) < 3: return json({"message": "Name length too short", "status_code": 303}) if '@' not in email or '.' not in email or len(email) < 9: return json({"message": "Email Invalid", "status_code": 303}) if len(password) < 8: return json({"message": "Password too short.", "status_code": 303}) return json({"data": Signup(name, email, password)})
def delete_user(id): user = Users.query.get(id) if not user: return json({'message': 'user do not exist', 'data': {}}), 404 if user: try: db.session.delete(user) db.session.commit() result = user_schema.dump(user) return json({'message': 'successfully deleted', 'data': result}), 201 except: return json({'message': 'unable to delete', 'data': {}}), 500
def score_url(newsurl): content_score = content_scorer.score_domain(newsurl) whitelist_score = whitelist_scorer.score_domain(newsurl) whois_score = whois_scorer.score_domain(newsurl) score = content_score + whitelist_score + whois_score / 3 return json({'score': score})
def request_counters_option(option): success = dict() err = None if option == 'add': success = {"result": True, "message": "Данные успешно поданы"} err = error(6050) if option == 'history': array = list() for _ in range(randint(1, 15)): array.append(Counter().history()) success = { "page": 1, "pages": 1, "rowPerPage": 100, "totalRowsCount": 100, "result": True, "data": array } err = error(7010) return (json(success), 200) if randint(0, 20) != 5 else (err, 500)
def request_analytics(): # { # "ls": "69100403061", # "startdate": "2018-01-01T00:00:00.000", # "enddate": "2018-11-07T23:59:59.000", # "rowid": "1050194" # } current = choice([True, False]) tarifs = ['Одноставочный', 'Двуставочный'] tarif = choice([True, False]) success = { "result": True, "change": choice([True, False]), "idTarif": randint(11100, 999900), "nameTarif": "Переходный", "data": [{ "Current": current, "Tarif": tarifs[0 if tarif else 1], "sum": randint(11100, 999900) }, { "Current": not current, "Tarif": tarifs[0 if not tarif else 1], "sum": randint(11100, 999900) }] } return (json(success), 200) if randint(0, 10) != 5 else (error(10040), 500)
def query_paging_users(): """ 用户分页查询 :arg {"page":2,"token": "te4uzdia-gkee-ziiy-5cjg-zz8qji20z7a6"} :return: json 详细格式如下,此接口受前端限制,可能会更改 { "code":200 # 状态码 "msg":"ok", # msg "data":{ # 返回数据对象 {"articles":[ # 文章列表 [用户1],[用户2],[用户3],[用户4], ....[用户10] ]}, { "current_page":1 # 当前页码 }, { "dic_list":[1,4] # 通过这个循环来标注下一页 下下一页的参数 例如 articles?p=2;在这里需要post传json格式{"page":1} }, { "show_index_status":0 # 是否显示首页,0为不显示 }, { "total":3 # 共有几页 } } } """ paging_info = request.get_json() current_page = paging_info.get("page") # 当前页面 show_shouye_status = 0 # 显示首页状态 if current_page == '': current_page = 1 else: current_page = int(current_page) if current_page > 1: show_shouye_status = 1 limit_start = (int(current_page) - 1) * 10 # 查询n-10*n条记录,首页 sql = "select * from tbl_user limit %d,10" % limit_start user_list = query(sql) # 查询总记录和计算总页数 sql = "select * from tbl_user" count = len(query(sql)) # 总记录 total = int(math.ceil(count / 10.0)) # 总页数 dic = _get_page(total, current_page) datas = { "users": user_list, "currentPage": int(current_page), 'total': total, 'showIndexStatus': show_shouye_status, 'showRange': dic # 下一页或下下一页的参数的循环参数(开始,结束) 在python中表示 range } return json(get_json(data=datas))
def user_index(): """ :params {"token":"pmqkp62j-n5pw-w882-zk3e-qh8722mivo4u"} 获取用户个人中心信息,包括历史评论、收藏文章、浏览记录、个人资料 :return: json """ # 历史浏览 user = _get_user_session()["userInfo"] query_comment_his_sql = "select * from tbl_article_comment as " \ "a join tbl_article as b where a.articleId=b.id " \ "and a.userId=%d and a.status=1 and b.status=1 limit 10" % user.get("id") # 收藏文章 query_collect_sql = "select a.* from tbl_article as a JOIN " \ "tbl_article_collect as b on a.id=b.articleId " \ "and b.userId=%s and a.status=1 and b.status=1 " \ "limit 10" % user.get("id") # 浏览记录 query_browsing_his_sql = "select a.* from tbl_article as a JOIN " \ "tbl_article_browsing_history as b on a.id=b.articleId " \ "and b.userId=%d and a.status=1 and b.status=1 limit 10" % user.get("id") # 个人喜欢 query_like_sql = "select a.* from tbl_article as a JOIN " \ "tbl_article_like as b on a.id=b.articleId " \ "and b.userId=%d and a.status = 1 and b.status=1 limit 10" % user.get("id") # 构造响应数据 datas = { "userInfo": _get_user_session().get("userInfo"), "likes": query(query_like_sql), "comments": query(query_comment_his_sql), "collects": query(query_collect_sql), "browsing": query(query_browsing_his_sql) } return json(get_json(data=datas))
def user_info_page(): """ 进入页面时请求此接口 :params {"token":"pmqkp62j-n5pw-w882-zk3e-qh8722mivo4u"} :return: json """ return json(get_json(data=_get_user_session()))
def query_paging_articles(): """ 文章分页查询 :arg {"page":1,"token": "lup5gvda-5vwa-q3yp-kub5-sz69v6qxtgr3"} :return: json 详细格式如下,此接口受前端限制,可能会更改 { "code":200 # 状态码 "msg":"ok", # msg "data":{ # 返回数据对象 {"articles":[ # 文章列表 [文章1],[文章2],[文章3],[文章4], ....[文章10] ]}, { "current_page":1 # 当前页码 }, { "dic_list":[1,4] # 通过这个循环来标注下一页 下下一页的参数 例如 articles?p=2;在这里需要post传json格式{"page":1} }, { "show_index_status":0 # 是否显示首页,0为不显示 }, { "total":3 # 共有几页 } } } """ paging_info = request.get_json() current_page = paging_info.get("page") # 当前页面 show_shouye_status = 0 # 显示首页状态 if current_page == '': current_page = 1 else: current_page = int(current_page) if current_page > 1: show_shouye_status = 1 limit_start = (int(current_page) - 1) * 10 # 查询n-10*n条记录,首页 sql = "select * from tbl_article limit %d,10" % limit_start article_list = query(sql) # 查询总记录和计算总页数 sql = "select * from tbl_article" count = len(query(sql)) # 总记录 total = int(math.ceil(count / 10.0)) # 总页数 dic = _get_page(total, current_page) datas = { "articles": article_list, "current_page": int(current_page), 'total': total, 'show_index_status': show_shouye_status, 'show_range': dic # 下一页或下下一页的参数的循环参数(开始,结束) 在python中表示 range } return json(get_json(data=datas))
def admin_index(): """ 管理员首页 :args {"token":"xxx} :return: """ return json(get_json(data=_get_admin_session()))
def index(): """ 首页接口 :arg :return json """ datas = {} # 返回的数据集,包括用户信息、文章分类和信息、跑马灯、轮播图 # 查询文章信息 articles = [] for type in range(1, 6): title = "article" + str(type) query_article_sql = "select * from tbl_article where type=%s LIMIT 10" % str( type) articles.append({title: query(query_article_sql)}) # 查询跑马灯信息 query_anno_sql = "select * from tbl_announcement where status=1 LIMIT 10" # 查询轮播图信息 query_all_carouses_sql = "select a.*, b.path as imgPath " \ "from tbl_carouse as a JOIN tbl_image_sources as b " \ "where a.imgId=b.id and b.status=1 and a.status=1;" datas = { "articles": articles, "annos": query(query_anno_sql), "carouses": query(query_all_carouses_sql), "userInfo": session.get("user") } return json(get_json(data=datas))
def score_url(newsurl): # whitelisting of the domain if newsurl is None: raise ValueError('Requires valid URL') whitelist_score = 0.5 whitelist_score = whitelist.get(newsurl.lower(), whitelist_score) # what is the content of the page content_score = 0.5 r = requests.get(newsurl) if r.status_code == 200: soup = BeautifulSoup(r.text) text = soup.get_text().lower() for keyword in keywords: if keyword in text: content_score = max(content_score - 0.1, 0) # whois the domain (age) domain_score = 0.5 domain = whois.query(newsurl) if domain is not None: today = date.today() daysalive = (today - domain.creation_date) # 0 days is 0, 365 is 0.5, 730 is 1 domain_score = min(max(0, daysalive.days), 730) / 730 score = (whitelist_score + content_score + domain_score) / 3 return json({'score': score})
def getGirlPair(): db = getattr(g, 'db', None) #!! TODO: add error processing here randomPair = GirlPair.getRandomPair(db) return json(randomPair)