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

论坛 期权论坛 脚本     
匿名技术用户   2020-12-27 10:58   25   0

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

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

#encoding: utf-8

import os

# __file__ refers to the file settings.py
APP_ROOT = os.path.dirname(os.path.abspath(__file__))   # refers to application_top
APP_STATIC_TXT = os.path.join(APP_ROOT, 'static/txt') #设置一个专门的类似全局变量的东西

二、在需要的地方调用

#encoding: utf-8

from flask import render_template,session, redirect,request
from flask import url_for
import os
from 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!输出成功!

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP