Bootstrap FreeKB - Flask - Read a file in Python Flask
Flask - Read a file in Python Flask

Updated:   |  Flask articles

Flask uses the MVC (Model View Controller) Framework. Just to make this as obvious as possible, I like my Flask apps to have the following.

  • Model -> models.py
  • View -> views.py
  • Controller -> __init__.py

Let's say your Flask application has the following structure. Notice in this example there is a properties.txt file.

├── main.py
├── database (directory)
│   ├── example.db
├── my-project (directory)
│   ├── __init__.py
│   ├── views.py
│   ├── models.py
│   ├── templates (directory)
│   │   ├── base.html
│   │   ├── home.html
│   │   ├── results.html
│   └── static (directory)
│       └── custom.css
│       └── properties.txt

 

Let's say properties.txt contains key value pairs.

ip=127.0.0.1

 

In your view (views.py in this example), here is how you could store the value of each value. In this example, the "ip" variable should contain the value in the properties.txt file (127.0.0.1).

import os
from flask import Blueprint, render_template

views = Blueprint('views', __name__)

@views.route('/')
def home():
    basedir = os.path.abspath(os.path.dirname(__file__))
    prop_file = os.path.join(basedir, 'static/files/properties.txt')

    if os.path.exists(prop_file ) == False:
        print(f"{json_file} does NOT exist")
        flash('Sorry. Something got totally hosed up on my end. Try again?', category='danger')
        return render_template('mybad.html')

    if os.path.isfile(prop_file ) == False:
        print(f"{prop_file} is NOT a file")
        flash('Sorry. Something got totally hosed up on my end. Try again?', category='danger')
        return render_template('mybad.html')

    if os.access(prop_file , os.R_OK) == False:
        print(f"{prop_file is NOT readable")
        flash('Sorry. Something got totally hosed up on my end. Try again?', category='danger')
        return render_template('mybad.html')

    with open(prop_file, "r") as file:
        for line in file.readlines():
            if "ip" in line:
                line = re.sub("ip=", "", line)
                ip = line.strip()
                print("IP = " + ip)

    return render_template('home.html')

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 8686c7 in the box below so that we can be sure you are a human.