我有一個朋友(這朋友不是我),朋友的單位裏有一個小型圖書室,圖書室中存放了很多書。css
儘管每本書都在相應的區域裏進行了編號,可是畢竟沒有圖書館的管理系統,你們找起來仍是要花點時間的。爲了讓你們更容易地找到這些書,朋友聯繫我,打算讓我幫他作一個簡單的圖書查詢系統(完整的圖書館管理系統)。html
Easier said than done,考慮到這仍是有必定複雜度的項目,我打算使用騰訊云云函數 SCF,把整個應用部署到 Serverless 架構上。前端
左邊是圖書檢索系統的首頁;右邊是檢索演示,比方說咱們搜索「精神」,App 就會依據返回相關的書籍。看起來還不賴。git
分類 tab:github
import jieba import openpyxl from gensim import corpora, models, similarities from collections import defaultdict import urllib.request with open("/tmp/book.xlsx", "wb") as f: f.write( urllib.request.urlopen("https://********").read() ) top_str = "abcdefghijklmn" book_dict = {} book_list = [] wb = openpyxl.load_workbook('/tmp/book.xlsx') sheets = wb.sheetnames for eve_sheet in sheets: print(eve_sheet) sheet = wb.get_sheet_by_name(eve_sheet) this_book_name_index = None this_book_number_index = None for eve_header in top_str: if sheet[eve_header][0].value == "書名": this_book_name_index = eve_header if sheet[eve_header][0].value == "編號": this_book_number_index = eve_header print(this_book_name_index, this_book_number_index) if this_book_name_index and this_book_number_index: this_book_list_len = len(sheet[this_book_name_index]) for i in range(1, this_book_list_len): add_key = "%s_%s_%s" % ( sheet[this_book_name_index][i].value, eve_sheet, sheet[this_book_number_index][i].value) add_value = { "category": eve_sheet, "name": sheet[this_book_name_index][i].value, "number": sheet[this_book_number_index][i].value } book_dict[add_key] = add_value book_list.append(add_key) def getBookList(book, book_list): documents = [] for eve_sentence in book_list: tempData = " ".join(jieba.cut(eve_sentence)) documents.append(tempData) texts = [[word for word in document.split()] for document in documents] frequency = defaultdict(int) for text in texts: for word in text: frequency[word] += 1 dictionary = corpora.Dictionary(texts) new_xs = dictionary.doc2bow(jieba.cut(book)) corpus = [dictionary.doc2bow(text) for text in texts] tfidf = models.TfidfModel(corpus) featurenum = len(dictionary.token2id.keys()) sim = similarities.SparseMatrixSimilarity( tfidf[corpus], num_features=featurenum )[tfidf[new_xs]] book_result_list = [(sim[i], book_list[i]) for i in range(0, len(book_list))] book_result_list.sort(key=lambda x: x[0], reverse=True) result = [] for eve in book_result_list: if eve[0] >= 0.25: result.append(eve) return result def main_handler(event, context): try: print(event) name = event["body"] print(name) base_html = '''<div class='mui-card'><div class='mui-card-header'>{{book_name}}</div><div class='mui-card-content'><div class='mui-card-content-inner'>分類:{{book_category}}<br>編號:{{book_number}}</div></div></div>''' result_str = "" for eve_book in getBookList(name, book_list): book_infor = book_dict[eve_book[1]] result_str = result_str + base_html.replace("{{book_name}}", book_infor['name']) \ .replace("{{book_category}}", book_infor['category']) \ .replace("{{book_number}}", book_infor['number'] if book_infor['number'] else "") if result_str: return result_str except Exception as e: print(e) return '''<div class='mui-card' style='margin-top: 25px'><div class='mui-card-content'><div class='mui-card-content-inner'>未找到圖書信息,請您從新搜索。</div></div></div>'''
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>圖書檢索系統</title> <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <link rel="stylesheet" href="https://others-1256773370.cos.ap-chengdu.myqcloud.com/booksearch/css/mui.min.css"> <style> html, body { background-color: #efeff4; } </style> <script> function getResult() { var UTFTranslate = { Change: function (pValue) { return pValue.replace(/[^\u0000-\u00FF]/g, function ($0) { return escape($0).replace(/(%u)(\w{4})/gi, "&#x$2;") }); }, ReChange: function (pValue) { return unescape(pValue.replace(/&#x/g, '%u').replace(/\\u/g, '%u').replace(/;/g, '')); } }; var xmlhttp; if (window.XMLHttpRequest) { // IE7+, Firefox, Chrome, Opera, Safari 瀏覽器執行代碼 xmlhttp = new XMLHttpRequest(); } else { // IE6, IE5 瀏覽器執行代碼 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200 && xmlhttp.responseText) { document.getElementById("result").innerHTML = UTFTranslate.ReChange(xmlhttp.responseText).slice(1, -1).replace("\"",'"'); } } xmlhttp.open("POST", "https://********", true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send(document.getElementById("book").value); } </script> </head> <body> <div class="mui-content" style="margin-top: 50px"> <h3 style="text-align: center">圖書檢索系統</h3> <div class="mui-content-padded" style="margin: 10px; margin-top: 20px"> <div class="mui-input-row mui-search"> <input type="search" class="mui-input-clear" placeholder="請輸入圖書名" id="book"> </div> <div class="mui-button-row"> <button type="button" class="mui-btn mui-btn-numbox-plus" style="width: 100%" onclick="getResult()">檢索 </button> </div> </div> <div id="result"> <div class="mui-card" style="margin-top: 25px"> <div class="mui-card-content"> <div class="mui-card-content-inner"> 能夠在搜索框內輸入書籍的全稱,或者書籍的簡稱,系統支持智能檢索功能。 </div> </div> </div> </div> </div> <script src="https://others-1256773370.cos.ap-chengdu.myqcloud.com/booksearch/js/mui.min.js"></script> </body> </html>
其實這是一個低頻使用的 App,畢竟單位圖書室藏書很少,人流量也不大。若是將它部署在一個傳統服務器上,可能不是個好的選擇,畢竟服務器放在那裏無論用不用都得花錢。web
因此這裏選擇了 Serverless 架構,部署在雲函數上,按量付費的特色能夠節省很多成本。同時,經過 APIGW 和 COS 的結合,完美解決了資源浪費的問題。騰訊雲 Serverless Framework 也是一個很好用的開發者工具,除此以外,這裏還使用了雲函數的 APIGW 觸發器,輕巧地替代了傳統 Web 框架和部分服務器軟件的安裝、使用和維護。瀏覽器
這只是一個小應用,不過稍加改造,也能作成查詢成績的 App。Serverless 的應用場景仍是頗有想象力的。服務器
傳送門:架構
- GitHub: github.com/serverless
- 官網:serverless.com
歡迎訪問:Serverless 中文網,您能夠在 最佳實踐 裏體驗更多關於 Serverless 應用的開發!app
推薦閱讀: 《Serverless 架構:從原理、設計到項目實戰》