Flask成长笔记--如何在Flask框架里面读写文本文件

来源:互联网 发布:int java 编辑:程序博客网 时间:2024/06/06 00:08

 我想在Flask中读取日志的文本文件,然后将读取的信息显示到网页上去形成一个管理的网页。真的是为了解决这个问题,要了半条命啊!特意记下了。
参考:https://stackoverflow.com/questions/14825787/flask-how-to-read-a-file-in-application-root

一、设置根目录
 我在工程项目中有一个专门的configure.py,用于写全局的配置。
我的文本文件在工程目录的static/txt中

#encoding: utf-8import os# __file__ refers to the file settings.pyAPP_ROOT = os.path.dirname(os.path.abspath(__file__))   # refers to application_topAPP_STATIC_TXT = os.path.join(APP_ROOT, 'static/txt') #设置一个专门的类似全局变量的东西

二、在需要的地方调用

#encoding: utf-8from flask import render_template,session, redirect,requestfrom flask import url_forimport osfrom config import APP_STATIC_TXT#这里测试一下读文本文件输出@main.route('/monitor_test', methods=['GET', 'POST'])def monitor_test():    with open(os.path.join(APP_STATIC_TXT, 'text.txt')) as f:        s=f.read(5) #读取前五个字节        f.close()    return 'ok'+str(s)

nice!输出成功!

原创粉丝点击