Pytest-Flask Cannot import name 'create_app' - python

Trying to run a basic functional test with pytest-flask but keep getting this error:
tests/conftest.py:2: in <module>
from learning_flashcards import create_app
E ImportError: cannot import name 'create_app'
Here is my directory structure:
.
├── Procfile
├── __pycache__
├── config.py
├── learning_flashcards
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-36.pyc
│   │   ├── app.cpython-36.pyc
│   │   └── views.cpython-36.pyc
│   ├── app.py
│   ├── db.py
│   ├── models.py
│   ├── static
│   │   └── style.css
│   ├── templates
│   └── views.py
├── learning_flashcards.egg-info
│   ├── PKG-INFO
│   ├── SOURCES.txt
│   ├── dependency_links.txt
│   ├── requires.txt
│   └── top_level.txt
├── manage.py
├── migrations
│   ├── README
│   ├── alembic.ini
│   ├── env.py
│   ├── script.py.mako
│   └── versions
├── requirements
│   ├── common.txt
│   ├── dev.txt
│   └── runtime.txt
├── requirements.txt
├── setup.py
├── tests
│   ├── __pycache__
│   │   ├── conftest.cpython-36-pytest-5.4.3.pyc
│   │   ├── test_data.cpython-36-pytest-5.4.3.pyc
│   │   └── test_site.cpython-36-pytest-5.4.3.pyc
│   ├── conftest.py
│   ├── test_data.py
│   └── test_site.py
└── venv
And here is my conftest.py file:
import pytest
from learning_flashcards import create_app
#pytest.fixture
def app():
app = create_app()
return app
Have tried various ways of exploring the import system (from .learning_flashcards, from .learning_flashcards.learning_flashcards, etc.), have also investigated the init file to see if it is not creating the app instance correctly, but it looks to be fine. App runs on local server but can't get test suite to work.
Here's init.py:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
import learning_flashcards.views
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres#localhost/flashcards'
db = SQLAlchemy()
And app.py:
from flask import Flask
from models import db
def create_app():
app = Flask(__name__)
db.init_app(app)
#app.route('/')
def learning_flashcards():
return "Hello World!"
POSTGRES = {
'user': 'postgres',
'pw': 'password',
'db': 'my_database',
'host': 'localhost',
'port': '5432',
}
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://%(user)s:%(pw)s#%(host)s:%(port)s/%(db)s' % POSTGRES
return app
if __name__ == '__main__':
app = create_app()
app.run()

Related

Relative import error with flask

According to this, I am trying to run my flask web application from my com_profiler directory as python -m api.index, python -m api.index.py, python api/index.py. But none of these are working. The errors I am getting are in the order -
-> ValueError: attempted relative import beyond top-level package
-> attempted relative import beyond top-level package
-> SystemError: Parent module '' not loaded, cannot perform relative import
Directory Structure:
comp_profiler/
├── api
│   ├── bootstrap.sh
│   ├── index.py
│   └── __init__.py
├── __init__.py
├── pipelines.py
├── random_useragent.py
├── requirements.txt
├── scrapy.cfg
├── spiders
│   ├── __init__.py
│   ├── content_handler.py
│   ├── core_spider.py
│   ├── middlewares.py
│   ├── scrapper
│   │   ├── __init__.py
│   │   ├── corporatedir.py
│   │   ├── craft.py
│   │   ├── tofler.py
│   │   └── zaubacorp.py
│   ├── scrapper.py
│   ├── seed_list_generator.py
│   ├── settings.py
│   └── utility.py
index.py
from flask import Flask, request, jsonify
from ..spiders.seed_list_generator import SeedListGenerator
app = Flask(__name__)
#app.route("/start-spider")
def hello_world():
spider = SeedListGenerator()
company_name = request.get_json()
print(company_name)
return "Hello world"
if __name__ == "__main__":
app.run()
I also tried running it from api directory, but no success.
Kindly let me know if I am missing something with flask setup, as I am just starting up with flask.
Update: I want to integrate SeedListGenerator as API call. Kindly suggest.
Thanks in advance.

Gunicorn ImportError: No module name myApp

