Home > Software engineering >  Can not import app from __init__.pt file in flask project to use app.config
Can not import app from __init__.pt file in flask project to use app.config

Time:12-07

I have a flask application with an init.py. In the create_app function, I have set app.config['UPLOAD_FOLDER']. I need to import app into my post.py file that has the routes which will be uploading and downloading files from. I am getting issues with every type of import I try.

init.py:

from flask import Flask, session, redirect, url_for
from bson.objectid import ObjectId
from pymongo import MongoClient
from os import path, mkdir
from flask_login import LoginManager

client = MongoClient()
db = client.Contractor 

def create_app():
  app = Flask(__name__)
  app.config['SECRET_KEY'] = '' 
  upload_folder = 'uploads/'
  if not path.exists(upload_folder):
    mkdir(upload_folder)

  from .views import views
  from .auth import auth
  from .post import post

  app.config['MAX_CONTENT_LENGTH'] = 1 * 1024 * 1024
  app.config['UPLOAD_FOLDER'] = upload_folder
  app.register_blueprint(views, url_prefix='/')
  app.register_blueprint(auth, url_prefix='/auth/')
  app.register_blueprint(post, url_prefix='/post/')

  return app

post.py:

from flask import Blueprint, render_template, request, flash, redirect, url_for, session
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from werkzeug.utils import secure_filename
from . import db
from bson.objectid import ObjectId
from os import path, mkdir

@post.route('/upload', methods=['GET', 'POST'])
def create_post():
  if 'username' in session:
    current_user = db.users.find_one({ 'username' : session['username']})
    if request.method == 'POST':
      data = request.form 
      photo = request.files['photo']
      print(photo)
 ---->photo.save(path.join(app.config['UPLOAD_FOLDER'], secure_filename(photo.filename)))
      caption = data.get('caption')
      location = data.get('location')

how can I import app from init.py

CodePudding user response:

I think you can import app where you import db.

from . import app, db

  • Related