NameError: name xxxxxx is not defined in flask - python

Am having an Import Error issue in a flask restful application, below is the project structure.
project/
app/
views/
tasks.py
flask_celery.py
run.py
So as you have seen above that's the project structure, so my challenge is am importing a variable from run.py to tasks.py. But when I run the application I get an error NameError: name 'celery_access' is not defined
So this is my run.py file :
from app.starwars.star_wars import StarWars
from app.utils.flask_celery import make_celery
app = Flask(__name__)
# configure celery
app.config.update(
CELERY_BROKER_URL='redis://redis:6379/0',
CELERY_RESULT_BACKEND='redis://redis:6379/0'
)
celery_access = make_celery(app)
# secret key
app.secret_key = "xxxx"
api = Api(app)
Then, in the tasks.py file it's where I access the variable name celery_access as below :
from run import celery_access
#celery_access.task()
def paginate_requested_data():
return Hello World''
How can I resolve the import ?

Functions from .py file (can (of course) be in different directory) can be simply imported by writing directories first and then the file name without .py extension:
from directory_name.file_name import function_name
And later be used: function_name()

Related

How set path of folder and files in Gunicorn. ( wsgi.py )

this my flask module main.py
import os
import Flask
import pandas as pd
app = Flask(__name__)
#app.route("/") # this route is working
def index():
return "this working"
#app.route("/data", methods=["POST"])
def get_data():
json = request.json
df = pd.DataFrame(json)
#here some other code that work on the data that are geting from folderspath as we have define below
if __name__=="__main__":
path=os.path.join(os.path.abspath(os.path.join('data')))
folder=os.path.join(path,'test')
app.run(debug=Flase,host="0.0.0.0")
if we just run the flask server it work and execute path statment but if we set for deployment purpose and using gunicorn the first route work. but when we send request to second route it give error of missing folder that are mention in paths. the below module (wsgi.py) is not getting those path how to set these path, that work in wsgi.py
my Gunicorn file wsgi.py
from main import app
if __name__=="__main__":
app.run()
i want wsgi.py to execute those path before app.run() i tried to put in those statement in wsgi before app.run() and imported dependences but still not working.
any help would be appreciated. thanks
You could try gunicorn's --pythonpath argument:
--pythonpath STRING A comma-separated list of directories to add to the Python path.

Why won't Google App Engine find my module (Python 3)?

I'm new to Google App Engine and having the trouble that the app doesn't find my module. I get the error line 5, in <module> import foo as bar ModuleNotFoundError: No module named 'foo'. I have the current file structure as seen below (following a great tutorial for Flask).
The problem is that routes.py cannot import foo.py.
app engine:/
app
static/css
templates
__init__.py
foo.py
routes.py
app.yaml
config.py
main.py
requirements.txt
source-context.json
Why is this? Are there special requirements for how files are structured on App Engine as this works locally?
Also, just to have things working I've tried having the code in the module foo in routes instead and the code works. But the code doesn't belong there and I want to structure it better but the app breaks when separating. In the end I would like to add directory "app engine":/app/libs (or else on recomendation) where I store my custom stuff.
EDIT (add code sample from routes.py)
from flask import render_template, flash, redirect, url_for
from app import app
from app.forms import LookupForm
import logging
import foo as bar
#app.route("/")
#app.route("/index")
def index():
return render_template("index.html")
I was able to reproduce the error you are experiencing. Here are my observations:
You are storing the foo module in a local folder called 'app' (a sub-directory of where you have your main.py file).
In order to reference the module in this situation, you would need to include the name of the sub-directory when doing the import.
Change the following line in your routes.py file:
import foo as bar
to:
import app.foo as bar
I have tested this solution and it worked for me. Please let me know if it helps.

How to deploy a Flask application on pythonanywhere with a folder as a module

