백엔드 기능 구현하기
4. 레시피 저장 - post방식 api 만들기
@app.route('/save_paik_recipe', methods=['POST'])
def save_paik_recipe():
# 클라이언트로부터 데이터를 받는 부분
email_receive = request.form['email_give']
url_receive = request.form['url_give']
# 사용자가 저장한 레시피의 url 파라미터를 'paik_all_recipes' db에서 조회한 후 카테고리 값 뽑기
paik_recipes_info = db.paik_all_recipes.find_one({'url': url_receive}, {'_id': 0})['category']
# print(paik_recipes_info)
exist_follow_url = db.save_paik_follow.find_one({'url': url_receive})
# print(exist_follow_url)
exist_official_url = db.save_paik_official.find_one({'url': url_receive})
# print(exist_official_url)
if paik_recipes_info == '따라하기레시피':
if exist_follow_url != None:
# 유저가 저장하려는 레시피가 이미 저장되어 있다면 중복저장하지 않기
return jsonify({'result': 'fail', 'message': '이미 저장된 레시피입니다! 레시피를 조회 해보세요.'})
else :
db.save_paik_follow.insert_one({
'email': email_receive,
'url': url_receive,
})
else:
if exist_official_url != None:
# 유저가 저장하려는 레시피가 이미 저장되어 있다면 중복저장하지 않기
return jsonify({'result': 'fail', 'message': '이미 저장된 레시피입니다! 레시피를 조회 해보세요.'})
else:
db.save_paik_official.insert_one({
'email': email_receive,
'url': url_receive,
})
# '공식레시피'이면 'save_paik_official' db에 저장되고, '따라하기레시피'이면 'save_paik_follow' db에 저장
return jsonify({'result': 'success'})
if exist_follow_url != None
여기서 참 많이 헤메었다.
중복저장을 못 하게 해야 조회할 때 원하는 데이터만 잘 나오기 때문에 코드를 짜는데..
저장데이터쪽에 현재 저장하려는 레시피의 url이 없다면 값이 None이 찍히길래 위와같이 넣었더니 잘 작동했다. len함수도 쓰고 별 짓 다해봤는데 안되길래.. 답답했는데. 역시 핵심은 오류메세지! 그 곳을 집중공략해서 해결할 것!
let email = $('#posting-email').val();
let url = $('#posting-url').val();
if(email ==''){
alert('이메일을 입력해주세요!');
$('#posting-email').focus();
return false;
}else if(url ==''){
alert('URL을 입력해주세요!');
$('#posting-url').focus();
return false;
}
$.ajax({
type: "POST", // POST 방식으로 요청하겠다.
url: "/save_paik_recipe", // /post라는 url에 요청하겠다.
data: { url_give: url, email_give: email }, // 데이터를 주는 방법
success: function(response){ // 성공하면
if (response['result'] == 'success') {
alert('레시피 저장 성공!');
window.location.reload();
} else {
alert('이미 저장된 레시피입니다! 레시피를 조회 해보세요.')
}
}
})