'AttributeError: module '__main__' has no attribute '__package__' - python

I was trying to build flask-web API. When I am trying to run the app.py code, I have got this error, please refer the code which I have mentioned below. Do I have to install some package to get 'package' into 'main'?
I tried to run in different platforms such jupyter notebook, spyder and Google Colab too, but it didn't work, and getting similar issues.
Here is my app.py code whic is giving error:
from flask import Flask, request, jsonify, render_template
import pickle
app = Flask(__name__)
model = pickle.load(open('model.pkl', 'rb'))
#app.route('/')
def home():
return render_template('index.html')
#app.route('/predict',methods=['POST'])
def predict():
'''
For rendering results on HTML GUI
'''
int_features = [int(x) for x in request.form.values()]
final_features = [np.array(int_features)]
prediction = model.predict(final_features)
output = round(prediction[0], 2)
return render_template('index.html', prediction_text='Employee Salary should be $ {}'.format(output))
#app.route('/predict_api',methods=['POST'])
def predict_api():
'''
For direct API calls trought request
'''
data = request.get_json(force=True)
prediction = model.predict([np.array(list(data.values()))])
output = prediction[0]
return jsonify(output)
if __name__ == "__main__":
app.run(debug=True)
Here is the error message I have got:
* Serving Flask app "__main__" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Restarting with stat
Traceback (most recent call last):
File "<ipython-input-21-3add8626fce0>", line 36, in <module>
app.run(debug=True)
File "C:\Users\ishwo\Anaconda3\lib\site-packages\flask\app.py", line 990, in run
run_simple(host, port, self, **options)
File "C:\Users\ishwo\Anaconda3\lib\site-packages\werkzeug\serving.py", line 1007, in run_simple
run_with_reloader(inner, extra_files, reloader_interval, reloader_type)
File "C:\Users\ishwo\Anaconda3\lib\site-packages\werkzeug\_reloader.py", line 332, in run_with_reloader
sys.exit(reloader.restart_with_reloader())
File "C:\Users\ishwo\Anaconda3\lib\site-packages\werkzeug\_reloader.py", line 159, in restart_with_reloader
args = _get_args_for_reloading()
File "C:\Users\ishwo\Anaconda3\lib\site-packages\werkzeug\_reloader.py", line 76, in _get_args_for_reloading
if __main__.__package__ is None:
AttributeError: module '__main__' has no attribute '__package__'}

Related

RuntimeError: Working outside of request context. with gunicorn

Whenever I run my code as python3 myapp.py it works fine but whenever I use gunicorn -w 4 myapp:index -b 10.91.1.230:5055 &
it throws
ion#aurora:~/TNQ$ [2019-02-05 14:26:34 +0530] [27107] [INFO] Starting
gunicorn 19.9.0
..............
27116
[2019-02-05 14:26:38 +0530] [27113] [ERROR] Error handling request /
Traceback (most recent call last):
File "/home/ion/.local/lib/python3.6/site-packages/gunicorn/workers/sync.py", line 135, in handle
self.handle_request(listener, req, client, addr)
File "/home/ion/.local/lib/python3.6/site-packages/gunicorn/workers/sync.py", line 176, in handle_request
respiter = self.wsgi(environ, resp.start_response)
File "/home/ion/TNQ/myapp.py", line 16, in index
f = request.files['file']
File "/home/ion/.local/lib/python3.6/site-packages/werkzeug/local.py", line 347, in __getattr__
return getattr(self._get_current_object(), name)
File "/home/ion/.local/lib/python3.6/site-packages/werkzeug/local.py", line 306, in _get_current_object
return self.__local()
File "/home/ion/.local/lib/python3.6/site-packages/flask/globals.py", line 37, in _lookup_req_object
raise RuntimeError(_request_ctx_err_msg)
RuntimeError: Working outside of request context.
This typically means that you attempted to use functionality that needed
an active HTTP request. Consult the documentation on testing for
information about how to avoid this problem.
myapp.py
from flask import Flask,request
from CXE.src.models import class_classic as cc
app = Flask(__name__)
#app.route('/', methods=['POST'])
#def index(environ, start_response):
def index(environ, start_response):
with app.app_context():
#if request.method == 'POST':
f = request.files['file']
a = cc.initiate(f)
return a
if __name__ == '__main__':
app.run(host = '0.0.0.0',port=5505,debug=True)
I need to put the code on gunicorn for serving it on threads. Any idea why isn't it working ?
It doesn't work because index is not a wsgi app - it's not enough for the function to have the correct signature. Do the following instead:
gunicorn -w 4 myapp:app -b 10.91.1.230:5055 &
You see no issue when you run python3 myapp.py because flask's dev server, app.run, does not require a wsgi app, whereas gunicorn does. With that said, you might as well go ahead and remove the index signature.

