0
votes

I am fairly new to python development and have no idea about flask, I have been assigned a project that is developed using flask. After working for couple of weeks i am now able to resolve all the dependencies and project is now compiled successfully. But when I run the project using flask run and then enter the url in browser it throws "flask.cli.NoAppException". How can I run my project I have tried like this.

  1. set FLASK_APP=init.py
  2. set FLASK_ENV=develpment
  3. flask run

    • Serving Flask app "init.py" (lazy loading)
    • Environment: develpment
    • Debug mode: on
    • Restarting with stat
    • Debugger is active!
    • Debugger PIN: 202-733-235
    • Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

here is the trackback

"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

here is my --init--.py file

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

and this is my project structure project structure I am using pycharm and widows 10.

1

1 Answers

1
votes

In your create_app function you probably do not want to use the global keyword for late initialisation of the app.

In the examples you provided the create_app function is never called, and so the app instance is never created. It is more common to use the create_app function as follows:

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

app = create_app()

The app instance should also be called app and not flask_app. Of course you can call it whatever you want, but by default flask looks for app. To specify your own change FLASK_APP=__init__.py to FLASK_APP=__init__:flask_app