Меню

App flask name ошибка

Reproducing the problem, and fixing it

Hello, I have reproduced the problem
This is the error code:

Error: Failed to find Flask application or factory in module
«src.app». Use «FLASK_APP=src.app:name to specify one.

Steps of reproducing the error:

  1. Create a file called app.py
  2. inside app.py put this code:
from flask import Flask

def create_app():
    app = Flask("abc")

    @app.route('/')
    def hello_world():
        return 'Hello, World!'

Or let the file be empty, like this:

# This is an empty file
# There is no flask application here
  1. Inside CLI run these commands:
export FLASK_APP=app.py
flask run
  1. watch the error appear on the screen

Solution 1 :

  1. make the function return the app
  2. Clearly create a variable called app and make it equal to the return value of the function, like this:

from flask import Flask
def create_app():
    app = Flask(__name__)
    @app.route('/')
    def hello_world():
        return 'Hello, World!'
    return app
app = create_app()

Solution 2: Get the app outside of the function:

from flask import Flask

app = Flask("abc")

@app.route('/')
def hello_world():
    return 'Hello, World!'

Environment data

VS Code version: 1.19.3
Python Extension version: 2018.1.0
Python Version: 3.6
OS and version: Ubuntu 17.10

Actual behavior

Error: Failed to find application in module «run». Are you sure it contains a Flask application? Maybe you wrapped it in a WSGI middleware or you are using a factory function.

Expected behavior

The flask app to begin running a localhost server.

Steps to reproduce:

  • Install Visual Studio Code
  • Install python extension
  • Update launch.json with the correct pythonPath and program settings for python.exe and flask.exe, respectively
  • Debug -> Start Debugging
  • Select «Python: Flask (0.11.x or later)» as the configuration
  • Press F5
  • Error message is printed and debugger doesn’t start

Settings

My launch.json «Python: Flask (0.11.x or later)» confugiration:

{
            "name": "Python: Flask (0.11.x or later)",
            "type": "python",
            "request": "launch",
            "stopOnEntry": false,
            "pythonPath": "${config:python.pythonPath}",
            "module": "flask",
            "cwd": "${workspaceRoot}",
            "env": {
                "FLASK_APP": "${workspaceFolder}/run.py"
            },
            "args": [
                "run",
                "--no-debugger",
                "--no-reload"
            ],
            "envFile": "${workspaceFolder}/.env",
            "debugOptions": [
                "RedirectOutput"
            ]
}

run.py file:

from module_test import create_app

if __name__ == '__main__':
    app = create_app('test', '')
    app.run(host='0.0.0.0', port=5000, debug=True)

__init.py__ file:

def create_app(config_file_name, chdir):
    app = Flask(__name__)
    return app

Logs

Output from Python output panel

Output from Console window (Help->Developer Tools menu)

Hi sorry to bother again, I’m working on my first flask project, very simple one.

I’m deploying my site on Digital Ocean, ubuntu server. And I complied with its instructions.

Problem:
When I tried to open the site in browser, it came with 500 error. Then I looked up the apache error log to find the following sentences.

Error log:

[Wed Dec 31 07:45:49 2014] [error] [client 112.64.71.131] mod_wsgi (pid=27835): Target WSGI script ‘/var/www/qianshan/qianshan.wsgi’ cannot be loaded as Python module.

[Wed Dec 31 07:45:49 2014] [error] [client 112.64.71.131] mod_wsgi (pid=27835): Exception occurred processing WSGI script ‘/var/www/qianshan/qianshan.wsgi’.

[Wed Dec 31 07:45:49 2014] [error] [client 112.64.71.131] Traceback (most recent call last):

[Wed Dec 31 07:45:49 2014] [error] [client 112.64.71.131] File «/var/www/qianshan/qianshan.wsgi», line 7, in

[Wed Dec 31 07:45:49 2014] [error] [client 112.64.71.131] from qianshan import app as application

[Wed Dec 31 07:45:49 2014] [error] [client 112.64.71.131] ImportError: cannot import name app

Tree structure of the project