I am trying to deploy my code on Heroku but gunicorn is giving error ImportError: No module named inventory.
My Directory Structure
--server
|
|--server
├── __init__.py
├── home
│   ├── __init__.py
│   ├── admin.py
│   ├── migrations
│   │   ├── __init__.py
│   ├── models.py
│   ├── tests.py
│   ├── views.py
├── inventory
│   ├── __init__.py
│   ├── admin.py
│   ├── migrations
│   │   ├── 0001_initial.py
│   │   ├── __init__.py
│   ├── models.py
│   ├── serializer.py
│   ├── tests.py
│   ├── views.py
├── manage.py
└── server
├── __init__.py
├── settings.py
├── urls.py
├── wsgi.py
wsgi.py
import os
from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.server.settings")
application = get_wsgi_application()
application = DjangoWhiteNoise(application)
Basically my main server Django project is in /server/server/settings.py
Need Help here
The DJANGO_SETTINGS_MODULE parameter should be set from the root of your project, that should be:
os.environ.setdefault("DJANGO_SETTINGS_MODULE",
"server.settings")

Running unit tests on the "Flaskr" tutorial micro-blogging app in Flask

I've cloned the flaskr application from Github and am trying to follow the Testing Flask Applications tutorial. Following Bonus: Testing the Application, I've added a subdirectory test to the top-level flaskr directory, so that my directory tree looks like this:
.
├── build
│   ├── bdist.linux-x86_64
│   └── lib.linux-x86_64-2.7
│   └── flaskr
│   ├── flaskr.py
│   ├── __init__.py
│   ├── schema.sql
│   ├── static
│   │   └── style.css
│   └── templates
│   ├── layout.html
│   ├── login.html
│   └── show_entries.html
├── dist
│   └── flaskr-0.0.0-py2.7.egg
├── flaskr
│   ├── flaskr.db
│   ├── flaskr.py
│   ├── flaskr.pyc
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── schema.sql
│   ├── static
│   │   └── style.css
│   └── templates
│   ├── layout.html
│   ├── login.html
│   └── show_entries.html
├── flaskr.egg-info
│   ├── dependency_links.txt
│   ├── PKG-INFO
│   ├── requires.txt
│   ├── SOURCES.txt
│   └── top_level.txt
├── MANIFEST.in
├── README
├── setup.cfg
├── setup.py
├── test
│   └── test_flaskr.py
└── tests
└── test_flaskr.py
Note that there are also 'built-in' tests in the directory tests; however, I'm writing tests in test_flaskr.py in the directory tests. So far I'm trying just one test:
import os
import flaskr
import unittest
import tempfile
class FlaskrTestCase(unittest.TestCase):
def setUp(self):
self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()
flaskr.app.config['TESTING'] = True
self.app = flaskr.app.test_client()
with flaskr.app.app_context():
flaskr.init_db()
def tearDown(self):
os.close(self.db_fd)
os.unlink(flaskr.app.config['DATABASE'])
def test_empty_db(self):
rv = self.app.get('/')
assert b'No entries here so far' in rv.data
if __name__ == '__main__':
unittest.main()
However, if I try to run this I get the following error:
Traceback (most recent call last):
File "/home/kurt/dev/scratch/flask/examples/flaskr/test/test_flaskr.py", line 13, in setUp
flaskr.init_db()
AttributeError: 'module' object has no attribute 'init_db'
I don't understand this error. My flaskr.py is the same as the one on https://github.com/pallets/flask/blob/master/examples/flaskr/flaskr/flaskr.py and has an init_db function defined. How can I make the unit test run?
When you import the flaskr package in your script, you can access the variables, functions etc. declared and defined in flaskr/__init__.py
init_db is not defined in flask/__init__.py, the code provided, expects init_db to be defined in flask/__init__.py.
There are two ways to fix the issue you have:
Replace flaskr.init_db() with flaskr.flaskr.init_db()
Modify the import statement in test_flaskr.py as follows:
Change import flaskr to from flaskr import flaskr

Flask: app.register_blueprint works fine when run using the builtin app.run. However fails when tied to apache

