user12970247
user12970247

Reputation:

Error when typing: "gunicorn app:application --preload -b 0.0.0.0:5000" on command line argument

When I run this on my terminal command line:

gunicorn app:application --preload -b 0.0.0.0:5000 

I am getting the following error:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/gunicorn/util.py", line 401, in import_app
    app = getattr(mod, name)
AttributeError: module 'app' has no attribute 'application'

And when I go to the errror file, I have:

def import_app(module):
    parts = module.split(":", 1)
    if len(parts) == 1:
        obj = "application"
    else:
        module, obj = parts[0], parts[1]

    try:
        mod = importlib.import_module(module)
    except ImportError:
        if module.endswith(".py") and os.path.exists(module):
            msg = "Failed to find application, did you mean '%s:%s'?"
            raise ImportError(msg % (module.rsplit(".", 1)[0], obj))
        raise

    # Parse obj as a single expression to determine if it's a valid
    # attribute name or function call.
    try:
        expression = ast.parse(obj, mode="eval").body
    except SyntaxError:
        raise AppImportError(
            "Failed to parse %r as an attribute name or function call." % obj
        )

    if isinstance(expression, ast.Name):
        name = expression.id
        args = kwargs = None
    elif isinstance(expression, ast.Call):
        # Ensure the function name is an attribute name only.
        if not isinstance(expression.func, ast.Name):
            raise AppImportError("Function reference must be a simple name: %r" % obj)

        name = expression.func.id

        # Parse the positional and keyword arguments as literals.
        try:
            args = [ast.literal_eval(arg) for arg in expression.args]
            kwargs = {kw.arg: ast.literal_eval(kw.value) for kw in expression.keywords}
        except ValueError:
            # literal_eval gives cryptic error messages, show a generic
            # message with the full expression instead.
            raise AppImportError(
                "Failed to parse arguments as literal values: %r" % obj
            )
    else:
        raise AppImportError(
            "Failed to parse %r as an attribute name or function call." % obj
        )

    is_debug = logging.root.level == logging.DEBUG
    try:
        app = getattr(mod, name)
    except AttributeError:
        if is_debug:
            traceback.print_exception(*sys.exc_info())
        raise AppImportError("Failed to find attribute %r in %r." % (name, module))

    # If the expression was a function call, call the retrieved object
    # to get the real application.
    if args is not None:
        try:
            app = app(*args, **kwargs)
        except TypeError as e:
            # If the TypeError was due to bad arguments to the factory
            # function, show Python's nice error message without a
            # traceback.
            if _called_with_wrong_args(app):
                raise AppImportError(
                    "".join(traceback.format_exception_only(TypeError, e)).strip()
                )

            # Otherwise it was raised from within the function, show the
            # full traceback.
            raise

    if app is None:
        raise AppImportError("Failed to find application object: %r" % obj)

    if not callable(app):
        raise AppImportError("Application object must be callable.")
    return app

I don´t really know what´s going here and why I am getting this error. I passed from python 2 to python 3 and I am reinstalling all the modules and packages but this error suddenly appeared. Thanks in advance

This is my directory tree:

FontsFree-Net-SFProDisplay-Bold.ttf
├── Procfile
├── __pycache__
├── app.py
├── contactbook.db
├── db.sqlite3
├── flask
│   ├── bin
│   ├── lib
│   └── pyvenv.cfg
├── helpers.py
├── requirements.txt
├── runtime.txt
├── socialauthphp
│   ├── App
│   ├── assets
│   ├── composer.json
│   ├── composer.lock
│   ├── hydridauth.php
│   ├── index.php
│   ├── logout.php
│   └── vendor
├── static
│   ├── Contacto.vcf
│   ├── icons
│   ├── img
│   ├── main.css
│   └── qr
└── templates
    ├── contact.html
    ├── index.html
    ├── layout.html
    ├── login.html
    ├── profile.html
    ├── qrcode.html
    ├── register.html
    └── view.html

part of app.py:

import os
import vobject
from werkzeug.datastructures import FileStorage
from werkzeug.utils import secure_filename
from flask_qrcode import QRcode
from django.core.exceptions import ValidationError
from django import forms
from flask_login import UserMixin
from flask import Flask
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileAllowed, FileRequired
from flask_uploads import UploadSet, configure_uploads, IMAGES, patch_request_class
from wtforms import SubmitField
from flask_login import LoginManager, login_required, login_user, current_user, login_manager
from flask import Flask, flash, jsonify, redirect, render_template, request, session, url_for
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
from flask import Flask
from tempfile import mkdtemp
from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError
from werkzeug.security import check_password_hash, generate_password_hash
from helpers import login_required

import sys


app = Flask(__name__)
login = LoginManager(app)
QRcode(app)

app.config["TEMPLATES_AUTO_RELOAD"] = True


# Ensure responses aren't cached
@app.after_request
def after_request(response):
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    response.headers["Expires"] = 0
    response.headers["Pragma"] = "no-cache"
    return response


app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///contactbook.db'
app.config["SESSION_FILE_DIR"] = mkdtemp()
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)

db = SQLAlchemy(app)
``````

Upvotes: 0

Views: 2323

Answers (1)

Nivardo Albuquerque
Nivardo Albuquerque

Reputation: 536

It is an error in your execution command gunicorn app:application --preload -b 0.0.0.0:5000

The gunicorn's docs (https://docs.gunicorn.org/en/stable/run.html) says that

gunicorn [OPTIONS] APP_MODULE

where APP_MODULE is $(MODULE_NAME):$(VARIABLE_NAME), your module name is app but your variable name is not application, it is also app.

so, the correct command is

gunicorn app:app --preload -b 0.0.0.0:5000

Upvotes: 3

Related Questions