Relative import error with flask - python

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.

Related

Pytest-Flask Cannot import name 'create_app'

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()

How to import locally in a proper way in PyCharm OSX

Here's how the directory looks like
├── Caches
│   ├── 11\ Centroids\ representing\ relative\ anchor\ sizes..png
│   ├── 9\ Centroids\ representing\ relative\ anchor\ sizes..png
│   ├── Generated\ anchors\ relative\ to\ sample\ image\ size.png
│   ├── Relative\ width\ and\ height\ for\ 10107\ boxes..png
│   └── data_set_labels.csv
├── Config
│   ├── feature_map.py
│   ├── set_annotation_conf.py
│   └── voc_conf.json
├── Helpers
│   ├── __pycache__
│   │   ├── annotation_parsers.cpython-37.pyc
│   │   └── visual_tools.cpython-37.pyc
│   ├── anchors.py
│   ├── annotation_parsers.py
│   ├── dataset_handlers.py
│   ├── models.py
│   └── visual_tools.py
├── README.md
├── sample_img.png
└── structure_requirements.txt
in dataset_handlers.py I need to import the following:
from ..Config.feature_map import get_feature_map
and in anchors.py I need to import the following:
from .visual_tools import visualization_wrapper
Both imports do resolve in PyCharm or in other words do not have syntax errors however when are run they give the following error:
ImportError: attempted relative import with no known parent package
If I do this:
from visual_tools import visualization_wrapper
the name visual_tools is unresolved however it runs without errors and it imports the requested things
How to be able to make relative imports from .some_module import something without getting errors and being resolved without marking the directory as sources root.

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

Importing app when using Alembic raises ImportError

I am trying to study how to use alembic in flask, I want to import a method in flask app:
tree .
.
├── README.md
├── alembic
│   ├── README
│   ├── env.py
│   ├── env.pyc
│   ├── script.py.mako
│   └── versions
│   ├── 8f167daabe6_create_account_table.py
│   └── 8f167daabe6_create_account_table.pyc
├── alembic.ini
├── app
│   ├── __init__.py
│   ├── main
│   │   ├── __init__.py
│   │   ├── errors.py
│   │   ├── forms.py
│   │   └── views.py
│   ├── models.py
│   └── templates
│   ├── 404.html
│   ├── 500.html
│   ├── base.html
│   ├── index.html
│   └── user.html
├── config.py
├── data.sqlite
├── manage.py
└── requirements.txt
in app/__init__.py:
def create_app(config_name):
app = Flask(__name__)
I want to import create_app in env.py:
from app import create_app
but the error shows as below when I run the command alembic upgrade head:
File "alembic/env.py", line 5, in <module>
from app import create_app
ImportError: No module named app
Any idea for this?
I guess you are trying to run
python env.py
In this case, your app directory is not in PYTHONPATH.
solution 1
Run the app from parent dir:
python alembic/env.py
solution 2
Set the PYTHONPATH before running the app
PYTHONPATH=/path/to/parent/dir python env.py
edit
I read about alembic. As #mrorno said, just set the PYTHONPATH before running alembic:
PYTHONPATH=. alembic upgrade head
alembic just tries to load your env.py source code. It's not in your package, so it can't access your app module.
Use solution 2 #tomasz-jakub-rup suggested, you can execute like
$ PYTHONPATH=. alembic upgrade head
and you should get your result.
Create file .env and insert PYTHONPATH=.

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