首页 技术 正文
技术 2022年11月24日
0 收藏 777 点赞 4,653 浏览 1851 个字

上一节总结了一个基本web应用的代码,这一节主要讲用户访问的数据记录在log文件中,并显示在页面上。

这节步骤:

  1. 按以下目录建好相应的文件夹及内容

webapp
|—-vsearch4web.py

|—-vsearch.log #自动创建的log文件,用于记录浏览器访问信息。
|—-static
|        |—-hf.css
|—-templates
|        |—-base.html  #基模板
|        |—-entry.html
|        |—-result.html

|        |—-Viewlog.html #查看日志文件

相比上一节,需要修改vsearch4web.py来将日志写入log文件,并新增Viewlog.html 来友好的显示结果。

修改后的vsearch4web.py

from flask import Flask, render_template, request, escape
from vsearch import search4lettersapp = Flask(__name__)# 写日志文件,同一个请求的不同信息以'|'分隔。
def log_request(req: 'flask_request', res: str) ->None:
with open('vsearch.log', 'a') as log:
print(req.form, req.remote_addr, req.user_agent, res, file=log, sep='|')@app.route('/search4', methods=['GET', 'POST'])
def do_search() -> 'html':
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('result.html', the_title=title, the_phrase=phrase, the_letters=letters, the_results=results)@app.route('/')
@app.route('/entry')
def entry_page() -> 'html':
return render_template('entry.html', the_title='Welcome to this Web!')@app.route('/viewlog')
def view_the_log() -> str:
contents = []
#读取日志文件,并读取为嵌套列表,便于以表格样式显示结果。
with open('vsearch.log') as log:
for line in log:
contents.append([])
for item in line.split('|'):
contents[-1
].append(escape(item))
titles = ('Form data', '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)

新增的Viewlog.html

{% extends 'base.html' %}{% block body %}<h2>{{the_title}}</h2><table>
<tr>
{% for row_title in the_row_titles %}
<th>{{row_title}}</th>
{% endfor %}
</tr>
{% for log_row in the_data %}
<tr>
{% for item in log_row %}
<td>{{item}}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
{% endblock %}

2. 启动服务器,并访问页面http://127.0.0.1:5000/,输入要查询的英文句子后,点击do it.随后访问http://127.0.0.1:5000/ viewlog.html可以查看到访问信息。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,945
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,471
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,284
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,100
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,732
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,767