본문 바로가기
미니 프로젝트

workbench와 flask 연동 후 원하는 값 얻기

by rattlesnake 2023. 5. 24.

하고 싶은 것: 

검색창에서 검색을 하면 그 값을 받아와서 그 값이 workbench 테이블 데이터 안에 있는 데이터만 불러오기

 

app.py

#searching data to db
def search_article(title):
    word = title
    conn = pymysql.connect(host="localhost", user="root", password="0000", database="dont_forget")
    cursor = conn.cursor()
    search_sql = f"""select title, body from web_forex_news where body like "%{word}%"
              UNION  select title, body from web_stock_news where body like "%{word}%"
              UNION  select title, body from web_bond_news where body like "%{word}%";"""
    cursor.execute(search_sql)
    search_result = cursor.fetchall()
    conn.close()
    return search_result
    
    @app.route('/search', methods=["GET"])
def search():
        word = request.args.get("word")
        results = search_article(word)
        if not results:
            return redirect(url_for('no_results'))
        else:
            return render_template('search_article.html', word=word, results=results)

@app.route('/no_results')
def no_results():
    return render_template('no_results.html')

MySql과 연동 후 search_acrticle에서 내가 가져오고 싶어 하는 데이터를 쿼리문 작성

search에서 search_article로 render

 

 

search_article.html

{% extends 'search.html' %}

{% block bodybody %}
{% for result in results %}
 <a target="_blank" class="t" onclick="clearhref(this, '{{result[0]}}')" style="cursor: pointer;">{{result[0]}}</a>
 <p>{{result[1]}}</p>
{% endfor %}>
{% endblock %}

 

search.html

 <div id="main_section" class="main_section">
     <h2>입력하신 검색어: '<span style="color: red;">{{word}}</span>'</h2>
     <hr>
{% block bodybody %}
{% endblock %}
   </div>

 

js

function clearhref(element, result) {
    element.setAttribute("href", "newsclick/" + result.replaceAll(" ", "_") );
}

 

'미니 프로젝트' 카테고리의 다른 글

element.setAttribute  (0) 2023.05.22