当前位置: 首页 > 知识库问答 >
问题:

运行flask app时出现“flask.cli.NoAppException”

罗翰
2023-03-14

我对python开发相当陌生,对flask一无所知,我被分配了一个使用flask开发的项目。经过几周的工作,我现在能够解决所有的依赖关系和项目现在编译成功。但当我使用flask run运行项目,然后在浏览器中输入url时,它抛出“flask.cli.NoAppException”。我怎么能像这样运行我的项目呢。

>

  • 设置FLASK_APP=init.py
  • 设置FLASK_ENV=开发
  • 烧瓶运行

    • 服务烧瓶应用程序init.py(延迟加载)
    • 环境:发展
    • 调试模式:开启
    • 重新启动stat
    • 调试器已激活!
    • 调试器引脚:202-733-235
    • 运行在http://127.0.0.1:5000/(按CTRLC退出)

    这是回溯

    "FLASK_APP=myappnam:name to specify one.
    Traceback (most recent call last)
    
        File "C:\Program Files\Python38\Lib\site-packages\flask\_compat.py", line 39, in reraise
    
        raise value
    
        File "C:\Program Files\Python38\Lib\site-packages\flask\cli.py", line 97, in find_best_app
    
        raise NoAppException(
    
        flask.cli.NoAppException: Failed to find Flask application or factory in module "myappnam". Use "FLASK_APP=myappnam:name to specify one.
    
    The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error.
    
    To switch between the interactive traceback and the plaintext one, you can click on the "Traceback" headline. From the text traceback you can also create a paste of it. For code execution mouse-over the frame you want to debug and click on the console icon on the right side.
    
    You can execute arbitrary Python code in the stack frames and there are some extra helpers available for introspection:
    
        dump() shows all variables in the frame
        dump(obj) dumps all that's known about the object
    

    这是我的--init--。py文件

    import os
    import logging
    import gevent
    import datetime
    import rollbar
    
    from gevent.queue import Queue
    from gevent.event import AsyncResult
    import zmq.green as zmq
    
    from werkzeug.contrib.fixers import ProxyFix
    
    # Greens the postgress connector
    try:
        import psycogreen.gevent
        psycogreen.gevent.patch_psycopg()
    except ImportError:
        pass
    
    from rauth.service import OAuth2Service
    
    from flask import Flask, Request
    from flask_sqlalchemy import SQLAlchemy
    from flask_bcrypt import Bcrypt
    from flask_login import LoginManager, current_user
    from flask_assets import Environment
    from flask_uploads import UploadSet, configure_uploads, IMAGES
    
    from app.util import setup_logging
    from app.exceptions import TimeoutError, BackendError
    import app.exceptions
    
    
    flask_app = None
    
    # Have to use an actor pattern because we cannot allow more than one request to
    # be pending at a time.
    class Backend(gevent.Greenlet):
        def __init__(self):
            super(Backend, self).__init__()
    
            self.inbox = Queue()
            self.zmq_context = zmq.Context()
            self.zmq_socket = None
            self.init_socket()
    
        def init_socket(self):
            zmq_socket = self.zmq_socket
            if zmq_socket is not None:
                zmq_socket.close(0)
    
            zmq_socket = self.zmq_context.socket(zmq.REQ)
            zmq_socket.connect(flask_app.config["SERVER_ZMQ_URI"])
            self.zmq_socket = zmq_socket
    
        def process(self, request):
            zmq_socket = self.zmq_socket
    
            poller = zmq.Poller()
            poller.register(zmq_socket, zmq.POLLIN)
    
            zmq_socket.send_json({
                "command": request["command"],
                "arguments": request["arguments"]
            })
            sockets = dict(poller.poll(10 * 1000))
    
            if zmq_socket not in sockets:
                self.init_socket()
                result = request["result"]
                result.set_exception(TimeoutError("The request to the backend timed out."))
                return
    
            received = zmq_socket.recv_json()
    
            result = request["result"]
            if received["success"]:
                result.set(received["result"])
            else:
                result.set_exception(BackendError(received["result"]))
    
        def _run(self):
            while True:
                self.process(self.inbox.get())            
    
        def send(self, command, **kwargs):
            result = AsyncResult()
            self.inbox.put({
                "command": command,
                "arguments": kwargs,
                "result": result
            })
            return result.get()
    
    
    class RollbarRequest(Request):
        @property
        def rollbar_person(self):
            if current_user.is_anonymous:
                return {
                    "id": 0, 
                    "username": "anonymous"
                }
            return {
                "id": current_user.id,
                "username": current_user.name,
                "email": current_user.email_address
            }
    
    
    def create_app(*args, **kwargs):
        global flask_app
        global l
    
        app_mode = os.environ.get("APP_MODE")
    
        assert app_mode is not None, "APP_MODE environment variable must be set"
    
        flask_app = Flask(__name__)
        flask_app.request_class = RollbarRequest
        flask_app.config.from_object("config.mode_{}".format(app_mode))
        flask_app.config["APP_MODE"] = app_mode
    
        setup_logging(flask_app.config["LOGGING_LEVEL"])
    
        l = logging.getLogger(__name__)
        l.info("starting in mode {}".format(app_mode))
    
        if not flask_app.config["DEBUG"]:
            rollbar.init(
                flask_app.config["ROLLBAR_API_KEY"],
                app_mode,
                allow_logging_basic_config=False
            )
    
        flask_app.jinja_env.globals.update(
            current_year=lambda: datetime.datetime.now().year
        )
    
        # Have to do this so that redirects work in proxy mode behind NGINX.
        if not flask_app.debug:
            flask_app.wsgi_app = ProxyFix(flask_app.wsgi_app)
    
        flask_app.db = SQLAlchemy(flask_app)
    
        flask_app.bcrypt = Bcrypt(flask_app)
        flask_app.assets = Environment(flask_app)
    
        flask_app.images = UploadSet("images", IMAGES)
        configure_uploads(flask_app, flask_app.images)
    
        flask_app.photos = UploadSet("photos", IMAGES)
        configure_uploads(flask_app, flask_app.photos)
    
        login_manager = LoginManager()
        login_manager.login_view = "signin"
        login_manager.login_message_category = "alert"  # Need newer release of Flask-Login for this to work.
        login_manager.init_app(flask_app)
    
        flask_app.facebook = OAuth2Service(
            name="facebook",
            base_url="https://graph.facebook.com/v2.8/",
            client_id=flask_app.config["FACEBOOK_CLIENT_ID"],
            client_secret=flask_app.config["FACEBOOK_CLIENT_SECRET"]
        )
    
        from app import views
        from app import models
        from app import commands
    
        flask_app.backend = Backend()
        flask_app.backend.start()
    
        app.exceptions.register(flask_app)
    
        return flask_app
    

  • 共有1个答案

    敖毅
    2023-03-14

    在您的create_app函数中,您可能不想使用全局关键字来延迟应用程序的初始化。

    在您提供的示例中,从未调用创建应用程序函数,因此从未创建应用程序实例。更常见的做法是使用如下创建应用程序功能:

    def create_app():
        app = flask.Flask(__name__)
        # do some setup
        return app
    
    app = create_app()
    

    应用程序实例也应称为app,而不是flask\u app。当然,你可以随意调用它,但默认情况下,flask会查找app。指定您自己的更改。pytoFLASK\u APP=\uu init\uu:FLASK\u APP

     类似资料:
    • 我在上面有一个问题:我使用了提供的答案,但仍然击中了一个对象错误。你能看到我错过了什么吗?我在“cash_sheet.range(”C8“).pastespecial xlpastevalues”处找到了错误

    • 在我的环境中设置了JAVA_HOME之后,我在运行pig时得到了以下结果: 当我这么做的时候: 但是在我的环境中,JAVA_HOME是这样设置的: 运行于:Ubuntu 10.04.4 LTS java:java版本“1.6.0_21”Hadoop版本:Hadoop-0.20.203 PIG版本:PIG-0.11.1 env:term=Xterm shell=/bin/bash xdg_sessi

    • 代码: pom.xml依赖项: 我不明白发生了什么事,有人能帮忙吗?

    • 问题内容: 我正在使用Java Jersey框架(与Maven),并使用IntelliJ作为我的IDE。我遇到了这个运行时异常,仅当我尝试从命令行运行代码(使用maven进行编译,然后使用java -jar)时才发生,而在IntelliJ中运行时却没有发生。 我有一些Java代码,这些代码将尝试在某个远程URL上进行HTTP GET,并尝试将返回的JSON读取到某些Lombok POJO中: 我不

    • 问题内容: 我正在使用gradle作为JavaFX插件。即使在 distribution /下 构建和运行可执行文件之后,一切都可以完美运行,但只有一类: 为了多种目的,我创建了以下对象: 在IDE中运行该程序没问题,一切正常。但是,如果我构建并尝试运行.exe文件,则会得到以下-StackTrace: 我真的不明白。怎么可能找不到这个类,而我所有其他的类却都找不到呢? 我的build.gradl

    • 问题内容: 我已经创建了自己的文件,并通过将其设置为系统类加载器。它已经初始化,并且一切正常,但是找不到我要加载的类。这是: 我已确认该罐子存在,并且路径正确。这是我在程序中如何称呼它: 这是我得到的例外(第166行是指我尝试创建新行的行: 我什至尝试像这样显式加载类: 是什么原因造成的?它不应该“正常工作”吗? 更新: 这是来自的重要代码 更新2: 这是一个SSCCE:http : //nucl