Unable to deploy Python Flask application in Google App Engine Flex Environment

I have searched in multiple places and have tried multiple ways to find a solution to this. But nothing was helpful, can you please help me provide the solution. It is getting extremely difficult to host a python flask application in google app engine flexible environment. Python code: "getresource.py"
Here is the link from google to deploy Python Flask application
Here is the simple code:
from flask import Flask, jsonify
from pymysql import connections, ProgrammingError, DatabaseError, MySQLError, DataError
from os import environ
DB_HOST = environ.get("DB_HOST")
USER = environ.get("USER")
PWD = environ.get("PASSWORD")
DATABASE = environ.get("DATABASE")
app = Flask(__name__)
dbconn = connections.Connection(
host=DB_HOST,
port=3306,
user=USER,
password=PWD,
db=DATABASE
)
#app.route("/getResource/<id>", methods=['GET'])
def getresource(id):
result = ()
select_sql = "SELECT `id`, `firstName`, `middleName`, `lastName`, `listOfTechWorkedOn`, `certifications`, `projects`, `applicationWorkLoadTypes` FROM `resource` WHERE `id`=%s"
cursor = dbconn.cursor()
try:
cursor.execute(select_sql, (id))
result = cursor.fetchone()
response = {}
response['id'] = result[0]
response['firstName'] = result[1]
response['middleName'] = result[2]
response['lastName'] = result[3]
response['listOfTechWorkedOn'] = result[4]
response['certifications'] = result[5]
response['projects'] = result[6]
response['applicationWorkLoadTypes'] = result[7]
return jsonify(response)
except ProgrammingError as p:
return
except DatabaseError as d:
return d
except MySQLError as m:
return m
except DataError as de:
return de
dbconn.close()
if __name__ == '__main__':
app.run(host='127.0.0.1',port=8080, debug=True)
Here is the app.yaml file
runtime: python
env: flex
entrypoint: gunicorn -b :$PORT getresource:app
service: getresource
runtime_config:
python_version: 3
manual_scaling:
instances: 1
env_variables:
DB_HOST: "1.2.3.4"
USER: "root"
PASSWORD: "abcdefg"
DATABASE: "abcd"
requirements.txt file
Flask==1.0.2
gunicorn==19.9.0
PyMySQL==0.9.2
I am getting the following error: "gcloud app deploy"
ERROR: (gcloud.app.deploy) Error Response: [13] An internal error occurred during deployment.
I have tried multiple ways, like changing the python code, putting google cloud libraries in the requirements.txt, chaning port, service name etc. But nothing seems to be working.
And surprisingly, I am not getting the error trace in stackdriver logs as well. And Google does not have proper answer it seems (at least from all the googling that i have done)
gcloud version
Google Cloud SDK 222.0.0
bq 2.0.36
core 2018.10.19
gsutil 4.34
**
EDIT:
** Thanks for all the response. I tried all the options, but getting the same error with following debug message. I cannot make anything out of it
Thanks for the response. I tried with all the suggested options, but getting the same error. Following is the debug log, and I cannot make anything out of it.
Updating service [getresource] (this may take several minutes)...failed.
DEBUG: (gcloud.app.deploy) Error Response: [13] An internal error occurred during deployment.
Traceback (most recent call last):
File "C:\Users\M1044921\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\calliope\cli.py", line 841, in Execute
resources = calliope_command.Run(cli=self, args=args)
File "C:\Users\M1044921\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\calliope\backend.py", line 770, in Run
resources = command_instance.Run(args)
File "C:\Users\M1044921\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\surface\app\deploy.py", line 90, in Run
parallel_build=False)
File "C:\Users\M1044921\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\command_lib\app\deploy_util.py", line 620, in RunDeploy
flex_image_build_option=flex_image_build_option)
File "C:\Users\M1044921\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\command_lib\app\deploy_util.py", line 422, in Deploy
extra_config_settings)
File "C:\Users\M1044921\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\api_lib\app\appengine_api_client.py", line 207, in DeployService
poller=done_poller)
File "C:\Users\M1044921\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\api_lib\app\operations_util.py", line 315, in WaitForOperation
sleep_ms=retry_interval)
File "C:\Users\M1044921\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\api_lib\util\waiter.py", line 254, in WaitFor
sleep_ms, _StatusUpdate)
File "C:\Users\M1044921\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\api_lib\util\waiter.py", line 316, in PollUntilDone
sleep_ms=sleep_ms)
File "C:\Users\M1044921\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\core\util\retry.py", line 229, in RetryOnResult
if not should_retry(result, state):
File "C:\Users\M1044921\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\api_lib\util\waiter.py", line 310, in _IsNotDone
return not poller.IsDone(operation)
File "C:\Users\M1044921\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\api_lib\app\operations_util.py", line 184, in IsDone
encoding.MessageToPyValue(operation.error)))
OperationError: Error Response: [13] An internal error occurred during deployment.
ERROR: (gcloud.app.deploy) Error Response: [13] An internal error occurred during deployment.

