最近對這個項目進行了優化完善,記錄了本次優化的過程
詳情頁景點文字顯示
用{{ mus.music_name }}代替了字符串
新建site頁做改動
author存儲Tzxkd位置副標題
address存儲簡介
Modern Chinese city known for its skyscrapers, the Bund promenade, art deco buildings & shopping.
China's capital & home to major sites such as the Forbidden City palace complex & Tiananmen Square.
景點推薦動態
推薦根據序號order
新建top_places表
建立新model
class TopPlaces( db.Model): """評論點贊""" __tablename__ = "top_places" id = db.Column("id", db.Integer, primary_key=True) # 評論編號 site_id = db.Column("site_id", db.Integer, nullable=False) # 用戶編號 rec_site_id = db.Column("rec_site_id", db.Integer, nullable=False) # 用戶編號 rank = db.Column("rank", db.Integer) |
寫view,運行,報錯:
sqlalchemy.exc.ArgumentError: Object <app.models.TopPlaces object at 0x000001C791FBF188> is not legal as a SQL literal value |
File "D:\anacondaProject\music-website-flask\app\home\views.py", line 443, in play top_place = Music.query.filter(Music.music_id == place_id) |
獲取的方式不對,通過主鍵的值查詢時直接使用:
cls.query.get(值) User.query.get(10) |
第一次查出的是對象,要遍歷從對象中取值
top_places = [] # 根據user.id,查出用戶點贊過的TopPlaces對象 top_places_list = TopPlaces.query.filter(TopPlaces.site_id == musicid).order_by(TopPlaces.rank.asc()).all() # 遍歷TopPlaces所有對象,查出點贊評論的id top_place_ids = [top_place.rec_site_id for top_place in top_places_list] for place_id in top_place_ids: print("place_id:%d",place_id) top_place = Music.query.get(place_id) top_places.append(top_place) |
推薦部分使用模型結果
@home.route('/map', methods=['POST']) def userinput(): app = current_app._get_current_object() # data = request.data data = str(request.data, encoding='utf-8') # print(data)接收的center place ms = app.where2go.most_similar(data) top_places_json = app.where2go.get_top_places_json(ms) app.result['top_places'] = top_places_json return json.dumps(app.result) |
model_output = JSON.parse(data) var center_location = model_output['center_location']; var geojson = model_output['top_places']; |
傳回一個dict
最好的方法是直接調用model中的函數,因爲進入頁面從後臺查數據,不需要前臺ajax
Ms:
def most_similar(self, input, topn=40): ''' use the trained word2vec model to give most similar recommendations to the input
input = search string in the format of place/char + place/char -... output = top recommendations in json format ''' |
使用ms結果:
for n, entry in enumerate(ms): place, sim = entry # Check if the recommendation is a geo location. if place in self.geotag_imglink_wikiurl: |
遍歷根據place查詢景點,判空
if not comment_like:
模型推薦view:
top_places = [] num_show = 0 max_markers = 1 app = current_app._get_current_object() ms = app.where2go.most_similar(music.music_name) for n, entry in enumerate(ms): place_name, sim = entry # Check if the recommendation is a geo location. place = Music.query.filter( Music.music_name.ilike('%' + place_name + '%') ).first() if place: # if place in self.geotag_imglink_wikiurl: top_places.append(place) num_show += 1 if num_show == max_markers: break |
好像成功了,因爲數據庫中添加的詳細介紹信息較少,第一個能查詢到的還是和原來一樣
這個做的時候可害怕了,糾結了好久,結果一運行一個bug也沒報,太順利了。(二營長,你他孃的意大利炮呢)
圖片link索引重新生成
圖片地址存儲在:
geotag_imglink_wikiurl[place]['img_path']
'data/pickles/geo_imglink_wikiurl.pkl'
查找模型運行日誌得(還好記了,不然腦殼都忘光):
scrap_wikivoyage_banners.py全部運行完在D:\anacondaProject\where2go\data生成了一個geotag_imglink_wikibanner.pkl
重新生成模型過程中需要重點代碼:
place = place.replace('/', '_') # REPLACE '/' with '_' BECAUSE IT CREATES A DIRECTORY |
重寫圖片文件名索引:
def make_local_img_url(self, place): ''' input = place output = return the default values for img_path and wiki_url ''' wiki_url = 'https://en.wikivoyage.org/wiki/%s' % place if os.path.exists('../../webapp/static/banners/%s.png' % place): img_path = 'static/banners/'+place+'.png' print 'place %s,' % place else: place = place.replace('/', '_') # REPLACE '/' with '_' BECAUSE IT CREATES A DIRECTORY if os.path.exists('../../webapp/static/banners/%s.png' % place): img_path = 'static/banners/'+place+'.png' print 'place %s,' % place else: return self.make_default_img_url(place) return img_path, wiki_url |
頁面顯示沒有改變,查看pikle的包含地名:確定已經包含了
geotag_imglink_wikiurl[place]['img_path']讀取的也依然是default
可以看到pickle文件中也是正常的:
(S'-58.56670000' tRp112087 ssS'guangzhou' p112088 (dp112089 g4 S'static/banners/guangzhou.png' p112090 sg6 S'https://en.wikivoyage.org/wiki/guangzhou' |
看到源碼中model保存了自己:
with open('../../data/pickles/where2go_model.pkl', 'wb') as f: cPickle.dump(where2go, f) |
在app.py中也有:
return pkl.load(open('../data/pickles/where2go_model.pkl', 'rb')) |
有可能保存了之後就沒有再進行讀取
所以重新運行了一遍where2go_model.py
更新成功
推薦處圖片位置刪除or加上改好的索引
原先生成時使用的js:
var portfolio_html = '<div class="portfolio-item"><img src='+image+' class="img-responsive" alt=""><div class="portfolio-caption"><a target="_blank" class="popup" href="' + wiki_url + '"><h4>'+rank+'. '+title+'</h4></div></div>'; |
var marker = e.layer, feature = marker.feature; //路徑 <link rel="shortcut icon" href="{{ url_for('static',filename='base/images/logo.png') }}"> // Create custom popup content var popupContent = '<a target="_blank" class="popup" href="' + feature.properties.url + '">' + '<div class=crop><img src="http://q7ourhxfp.bkt.clouddn.com' + feature.properties.image + '" height/></div><div class=text-center style="padding:15px 0 0 0"><font size="5">' + feature.properties.title + '</font></div></a>'; |
這裏設計到之前一直解決不了的url_for('static'動態生成的html字符串的src中的問題
參考:http://codingdict.com/questions/6062
原意(但寫法錯): <img src=" {{ url_for('static', filename='uploads/users/{{ song['artistName'] }}/{{ song['pathToCover'] }}') }}"> |
建議: <img src="{{ url_for('static', filename='uploads/users/') }} {{ song['artistName'] }}/{{ song['pathToCover'] }}"> |
考慮參考評論把動態生成的改成靜態包含的,通過是否查詢變量控制css和py是否顯示
View
考慮主頁與詳情頁的不同,這裏不是進頁面就顯示,而是查詢後顯示,可參考評論中的新增
新增評論評論view-news_comment:
也沒有重新渲染頁面,但使用jsonify傳遞參數
return jsonify(errno="0", errmsg="評論成功", data=comment.to_dict()) |
Jsonify與Python 自帶的 json 模塊相類似,暫時不多做關注
html
列表放置位置爲:
<div class="container" id ="portfolio"> </div> |
原先在html中對data參數的使用:完全作爲ajax的返回值:
'success': function (data) { model_output = JSON.parse(data) |
顯示新增評論的操作也是在js中進行的:
if (comment.user.avatar_url) { comment_html += '<img src="' + comment.user.avatar_url + '" alt="用戶圖標">' } else { comment_html += '<img src="../../static/news/images/person01.png" alt="用戶圖標">' } |
這裏使用了靜態相對地址
首頁json:
var portfolio_html = '<div class="portfolio-item"><img src="../../'+image +'" class="img-responsive" alt=""><div class="portfolio-caption"><a target="_blank" class="popup" href="' + wiki_url + '"><h4>'+rank+'. '+title+'</h4></div></div>'; |
也使用相對地址然後成功了,之前直接static或urlfor的方法都不好用
去除圖片拉伸
標籤上的圖片顯示得有點扭曲,顯示方式改成:剪裁適應
參考:https://segmentfault.com/q/1010000018971940
object-fit似乎是被人忽視的一個CSS3屬性。因爲存在兼容性,所以沒有background-size好用,但是由於某種情況,你不得不用img標籤來引入圖片,這時候用object-fit是很好的選擇。
我們給上圖所有img都統一加上object-fit:cover;