首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在命令行参数上键入"gunicorn :application --preload -b 0.0.0.0:5000“时出错

在命令行参数上键入"gunicorn :application --preload -b 0.0.0.0:5000“时出错
EN

Stack Overflow用户
提问于 2020-04-25 00:19:20
回答 1查看 952关注 0票数 0

当我在我的终端命令行上运行这个命令时:

代码语言:javascript
运行
复制
gunicorn app:application --preload -b 0.0.0.0:5000 

我收到以下错误:

代码语言:javascript
运行
复制
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'

当我转到错误文件时,我有:

代码语言:javascript
运行
复制
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

我真的不知道这是怎么回事,也不知道为什么我会收到这个错误。我从python 2转到python 3,我正在重新安装所有的模块和包,但是这个错误突然出现了。提前感谢

这是我的目录树:

代码语言:javascript
运行
复制
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

App.py的一部分:

代码语言:javascript
运行
复制
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)
代码语言:javascript
运行
复制
EN

Stack Overflow用户

回答已采纳

发布于 2020-04-25 03:05:27

这是执行命令gunicorn app:application --preload -b 0.0.0.0:5000中的错误

独角兽的文档(https://docs.gunicorn.org/en/stable/run.html)说

代码语言:javascript
运行
复制
gunicorn [OPTIONS] APP_MODULE

其中APP_MODULE是$(MODULE_NAME):$(VARIABLE_NAME),您的模块名称是app,但您的变量名称不是app,它也是app。

因此,正确的命令是

代码语言:javascript
运行
复制
gunicorn app:app --preload -b 0.0.0.0:5000
票数 3
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61412843

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档