Flask: app.register_blueprint works fine when run using the builtin app.run. However fails when tied to apache. I am getting a 404 error when I access the url
http://ipadddress/register - 404 Not Found
I have setup a Flask App with Apache2 and wsgi configuration. Below is the code. I have done the apache setup using Digital Ocean - Apache Flask configuration on debian systems
init.py
from flask import Flask, render_template
from register.registeration import account_api
app = Flask(__name__)
app.register_blueprint(account_api)
#app.route('/')
def home():
return render_template('index.html')
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8080, debug=True)
register/registration.py
from flask import Blueprint, render_template
account_api = Blueprint('account_api', __name__)
#account_api.route('/register')
def register():
return render_template('register.html')
flaskapp.wsgi
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/home/pi/ReSTServices/env/")
from FlaskApp import app as application
application.secret_key = 'MyHappyNewsWithHacker'
Project Structure
├── flaskapp.wsgi
├── __init__.py
├── register
│   ├── __init__.py
│   └── registeration.py
├── static
│   └── dist
│   ├── css
│   │   ├── bootstrap.css
│   │   ├── bootstrap.css.map
│   │   ├── bootstrap.min.css
│   │   ├── bootstrap.min.css.map
│   │   ├── bootstrap-theme.css
│   │   ├── bootstrap-theme.css.map
│   │   ├── bootstrap-theme.min.css
│   │   ├── bootstrap-theme.min.css.map
│   │   ├── font-awesome.min.css
│   │   ├── sticky_footer.css
│   │   └── style.css
│   ├── fonts
│   │   ├── FontAwesome.otf
│   │   ├── fontawesome-webfont.eot
│   │   ├── fontawesome-webfont.svg
│   │   ├── fontawesome-webfont.ttf
│   │   ├── fontawesome-webfont.woff
│   │   ├── fontawesome-webfont.woff2
│   │   ├── glyphicons-halflings-regular.eot
│   │   ├── glyphicons-halflings-regular.svg
│   │   ├── glyphicons-halflings-regular.ttf
│   │   ├── glyphicons-halflings-regular.woff
│   │   └── glyphicons-halflings-regular.woff2
│   ├── img
│   │   └── rpi.png
│   └── js
│   ├── bootstrap.js
│   ├── bootstrap.min.js
│   └── npm.js
└── templates
├── index.html
└── register.html

Flask importing files through Pycharm

Following microblog tutorial on Flask: http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
In Pycharm, no matter how I structure or name the files, I cannot get the dev server to run if I separate the code and import the files. I also can't get it to inherit the codes no matter where I move the init, views, run files. The only way for me to get the server to run is to have all the commands execute on the same file. What am I doing wrong?
I have it setup as:
Project 1 > app(directory) > tmp(directory) > run.py(file)
app(directory) > static(directory) > templates(directory) > init.py(file) > views.py(file) (I have tried different arrangements.)
Inside views.py:
from app import app
Inside run.py:
from app import app
Inside init.py:
from flask import Flask
from app import views
(I have tried many different combinations such as from app import app.views. from app import views as app_views. I have also tried renaming the directories/files, nothing is working.)
Build the new project with PyCharm, it will create a virtual environment for you. Then put these into a run.py in a root of your
a project like that (don't forget to turn debugging mode off in prod)
from app import create_app
app = create_app()
if __name__ == '__main__':
app.run(debug=True)
Set up init.py file inside you 'app':
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)
bcrypt.init_app(app)
login_manager.init_app(app)
mail.init_app(app)
Store your credentials into Config class:
class Config:
SECRET_KEY = 'your key... '
SQLALCHEMY_DATABASE_URI = 'your db...'
SQLALCHEMY_TRACK_MODIFICATIONS = False
MAIL_SERVER = 'smtp.google.com'
MAIL_PORT = 587
MAIL_USE_TLS = True
MAIL_USERNAME = 'your email'
MAIL_PASSWORD = 'email password'
Structure your project, placing an empty init.py into each directory( accordingly to your architecture). Here is an example below, how to structure your project in Flask. It runs with no problem on
.
├── README.md
├── app
│   ├── __init__.py
│   ├── config.py
│   ├── errors
│   │   ├── 403.html
│   │   ├── 404.html
│   │   ├── 500.html
│   │   ├── __init__.py
│   │   └── handlers.py
│   ├── main
│   │   ├── __init__.py
│   │   └── routes.py
│   ├── models.py
│   ├── posts
│   │   ├── __init__.py
│   │   ├── forms.py
│   │   └── routes.py
│   ├── site.db
│   ├── static
│   │   ├── main.css
│   │   └── profile_pics
│   │   ├── 3c4feb2bb50d90df.png
│   │   ├── ba3d328163a8125e.png
│   │   └── default.jpg
│   ├── templates
│   │   ├── about.html
│   │   ├── account.html
│   │   ├── create_post.html
│   │   ├── home.html
│   │   ├── layout.html
│   │   ├── login.html
│   │   ├── post.html
│   │   ├── register.html
│   │   ├── reset_request.html
│   │   ├── reset_token.html
│   │   └── user_posts.html
│   └── users
│   ├── __init__.py
│   ├── forms.py
│   ├── routes.py
│   └── utils.py
└── run.py

Categories