Setting Jinja environment global variable outside of request context

I have a function called generate_csrf_token which is located in package commons.formsecurity containing the following code.
import random
import string
from flask import session
def generate_csrf_token():
if '_csrf_token' not in session:
state = ''.join(random.choice(string.ascii_uppercase + string.digits)
for x in xrange(32))
session['_csrf_token'] = state
return session['_csrf_token']
I am calling this in my create_app function.
from flask import Flask
from routes_manager import configure_blueprints
from error_handling import configure_error_handling
from flask import session
from flask.ext.session import Session
from commons.formsecurity import generate_csrf_token
def create_app():
"""Create the Flask App"""
app = Flask(__name__)
app.secret_key = 'lalalalalala'
app.jinja_env.globals['csrf_token'] = generate_csrf_token()
configure_blueprints(app)
configure_error_handling(app)
return app
create_app is called from main.py
from app import create_app
app = create_app()
"""Run the clients"""
if __name__ == '__main__':
app.run(debug=True)
When I run my Flask application. I get the following error.
ERROR 2017-05-25 12:12:50,720 wsgi.py:263]
Traceback (most recent call last):
File "C:\Program Files (x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line 240, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "C:\Program Files (x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line 299, in _LoadHandler
handler, path, err = LoadObject(self._handler)
File "C:\Program Files (x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line 85, in LoadObject
obj = __import__(path[0])
File "C:\Code\App-Engine\cfc-melbourne-website\main.py", line 3, in <module>
app = create_app()
File "C:\Code\App-Engine\cfc-melbourne-website\app\__init__.py", line 12, in create_app
app.jinja_env.globals['csrf_token'] = generate_csrf_token()
File "C:\Code\App-Engine\cfc-melbourne-website\app\commons\formsecurity.py", line 7, in generate_csrf_token
if '_csrf_token' not in session:
File "lib\werkzeug\local.py", line 379, in <lambda>
__contains__ = lambda x, i: i in x._get_current_object()
File "lib\werkzeug\local.py", line 306, in _get_current_object
return self.__local()
File "lib\flask\globals.py", line 37, in _lookup_req_object
raise RuntimeError(_request_ctx_err_msg)
RuntimeError: Working outside of request context.
This typically means that you attempted to use functionality that needed
an active HTTP request. Consult the documentation on testing for
information about how to avoid this problem.
Where is the best place to call the following
app.jinja_env.globals['csrf_token'] = generate_csrf_token()
If you don't call the generate_csrf_token() function, and instead store the reference to the function, you can call it in your Jinja templates (which will be in the context where a request is available).
So replace
app.jinja_env.globals['csrf_token'] = generate_csrf_token()
With
app.jinja_env.globals['csrf_token'] = generate_csrf_token
And in your templates, use:
<input name=_csrf_token type=hidden value="{{ csrf_token() }}">

Traceback when running simple Flask application [duplicate]

This question already has an answer here:
Quickstart Flask application failing for some reason
(1 answer)
Closed 6 years ago.
Edit: This question apparently has an answer here
Quickstart Flask application failing for some reason
As well as a (closed and apparently fixed) GitHub issue here:
https://github.com/pallets/werkzeug/issues/798
Unfortunately I'm still experiencing the problem, even with Werkzeug 0.12-dev (the latest code from GitHub).
I've just started developing a simple Flask application with Python 3.4 on Windows. Literally, at the moment, here are the only contents of fileserve.py.
import os.path
from flask import abort, Flask
base_directory = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config.from_pyfile(os.path.join(base_directory, 'fileserve.cfg'))
#app.route('/')
def index():
abort(403)
if __name__ == '__main__':
app.run(debug=True)
When I try running the application, I get the following traceback:
Traceback (most recent call last):
File "fileserve.py", line 22, in <module>
app.run(debug=True)
File "C:\Users\jscholes\dev\fileserve\env\lib\site-packages\flask\app.py", line 772, in run
run_simple(host, port, self, **options)
File "C:\Users\jscholes\dev\fileserve\env\lib\site-packages\werkzeug\serving.py", line 633, in run_simple
application = DebuggedApplication(application, use_evalex)
File "C:\Users\jscholes\dev\fileserve\env\lib\site-packages\werkzeug\debug\__init__.py", line 249, in __init__
if self.pin is None:
File "C:\Users\jscholes\dev\fileserve\env\lib\site-packages\werkzeug\debug\__init__.py", line 259, in _get_pin
self._pin, self._pin_cookie = get_pin_and_cookie_name(self.app)
File "C:\Users\jscholes\dev\fileserve\env\lib\site-packages\werkzeug\debug\__init__.py", line 169, in get_pin_and_cookie_name
h.update('cookiesalt')
TypeError: Unicode-objects must be encoded before hashing
This error occurs even with a simple "hello world" app:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return 'Hello world'
app.run(debug=True)
Is Flask's support for Python 3 just not very good? Is there a workaround for this? Working without the option of debug mode is not a great prospect.
Upgrade your werkzeug installation.
In my install, with werkzeug.__version__ == 0.11.7, line 169 reads:
h.update(b'cookiesalt')

flask "hello world" can not run in debug model

I followed official document, installed virtualenv and flask, and then python hello.py
But there is something wrong:
* Running on http://127.0.0.1:5000/
* Restarting with reloader: inotify events
Traceback (most recent call last):
File "hello.py", line 9, in <module>
app.run(debug=True)
File "/home/aa/prj/env/lib/python2.7/site-packages/Flask-0.7.2-py2.7.egg/flask/app.py", line 553, in run
return run_simple(host, port, self, **options)
File "/home/aa/prj/env/lib/python2.7/site-packages/Werkzeug-0.7-py2.7.egg/werkzeug/serving.py", line 609, in run_simple
run_with_reloader(inner, extra_files, reloader_interval)
File "/home/aa/prj/env/lib/python2.7/site-packages/Werkzeug-0.7-py2.7.egg/werkzeug/serving.py", line 528, in run_with_reloader
reloader_loop(extra_files, interval)
File "/home/aa/prj/env/lib/python2.7/site-packages/Werkzeug-0.7-py2.7.egg/werkzeug/serving.py", line 436, in reloader_loop
reloader(fnames, interval=interval)
File "/home/aa/prj/env/lib/python2.7/site-packages/Werkzeug-0.7-py2.7.egg/werkzeug/serving.py", line 464, in _reloader_inotify
mask = reduce(lambda m, a: m | getattr(EventsCodes, a), mask, 0)
File "/home/aa/prj/env/lib/python2.7/site-packages/Werkzeug-0.7-py2.7.egg/werkzeug/serving.py", line 464, in <lambda>
mask = reduce(lambda m, a: m | getattr(EventsCodes, a), mask, 0)
AttributeError: type object 'EventsCodes' has no attribute 'IN_DELETE_SELF'
my hello.py:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return "Hello World!"
if __name__ == '__main__':
app.run(debug=True)
but if without debug that's ok? why?
my /env/lib/python2.7/site-packages:
distribute-0.6.10-py2.7.egg
Jinja2-2.6-py2.7.egg
Werkzeug-0.7-py2.7.egg
easy-install.pth
pip-0.7.2-py2.7.egg
This seems to be a bug triggered by a change in pyinotify's API, which you must also have installed. You could remove pyinotify or use a dirty hack to force it to use stat() instead of pyinotify. To line 496 of werkzeug/serving.py try adding (below the part where it attempts to import pyinotify):
# dirty hack
reloader = _reloader_stat_loop
reloader_name = "stat() polling"
Make sure to also report the bug to the werkzeug developers.

Categories