Currently I am trying to a deploy my first FLASK application on PythonAnywhere.
Im not sure if this is the correct terminology but I have a folder as a module and there for I can't seem to find the correct way to deploy my application. I am not even sure where to start in resolving this issue. Any advice?
File and Folder Layout Snipped
my init.py code is:
import os
from flask import Flask
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY='secret',
DATABASE=os.path.join(app.instance_path, 'LAMA.sqlite'),
)
if test_config is None:
# load the instance config, if it exists, when not testing
app.config.from_pyfile('config.py', silent=True)
else:
# load the test config if passed in
app.config.from_mapping(test_config)
# ensure the instance folder exists
try:
os.makedirs(app.instance_path)
except OSError:
pass
# database
from . import db
db.init_app(app)
# authentication blueprint
from . import auth
app.register_blueprint(auth.bp)
# blog blueprint - the main index
# from . import blog
# app.register_blueprint(blog.bp)
# app.add_url_rule('/', endpoint='index')
# book blueprint
from . import book
app.register_blueprint(book.bp)
app.add_url_rule('/', endpoint='index')
return app
I have also followed the python debugging page where I have done the following:
>>> import LAMA
>>> print(LAMA)
<module 'LAMA' from '/home/ivanv257/LAMA_MAIN/LAMA/__init__.py'>
So at this stage in my WSGI configuration file I have:
import sys
path = '/home/ivanv257/LAMA_MAIN/LAMA/__init__.py'
if path not in sys.path:
sys.path.append(path)
from LAMA import app as application
I have also tried many other combinations such as
path = '/home/ivanv257/LAMA_MAIN/LAMA/'
from init import app as application
path = '/home/ivanv257/LAMA_MAIN/'
from init import app as application
path = '/home/ivanv257/LAMA_MAIN/'
from LAMA import app as application
my source code path is : /home/ivanv257/LAMA_MAIN/LAMA , although I have also tried different combinations such as /home/ivanv257/LAMA_MAIN/
ERROR DETAIL:
2018-12-08 10:05:32,028: Error running WSGI application
2018-12-08 10:05:32,030: ModuleNotFoundError: No module named 'LAMA'
2018-12-08 10:05:32,030: File "/var/www/ivanv257_pythonanywhere_com_wsgi.py", line 83, in <module>
2018-12-08 10:05:32,030: from LAMA import app as application # noqa
To solve my problem I changed the following (with some assistance) from lama import create_app:
import sys
path = '/home/ivanv257/LAMA_MAIN/LAMA'
if path not in sys.path:
sys.path.append(path)
from lama import create_app
application = create_app()
I also had to remove the from . to just imports
import db
db.init_app(app)
# authentication blueprint
import auth
app.register_blueprint(auth.bp)
You are close. To deploy your app, navigate to the webapps page on your user dashboard. If you have not done so already, click the "Add new a webapp" button and enter the desired name of the app. Then, on the same webapp page on the dashboard, scroll down to the "Code" section of the page. Click on the "source code" a href and add the absolute path (full path) to the lama_main directory storing your init.py file.
Next, click on "WSGI configuration file" link. In the WSGI configuration file for your app, set the correct path to the parent directory and import app from the init.py file:
import sys
# add your project directory to the sys.path
project_home = u'/home/your_user_name/lama_main'
if project_home not in sys.path:
sys.path = [project_home] + sys.path
# import flask app but need to call it "application" for WSGI to work
from init import app as application #note that the module being imported from must be the file with "app" defined.
Then, save the WSGI file and return to the webapp panel on your dashboard. Click the "Reload {your site name}" button. Now, you should be able to visit the site by clicking on the main link at the top of the page.

How to load config file in python from an external module

I have a config module (myConfig.py) present in a library for which i created a standard distribution package using setuptools.
--configPackage
|
| ---- myConfig.py
| ---- __init__.py
myConfig.py is a key value pair like this:
MY_NAME = 'myname'
MY_AGE = '99'
Now I have another python project where I import this config module like this
import configPackage.myConfig as customConfig
If this config file was native to my python project and had not come from an external project then I would have done something like this:
app = Flask(__name__)
app.config.from_object('app.configPackage.config')
where config is actually config.py file under configPackage.
and any key value pair in config.py could then be accessed as
myName = app.config['MY_NAME']
My problem is that I am not able to load the external config file in the above mentioned way for a native config file. What I have tried is this which doesn't work:
import configPackage.myConfig as customConfig
app = Flask(__name__)
app.config.from_object(customConfig)
myName = app.config['MY_NAME']
I get the following error
model_name = app.config['model_name']
KeyError: 'model_name'
Which means that it is not able to load the config file from external module correctly. Can anyone tell me the right way to accomplish this ?
Try this,
in your __init__.py of configPackage import myConfig as shown below
import configPackage.myConfig as myConfig
And in your other app try
app.config.from_object('configPackage.myConfig')

Python "name app = bottle.default_app() not defined" error

I'm using the Bottle framework for a simple application that I'm working on atm. I have my bottle library located in the folder "lib" and I call the bottle framework from the lib folder by "import lib.bottle". This is my folder structure:
lib
- bottle.py
- bottledaemon.py
- __init__.py
view
- log-in.tpl
mybottleapp.py
This is my code:
#!/usr/bin/env python
import lib.bottle
from lib.bottle import route, template, debug, static_file, TEMPLATE_PATH, error, auth_basic, get, post, request, response, run, view, redirect, SimpleTemplate, HTTPError
from lib.bottledaemon import daemon_run
import os
import ConfigParser
#######################
# Application Logic #
#######################
# This line of code is not recognised:
app = bottle.default_app()
##################
# Page Routing #
##################
##### LOG-IN PAGE #####
#route('/')
#view('log-in')
def show_page_index():
outout = 0
# Pathfix for Daemon mode
TEMPLATE_PATH.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "view")))
debug(mode=True)
# Pass to the daemon
if __name__ == "__main__":
daemon_run()
So it throws this error at me:
"name app = bottle.default_app() not defined"
If I remove this line "app = bottle.default_app()" the app works fine BUT I realy want to have it in there for programming purposes.
So what am I doing wrong? Is it maybe cuz I run the app in daemon mode or maybe I don't call it right from the lib folder?
Btw I also can't import ConfigParser. This maybe has a diffirent cause but I can't use it.
I think all you need to do is change this:
import lib.bottle
to this
import lib.bottle as bottle
Note: in my setup all I need to do is this:
import bottle
So it throws this error at me: name app = bottle.default_app() not defined
Lies
Your error is actually
Traceback (most recent call last):
File ..., line ..., in ...
app = bottle.default_app()
NameError: name 'bottle' is not defined
Because you did not define bottle. You defined lib.bottle. Either use your new name
app = lib.bottle.default_app()
or rename it:
import lib.bottle as bottle

Categories