def add(): try: user_id = request.get_json()['user_id'] name = request.get_json()['name'] url = request.get_json()['url'] expect_price = request.get_json()['expect_price'] app_table_query = app_table.select().where( (app_table.user_id == user_id) & (app_table.is_valid == 1)).order_by(app_table.order).dicts() order = app_table_query[-1]['order'] + 1 app_table.create( name=name, url=url, user_id=user_id, expect_price=expect_price, order=order, is_valid=1, update_time=datetime.datetime.now(), ) response = {'code': 200, 'msg': '成功!'} return jsonify(response) except Exception as e: traceback.print_exc() response = { 'code': 500, 'msg': '失败!错误信息:' + str(e) + ',请联系管理员。', 'data': [] } return jsonify(response), 500
def edit(): try: user_id = request.get_json()['user_id'] threshold_min = float(request.get_json()['threshold_min']) threshold_max = float(request.get_json()['threshold_max']) if threshold_min >= threshold_max: return rsp.failed('阈值最小值不能大于或等于阈值最大值'), 500 if user_id == 0: return rsp.failed('无法为未登录用户设定阈值'), 500 threshold = [threshold_min, threshold_max] try: _ = gold_price_push_option.update(is_valid=0).where( (gold_price_push_option.is_valid == 1) & (gold_price_push_option.user_id == user_id)).execute() except DoesNotExist: ... gold_price_push_option.create(user_id=user_id, is_valid=1, push_threshold=str(threshold), update_time=datetime.datetime.now()) return rsp.success() except Exception as e: traceback.print_exc() return rsp.failed(e), 500
def userAdd(): try: login_name = request.get_json()['login_name'] name = request.get_json()['name'] role_id = request.get_json()['role_id'] password = request.get_json()['password'] stable_salt = request.get_json()['stable_salt'] is_login_name_exist = cf.is_data_existed_in_db(user, user.login_name, login_name) if is_login_name_exist: response = {'code': 406, 'msg': '已经存在此登录名的用户,请修改您的登录名'} return jsonify(response) else: user.create(name=name, login_name=login_name, role_id=role_id, stable_salt=stable_salt, password=password, is_valid=1, create_time=datetime.datetime.now(), update_time=datetime.datetime.now()) response = {'code': 200, 'msg': '成功'} return jsonify(response) except Exception as e: response = {'code': 500, 'msg': e, 'data': {}} return jsonify(response), 500
def userChangePassword(): try: login_name = request.get_json()['login_name'] user_query = user.select().where(user.login_name == login_name).dicts() if len(user_query) == 0: response = { 'code': 403, 'msg': '用户名或密码错误!', } return jsonify(response), 403 else: for row in user_query: salt_expire_time = row['salt_expire_time'] server_timestamp = datetime.datetime.now() if server_timestamp < salt_expire_time + datetime.timedelta( seconds=ALLOWED_TIME_SPAN): stable_salt = request.get_json()['stable_salt'] password = request.get_json()['password'] user.update(stable_salt=stable_salt, password=password, update_time=datetime.datetime.now()).where( user.login_name == login_name).execute() pf.del_user_id_to_redis(row['id']) response = {'code': 200, 'msg': '成功'} else: response = {'code': 403, 'msg': '登录状态已过期,请返回并重新验证密码'} return jsonify(response) except Exception as e: return rsp.failed(e), 500
def edit(): try: user_id = request.get_json()['user_id'] apps = request.get_json()['apps'] app_del_all(user_id) for app in apps: app_table.create( name=app['name'], url=app['url'], user_id=user_id, expect_price=app['expect_price'], order=app['order'], is_valid=1, update_time=datetime.datetime.now(), ) response = {'code': 200, 'msg': '成功!'} return jsonify(response) except Exception as e: traceback.print_exc() response = { 'code': 500, 'msg': '失败!错误信息:' + str(e) + ',请联系管理员。', 'data': [] } return jsonify(response), 500
def api_info(): if request.method == 'POST': print('Incoming..') print(request.get_json()) # parse as JSON return (request.get_json()) else: message = {'greeting': 'Hello from Flask!'} return jsonify(message) # serialize and use JSON headers
def searchLog(): try: user_id = request.get_json()['user_id'] engine_id = request.get_json()['engine_id'] search_text = request.get_json()['search_text'] search_engines_log.create( user_id=user_id, user='' if user_id == 0 else User(user_id=user_id).user_name, engine_id=engine_id, search_text=search_text, ip=request.remote_addr, update_time=datetime.datetime.now()) return rsp.success() except Exception as e: traceback.print_exc() return rsp.failed(e)
def searchEnginesSearch(): try: if request.get_json()['name'] == '百度': return rsp.success( eval( urllib.request.urlopen( request.get_json()['autoCompleteUrl']).read().decode( 'gbk').split('s:')[1].split('});')[0])) except Exception as e: traceback.print_exc() return rsp.failed(e)
def get(): try: user_id = request.get_json()['user_id'] _current_page = request.get_json()['current_page'] _pagination_size = request.get_json()['pagination_size'] _ = image_hosting_table.select().where((image_hosting_table.user_id == user_id) & (image_hosting_table.is_valid == 1)) _total = _.count() _r = _.order_by(-image_hosting_table.update_time).paginate(_current_page, _pagination_size).dicts() _list = [{'id': s_['id'], 'file_name': s_['file_name'], 'shorted_link': s_['shorted_link'], 'update_time': s_['update_time'].strftime("%Y-%m-%d %H:%M:%S")} for s_ in _r] return rsp.success({'list': _list, 'total': _total}) except Exception as e: return rsp.failed(e), 500
def get(): try: user_id = request.get_json()['user_id'] widget_id = request.get_json()['widget_id'] push_list = PushList(user_id=user_id, widget_id=widget_id).push_list_get().push_list if len(push_list) > 1: raise Exception('Bad Data Returned, Check The Parameter!') return rsp.success([] if len(push_list) == 0 else push_list[0].convert_to_dict()) except Exception as e: traceback.print_exc() return rsp.failed(e), 500
def changeName(): try: user_id = request.get_json()['user_id'] id = request.get_json()['id'] file_name = request.get_json()['file_name'] _ = image_hosting_table.get(image_hosting_table.id == id) if int(_.user_id) != int(user_id): return rsp.refuse('文件归属错误!'), 403 else: _.file_name = file_name _.save() return rsp.success() except Exception as e: traceback.print_exc() return rsp.failed(e), 500
def delete(): try: user_id = request.get_json()['user_id'] id = request.get_json()['id'] _ = image_hosting_table.get(image_hosting_table.id == id) if int(_.user_id) != int(user_id): return rsp.refuse('文件归属错误!'), 403 else: _.token = _.token + '[deleted:' + str(time.time()) + ']' _.is_valid = 0 _.save() return rsp.success() except Exception as e: traceback.print_exc() return rsp.failed(e), 500
def qns(): data = request.get_json() print("heloo", data) if ((db.add_ques(data['fusn'], data['ques'], data['stime'], data['etime'], data['tname'], data['tcode'])) == 1): return jsonify({'status': 'True'}) return jsonify({'status': 'False'})
def execute(site_type, branch_name): post = request.get_json() content_type = request.headers.get('Content-Type') if content_type != 'application/json': raise ServerError('handling {content_type} is not implemented'.format( content_type=content_type), status_code=501) resp = {'status': 'ok'} script_args = parsePost(post, branch_name) if script_args: try: scripts = app_config.SCRIPTS[site_type] except KeyError: raise ServerError( "No script file defined for '{0}' in config.".format( site_type), status_code=501) else: run_scripts.delay(scripts, script_args) response = make_response(json.dumps(resp), 202) response.headers['Content-Type'] = 'application/json' return response
def get_explore_palettes(): """ FLASK POST routing method for '/getExplorePalettes' Returns a list of palettes from a repository. The POST request content is a JSON string containing the repository name, branch and access token. """ content = request.get_json(silent=True) try: repo_name = content["repository"] repo_branch = content["branch"] repo_token = content["token"] except KeyError as ke: print("KeyError {1}: {0}".format(str(ke), repo_name)) return jsonify( {"error": "Repository, Branch or Token not specified in request"}) # Extracting the true repo name and repo folder. folder_name, repo_name = extract_folder_and_repo_names(repo_name) g = github.Github(repo_token) try: repo = g.get_repo(repo_name) except github.UnknownObjectException as uoe: print("UnknownObjectException {1}: {0}".format(str(uoe), repo_name)) return jsonify({"error": uoe.message}) # get results d = find_github_palettes(repo, "", repo_branch) # return correct result return jsonify(d)
def message(): values = request.get_json() # We run the proof of work algorithm to get the next proof... last_block = blockchain.last_block last_proof = last_block['proof'] proof = blockchain.proof_of_work(last_proof) '''reg_node()''' # We must receive a reward for finding the proof. # The sender is "0" to signify that this node has mined a new coin. blockchain.new_transaction( sender=values.get('sender'), recipient=values.get('recipient'), amount=values.get('amt'), ) # Forge the new Block by adding it to the chain block = blockchain.new_block(proof) response = { 'message': values.get('message'), 'index': block['index'], 'transactions': block['transactions'], 'proof': block['proof'], 'previous_hash': block['previous_hash'], } return jsonify(response), 200
def verifyID(): values = request.get_json() if (booklib.verify_address(values['ID']['public_key'], values['ID']['book_index'], values['ID']['address_signature'])): return 'verified user ', 201 return 'not verified user', 400
def get_interactions(): req = request.get_json() genes = req['geneList'] types = req['evidenceTypes'] dict = { 'format': 'tsv-no-header', 'method': 'network', 'genes': "%0d".join(genes), 'species': '9606', 'app': 'omics-analytics-project' } url = constants.STRINGDB_REQUEST_TEMPLATE.format(dict['format'], dict['method'], dict['genes'], dict['species'], dict['app']) print(url) try: response = urllib.request.urlopen(url) except urllib.error.URLError as err: error_message = err.read() print(error_message) sys.exit() network_data = [ x.decode('utf8').strip().split("\t") for x in response.readlines() ] # print (lines) output = app_util.cystoscape(network_data, types) return jsonify(output), 200
def insert(user_id): """Hacky way of inserting data into the project database.""" data = request.get_json() try: connection = pymysql.connect( host='hacksc.cv6knx9xzbuq.us-west-1.rds.amazonaws.com', user='******', password='******', db='main', cursorclass=pymysql.cursors.DictCursor) with connection.cursor() as cursor: sql = "INSERT INTO `user_data` (`user_id`, `agreeableness`, `conscientiousness`, `extraversion`, `emotional_range`, `openness`, `name`) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s') ON DUPLICATE KEY UPDATE user_id='%s', agreeableness='%s', conscientiousness='%s', extraversion='%s', emotional_range='%s', openness='%s', name='%s'" % ( user_id, data['Agreeableness'], data['Conscientiousness'], data['Extraversion'], data['Emotional range'], data['Openness'], data['name'], user_id, data['Agreeableness'], data['Conscientiousness'], data['Extraversion'], data['Emotional range'], data['Openness'], data['name']) cursor.execute(sql) connection.commit() return "Hello World" except (ValueError, KeyError, TypeError) as error: print(error) resp = Response({"JSON Format Error."}, status=400, mimetype='application/json') return resp
def get_doc_id(): data = request.get_json() x = int(data.get('docID')) print(type(x)) string_x = str(x) return jsonify(string_x)
def execute(site_type, branch_name): post = request.get_json() content_type = request.headers.get('Content-Type') if content_type != 'application/json': raise ServerError('handling {content_type} is not implemented'.format(content_type=content_type), status_code=501) resp = {'status': 'ok'} script_args = parsePost(post, branch_name) if script_args: try: scripts = app_config.SCRIPTS[site_type] except KeyError: raise ServerError("No script file defined for '{0}' in config.".format(site_type), status_code=501) else: run_scripts.delay(scripts, script_args) response = make_response(json.dumps(resp), 202) response.headers['Content-Type'] = 'application/json' return response
def insert_user_values(user_id): """Hacky way of inserting data into the project database.""" data = request.get_json() try: connection = pymysql.connect( host='hacksc.cv6knx9xzbuq.us-west-1.rds.amazonaws.com', user='******', password='******', db='main', cursorclass=pymysql.cursors.DictCursor) with connection.cursor() as cursor: sql = "INSERT INTO `user_values` (`user_id`, \ `Conservation`, \ `Openness to change`, \ `Hedonism`, \ `Self-enhancement`, \ `Self-transcendence`) \ VALUES ('%s', '%s', '%s', '%s', '%s', '%s')" \ % (user_id, data['Conservation'], data['Openness to change'], data['Hedonism'], data['Self-enhancement'], data['Self-transcendence']) cursor.execute(sql) connection.commit() return "Hello World" except (ValueError, KeyError, TypeError) as error: print(error) resp = Response({"JSON Format Error."}, status=400, mimetype='application/json') return resp
def ver(): try: print('request.is_json', request.is_json) values = request.get_json() print('values', values) source_image = get_image(values['source']) if source_image is None: print('source image is None') return '-1' assert not isinstance(source_image, list) print(source_image.shape) target_image = get_image(values['target']) if target_image is None: print('target image is None') return '-1' #print(target_image.shape) if not isinstance(target_image, list): target_image = [target_image] #print('before call') #ret = model.is_same_id(source_image, target_image) ret = model.sim(source_image, target_image) except Exception as ex: print(ex) return '-1' #return str(int(ret)) print('sim', ret) return "%1.3f" % ret
def new_book(): values = request.get_json() required = ['title'] if not all(k in values for k in required): return 'Missing values', 400 if not booklib.is_empty() and booklib.if_exists(values['title']): response = { 'message': 'this book already exists', } return jsonify(response), 400 hosturl = request.host book = Blockchain(values['title'], hosturl) book.nodes = booklib.nodes booklib.book_arr.append(book) booklib.set_current_book(values['title']) booklib.resolve_books() neighboors = booklib.nodes for node in neighboors: response = requests.post(f'http://{node}/book/set', json={'title': values['title']}) response = { 'message': 'A new book has been added!', 'books': [x.title for x in booklib.book_arr] } return jsonify(response), 201
def create_youcoins(): payload = request.get_json() user = models.User.get(models.User.username == payload['username']) key = "AIzaSyCQ2cEg3s_1ahHpikqqoPwrTRFBKQB-zFU" url = payload["channelUrl"] for i in range(len(url)): if url[i:i + 8] == "channel/": name = url[i + 8:] data = urllib.request.urlopen( "https://www.googleapis.com/youtube/v3/channels?part=snippet%2CcontentDetails%2Cstatistics&id=" + name + "&key=" + key).read() subs = json.loads(data)["items"][0]["statistics"]["subscriberCount"] title = json.loads(data)["items"][0]["snippet"]["title"] youcoin = models.Youcoin.create(user=user.id, channelUrl=payload['channelUrl'], channelTitle=title, channelId=name, startingNum=int(subs), currentNum=int(subs), profit=0) you_dict = model_to_dict(youcoin) return jsonify(data=you_dict, status={"code": 281, "message": "Success"})
def request_book(): values = request.get_json() required = ['title'] if not all(k in values for k in required): return 'Missing values', 400 owner = booklib.find_owner(values['title']) neighboors = booklib.nodes if ((owner != f'http://{request.host}') and (owner != 'book doesn\'t exist')): if (booklib.ping_node(owner, values['title'], request.host)): message = { 'verification': 'sender and recipient are verified', 'message': 'book has been successfully requested', 'former owner': owner, 'new owner': f'http://{request.host}' } return jsonify(message), 201 message = { 'verification': 'either recipient or sender are not verifiable', 'message': 'book request is void' } return jsonify(message), 400 if (booklib.if_exists(values['title']) == False): message = {'message': f'{values["title"]} doesn\'t exist'} return jsonify(message), 400 else: message = { 'message': 'request cannot be made because you are the owner' } return jsonify(message), 400
def save(): """ FLASK POST routing method for '/saveToLocalFile' Saves a file to local computer. """ content = request.get_json(silent=True) temp_file = tempfile.TemporaryFile() try: json_string = json.dumps(content) if sys.version_info < (3, 2, 0): temp_file.write(json_string) else: temp_file = tempfile.TemporaryFile(mode="w+t") temp_file.write(json.dumps(content, indent=4, sort_keys=True)) # Reset the seeker temp_file.seek(0) string = temp_file.read() # Indent json for human readable formatting. graph = json.loads(string) json_data = json.dumps(graph, indent=4) return json_data finally: temp_file.close()
def get_docker_image_tags(): """ FLASK POST routing method for '/getDockerImagesTag' Returns a list of tags for a certain docker image from the docker registry. The POST request content is a JSON string containing the image name. """ content = request.get_json(silent=True) try: image_name = content["imagename"] except KeyError as ke: print("KeyError: {0}".format(str(ke))) return jsonify({"error": "Imagename not specified in request"}) docker_url = "https://registry.hub.docker.com/v2/repositories/" + image_name + "/tags" # avoid ssl errors when fetching a URL using urllib.request # https://stackoverflow.com/questions/50236117/scraping-ssl-certificate-verify-failed-error-for-http-en-wikipedia-org ssl._create_default_https_context = ssl._create_unverified_context with urllib.request.urlopen(docker_url) as url: data = json.loads(url.read().decode()) #print(data) return jsonify(data)
def register(): data = request.get_json() add_new_instance(data, request.remote_addr) context = {"status": "new instance added!"} return (flask.jsonify(**context), 201)
def feedbacks_video(): data = request.get_json() comment_data = feedback(comment=data['comment'], video_id=data['video_id']) db.session.add(comment_data) db.session.commit() print("You have liked it") return jsonify({'message': 'comment aaded successfull without like'})
def flask_request(request): try: json = request.get_json( silent=True, force=True ) #Silent parsing otherwise none and force ignore the content type. request_args = request.args if json and 'Year' and 'Month' in json: # This require for JSON content Year = escape(json['Year']) Month = escape(json['Month']) elif request_args and 'Year' and 'Month' in request_args: # This requires for String url Year = request_args['Year'] Month = request_args['Month'] else: d1 = dt.date.today( ) # Else any of above is not passed then else condition d1Year = d1.year Backdated_Month = d1.month - 3 # Minus 3 Month File from date d1Month = '%02d' % Backdated_Month # Leading zero Year, Month = d1Year, d1Month ingest_upload(Year, Month) print('Success ... ingested to {}{}'.format(Year, Month)) except Exception as e: print('Try again later using flask: {}'.format(e))
def hello(): data = request.get_json() message = data.get('messages')[0]['text'] userId = data.get('appUser')['_id'] print ("in hello") #nuanceParse(message) print (nuanceParse(message)) return 'all good'
def webhook(): req = request.get_json(silent=True, force=True) res = processRequest(req) res = json.dumps(res, indent=4) r = make_response(res) r.headers['Content-Type'] = 'application/json' return r
def image(): feed_dict = {inputs: [request.get_json()]} feed_dict.update(app.config['DEFAULT_FEED_DICT']) result = sess.run(generate_image, feed_dict=feed_dict) return jsonify(result='data:image/png;base64,' + base64.b64encode(result).decode())