백엔드 기능 구현하기
3. 레시피 search - get방식 api 만들기
@app.route('/search_paik_follow', methods=['GET'])
def search_paik_follow_view():
# title_give로 클라이언트가 준 title을 가져오기
title_receive = request.args.get('title_give')
# title의 값이 받은 title과 일치하는 document 찾기 & _id 값은 출력에서 제외하기
follow_recipe_info = list(db.paik_all_recipes.find({'category': '따라하기레시피', 'title': {'$regex': title_receive}}, {'_id': 0}))
# info라는 키 값으로 해당하는 레시피 데이터 내려주기
return jsonify({'result': 'success', 'follow_recipe_info': follow_recipe_info})
let recipe = $('#recipe_input').val();
if(recipe ==''){
alert('레시피를 입력해주세요!');
$('#posting-email').focus();
return false;
}
$('#paik_official').html('');
$('#paik_follow').html('');
// Developer 문세미 - ajax 코드 - paik-follow-recipe_search
$.ajax({
type: "GET",
url: "/search_paik_follow?title_give=" + recipe,
data: {},
success: function(response){
if (response['result'] == 'success') {
let follow_recipe_info = response['follow_recipe_info'];
console.log(follow_recipe_info);
for (let i = 0; i < follow_recipe_info.length; i++) {
paik_follow_recipe_list(follow_recipe_info[i]['image'],follow_recipe_info[i]['title'],follow_recipe_info[i]['posting_day'],follow_recipe_info[i]['description'],follow_recipe_info[i]['author'],follow_recipe_info[i]['url'])
}
} else {
alert('레시피를 받아오지 못했습니다');
}
}
})
@app.route('/search_paik_official', methods=['GET'])
def search_paik_official_view():
# title_give로 클라이언트가 준 title을 가져오기
title_receive = request.args.get('title_give')
# title의 값이 받은 title과 일치하는 document 찾기 & _id 값은 출력에서 제외하기
official_recipe_info = list(db.paik_all_recipes.find({'category': '공식레시피', 'title': {'$regex': title_receive}}, {'_id': 0}))
# info라는 키 값으로 해당하는 레시피 데이터 내려주기
return jsonify({'result': 'success', 'official_recipe_info': official_recipe_info})
ㄴ 참조한 사이트이다.
db.products.find({name:{regex:"sd"}) --> name키값에 sd가 포함되어 있는 것을 찾아라regex : "s" --> s가 포함되어있는것을 찾기
" --> 끝자리가 s인것을 찾기
$regex : "^s" --> 첫자리가 s인것을 찾기
출처 : mongodb에서 문자열 검색 쿼리
official_recipe_info = list(db.paik_all_recipes.find({'category': '공식레시피', 'title': {'$regex': title_receive}}, {'_id': 0}))
ㄴ 해결 된 코드
official_recipe_info = list(db.paik_all_recipes.find({'category': '공식레시피'}, {'title': {'$regex': title_receive}}, {'_id': 0}))
ㄴ 이렇게 실행하니 계속 오류가 나서 몇 시간을 헤멨다.
{},{},{} 이런식으로 하나씩 딕셔너리형태로 작성했는데
{..., ...},{} 이렇게 하니 되었다..
검색해도 안 나와서 내가 직접 해결했지만 해결해놓고도 왜 맞는지.. 모르겠다..
ㄴ 'title_give'로 김치를 입력했을 때의 api모습 (공식레시피)
ㄴ 'title_give'로 김치를 입력했을 때의 api모습 (따라하기레시피)
오늘의 느낀점!
계속 헤메었던 부분이 해결되어서 너무나 기뻤다.
작은 부분일지라도 해결되지 않으니.. 너무나 답답했는데
해결되는 순간의 그 짜릿함이란! 이게 코딩의 매력인 것 같다. 구글링으로 해결 되면 좋겠지만.. 구글링으로도 해결이 안된다면! 이 코드, 저 코드 넣어보고 될 때까지 keep going하자. 답은 나오게 되어있다.