Article Outline
Python mysql example 'lern vsearch4web'
Functions in program:
def view_the_log() -> 'html':
def entry_page() -> 'html':
def do_search() -> 'html':
def log_request(req: 'flask_request', res: str) -> None:
python lern vsearch4web
Python mysql example: lern vsearch4web
from flask import Flask, render_template, request, escape
from vsearch import search4letters
from DBcm import UseDatabase
app = Flask(__name__)
app.config['dbconfig'] = {'host': '127.0.0.1',
'user': 'vsearch',
'password': 'vsearchpasswd',
'database': 'vsearchlogDB', }
def log_request(req: 'flask_request', res: str) -> None:
"""Журналирует вэб-запрос и возвращает результаты."""
with UseDatabase(app.config['dbconfig']) as cursor:
_SQL = """insert into log
(phrase, letters, ip, browser_string, result)
values
(%s, %s, %s, %s, %s)"""
cursor.execute(_SQL, (req.form['phrase'],
req.form['letters'],
req.remote_addr,
req.user_agent.browser,
res, ))
@app.route('/search4', methods=['POST'])
def do_search() -> 'html':
"""Extract the posted data; perform the search; return results."""
phrase = request.form['phrase']
letters = request.form['letters']
title = 'Here are your results:'
results = str(search4letters(phrase, letters))
log_request(request, results)
return render_template('results.html',
the_title=title,
the_phrase=phrase,
the_letters=letters,
the_results=results,)
@app.route('/')
@app.route('/entry')
def entry_page() -> 'html':
"""Display this webapp's HTML form."""
return render_template('entry.html',
the_title='Welcome to search4letters on the web!')
@app.route('/viewlog')
def view_the_log() -> 'html':
"""Выводит содержимое файла в виде HTML-таблицы."""
with UseDatabase(app.config['dbconfig']) as cursor:
_SQL = """ select phrase, letters, ip, browser_string, result
from vsearchlogDB.log"""
cursor.execute(_SQL)
contents = cursor.fetchall()
titles = ('Phrase','Letters', 'Remote_addr', 'User_agent', 'Results')
return render_template('viewlog.html',
the_title='View Log',
the_row_titles=titles,
the_data=contents,)
if __name__ == '__main__':
app.run(debug=True)
Python links
- Learn Python: https://pythonbasics.org/
- Python Tutorial: https://pythonprogramminglanguage.com