spark@Qianshan:/var/www/qianshan$ tree -L 2
.
├── qianshan
│   ├── config.ini
│   ├── qianshan.py
│   ├── static
│   ├── templates
│   └── venv
└── qianshan.wsgi

Virtual Host configuration

<VirtualHost *:80>
            ServerName qianshan.co
            ServerAdmin spark@qianshan.co
            WSGIScriptAlias / /var/www/qianshan/qianshan.wsgi
            <Directory /var/www/qianshan/qianshan/>
                    Order allow,deny
                    Allow from all
            </Directory>
            Alias /static /var/www/qianshan/qianshan/static
            <Directory /var/www/qianshan/qianshan/static/>
                    Order allow,deny
                    Allow from all
            </Directory>
            ErrorLog ${APACHE_LOG_DIR}/error.log
            LogLevel warn
            CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

wsgi

#!/usr/bin/python
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/qianshan/")

from qianshan import app as application
application.secret_key = 'Add your secret key'

.py file

# Filename: qianshan.py
# encoding: utf-8

import ConfigParser
import codecs
from flask import Flask
from flask import render_template

app = Flask(__name__)

@app.route('/')
def index():
    block_list = getBlockList()
    website_dict = getWebsiteDict()
    return render_template('index.html', block_list=block_list, website_dict=website_dict)
...
...
if __name__ == '__main__':
    app.run()

Happy new year to all if you are lucky enough to see this bottom line ^_^

Hi sorry to bother again, I’m working on my first flask project, very simple one.

I’m deploying my site on Digital Ocean, ubuntu server. And I complied with its instructions.

Problem:
When I tried to open the site in browser, it came with 500 error. Then I looked up the apache error log to find the following sentences.

Error log:

[Wed Dec 31 07:45:49 2014] [error] [client 112.64.71.131] mod_wsgi (pid=27835): Target WSGI script ‘/var/www/qianshan/qianshan.wsgi’ cannot be loaded as Python module.

[Wed Dec 31 07:45:49 2014] [error] [client 112.64.71.131] mod_wsgi (pid=27835): Exception occurred processing WSGI script ‘/var/www/qianshan/qianshan.wsgi’.

[Wed Dec 31 07:45:49 2014] [error] [client 112.64.71.131] Traceback (most recent call last):

[Wed Dec 31 07:45:49 2014] [error] [client 112.64.71.131] File «/var/www/qianshan/qianshan.wsgi», line 7, in

[Wed Dec 31 07:45:49 2014] [error] [client 112.64.71.131] from qianshan import app as application

[Wed Dec 31 07:45:49 2014] [error] [client 112.64.71.131] ImportError: cannot import name app

Tree structure of the project

spark@Qianshan:/var/www/qianshan$ tree -L 2
.
├── qianshan
│   ├── config.ini
│   ├── qianshan.py
│   ├── static
│   ├── templates
│   └── venv
└── qianshan.wsgi

Virtual Host configuration

<VirtualHost *:80>
            ServerName qianshan.co
            ServerAdmin spark@qianshan.co
            WSGIScriptAlias / /var/www/qianshan/qianshan.wsgi
            <Directory /var/www/qianshan/qianshan/>
                    Order allow,deny
                    Allow from all
            </Directory>
            Alias /static /var/www/qianshan/qianshan/static
            <Directory /var/www/qianshan/qianshan/static/>
                    Order allow,deny
                    Allow from all
            </Directory>
            ErrorLog ${APACHE_LOG_DIR}/error.log
            LogLevel warn
            CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

wsgi

#!/usr/bin/python
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/qianshan/")

from qianshan import app as application
application.secret_key = 'Add your secret key'

.py file

# Filename: qianshan.py
# encoding: utf-8

import ConfigParser
import codecs
from flask import Flask
from flask import render_template

app = Flask(__name__)

@app.route('/')
def index():
    block_list = getBlockList()
    website_dict = getWebsiteDict()
    return render_template('index.html', block_list=block_list, website_dict=website_dict)
...
...
if __name__ == '__main__':
    app.run()

Happy new year to all if you are lucky enough to see this bottom line ^_^

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Apk add alpine desktop ошибка
  • Api яндекс директ ошибки