Created
July 17, 2020 02:00
-
-
Save yaparlareddy/687130f7b8db08aecd552886960f23a7 to your computer and use it in GitHub Desktop.
p
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from flask import Flask, request, jsonify | |
| import redis | |
| Redis = redis.StrictRedis(host='localhost', port=6379, db=0, charset="utf-8", decode_responses=True) | |
| app = Flask(__name__) | |
| @app.route("/") | |
| def root(): | |
| return "Hello world!" | |
| @app.route("/add_word/word=<word>") | |
| def insert(word): | |
| word = word.strip() | |
| for index in range(1, len(word)): | |
| substring = word[0:index] | |
| Redis.zadd("database2", {substring: 0}) | |
| print(substring) | |
| Redis.zadd("database2", {(word + '*'): 0}) | |
| return "add word" | |
| @app.route("/autocomplete/query=<word>") | |
| def find(word): | |
| word = word.strip() | |
| autocompleted_words = [] | |
| starting_index = Redis.zrank("database2", word) | |
| if not starting_index: | |
| return [] | |
| range = Redis.zrange("database2", starting_index, -1) | |
| if len(range) == 0 or not range: | |
| return [] | |
| data: object | |
| for data in range: | |
| print(data) | |
| min_len = min(len(data), len(word)) | |
| if data[0:min_len] != word[0:min_len]: | |
| return jsonify(autocompleted_words) | |
| break | |
| if len(data) > 1 and data[-1] == '*': | |
| autocompleted_words.append(data[0:-1]) | |
| print(autocompleted_words) | |
| return jsonify(autocompleted_words) | |
| if __name__ == "__main__": | |
| app.run(debug=True, use_reloader=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment