I am currently developing an application. this web app has its own domain. when initially created i set up the domain and the registrar using the cname and it succesfully displayed after a couple of hours "this is a flask app..." something like that.
i decided to follow the examples of Mr Grinberg in his book (fully functional on localhost). So i cloned my personal repository to pythonanywhere and ran the following commands.
python manage.py db init
python manage.py db upgrade
python manage.py migrate
every thing is ok so far. and i checked out the mysql database using mysql workbench.
Now comes my issue.
when i run python manage.py runserver
it throws me the following error.
/home/username/.virtualenvs/webapp/local/lib/python2.7/site-packages
/flask_sqlalchemy/__init__.py:800: UserWarning: SQLALCHEMY_TRACK_MODIFICA
TIONS adds significant overhead and will be disabled by default in the future. Set it to True to suppress this warning.
warnings.warn('SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True to su
ppress this warning.')
Traceback (most recent call last):
File "manage.py", line 20, in <module>
manager.run()
File "/home/username/.virtualenvs/webapp/local/lib/python2.7/site-packages/flask_script/__init__.py", line 412, in run
result = self.handle(sys.argv[0], sys.argv[1:])
File "/home/username/.virtualenvs/webapp/local/lib/python2.7/site-packages/flask_script/__init__.py", line 383, in handle
res = handle(*args, **config)
File "/home/username/.virtualenvs/webapp/local/lib/python2.7/site-packages/flask_script/commands.py", line 425, in __call__
**self.server_options)
File "/home/username/.virtualenvs/webapp/local/lib/python2.7/site-packages/flask/app.py", line 843, in run
run_simple(host, port, self, **options)
File "/home/username/.virtualenvs/webapp/local/lib/python2.7/site-packages/werkzeug/serving.py", line 677, in run_simple
s.bind((hostname, port))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use
i tried disabling the wsgi.py file (commenting everything out) still the same.
Things to know:
i have a paid acount.
this is the second webapp on pythonanywhere. (the first one is not modeled based on the tutorial and works just fine)
EDIT
i changed the port from 5000 to 9000. and it runs in the console. but i cant visit my site. should i comment out the wsgi file?
currently it looks likes this:
import sys
# # add your project directory to the sys.path
project_home = u'/home/username/e_orders/e_orders'
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 manager import app as application
manage.py
import os
from app import create_app, db
from app.models import User
from flask_script import Manager, Shell, Server
from flask_migrate import Migrate, MigrateCommand
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
migrate = Migrate(app, db)
def make_shell_context():
return dict(app=app, db=db, User=User)
manager.add_command('shell', Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
manager.add_command('runserver', Server(port=9000))
if __name__ == '__main__':
manager.run()
EDIT 2
i have the following error with the wsgi configuration above.
errorlog
ImportError: No module named manager
2016-08-04 17:42:39,589 :Error running WSGI application
Traceback (most recent call last):
File "/bin/user_wsgi_wrapper.py", line 154, in __call__
app_iterator = self.app(environ, start_response)
File "/bin/user_wsgi_wrapper.py", line 170, in import_error_application
raise e
ImportError: No module named manager
PythonAnywhere dev here.
If you run a Flask app from a console on PythonAnywhere, it's not actually accessible from anywhere else. It may well run, but nothing will route any requests to it. So there's no need to run anything from the console (unless you're just testing for syntax errors, I guess).
Instead, you need to create a web app on the "Web" tab -- it looks like you've already done that. This then routes using the WSGI file that you seem to have discovered.
If you've done all that, then when you visit the domain that appears on the "Web" tab (normally something like yourusername.pythonanywhere.com) then you should see your site. If you get an error, then check out the error logs (also linked from the "Web" tab), which should help you debug.
[edit: added affiliation]
Sorry for the big delay. The solution to run the server is the one bellow.
# This file contains the WSGI configuration required to serve up your
# web application at http://<your-username>.pythonanywhere.com/
# It works by setting the variable 'application' to a WSGI handler of some
# description.
#
# The below has been auto-generated for your Flask project
import sys
# # add your project directory to the sys.path
project_home = u'/home/username/mysite/'
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 manage import app as application
i will post the database setup also...
Related
I'm trying to set up my first Python web application through Flask. I've used the setup module on my hosting service, and I've hit a problem. When I try to run the app, I get an error page from Phusion Passenger. In the searching I've done so far, similar problems seem to come from Passenger's inability to locate the needed software. But I haven't done this before, so I may well be misunderstanding the problem. All help much appreciated.
Here are the contents of passenger_wsgi.py:
import imp
import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
wsgi = imp.load_source('wsgi', 'flaskblog.py')
application = wsgi.application
And here is what the site admin pulled from the error log:
[ E 2020-05-25 15:09:08.9018 32404/T1q age/Cor/App/Implementation.cpp:221 ]:
Could not spawn process for application /home/eriksimp/public_html/flaskblog: The application process exited prematurely.
App 28117 output: File "/home/eriksimp/virtualenv/public_html/flaskblog/3.7/lib64/python3.7/imp.py", line 171, in load_source
App 28117 output: File "/home/eriksimp/public_html/flaskblog/passenger_wsgi.py", line 8, in <module>
App 28117 output: File "/home/eriksimp/virtualenv/public_html/flaskblog/3.7/lib64/python3.7/imp.py", line 171, in load_source
The problem was that I hadn't activated the environment. (I was following instructions that didn't include that step.) I created the app using cPanel, and at the end of the process, cPanel provided a Terminal command (at the top of the page) to activate the app. I entered Terminal through cPanel, ran that command, then ran "pip install flask."
Then I restarted the application and reloaded the page. Now it works!
I have following question to sqlalchemy in gae. I'm using the integrated google app engine sdk from Pycharm. Everything works fine, except the integration of sqlalchemy. The database itself works fine if I debug it with the Python interpreter. But when I'm trying to run it together with the google app engine I'm getting troubles with the import of the sqlalchemy library.
I already tried to solve it with virtualenv, but it didn't work either.
Here is my output log:
Connected to pydev debugger (build 131.618)
WARNING 2014-02-17 10:58:22,887 api_server.py:331] Could not initialize images API; you are likely missing the Python "PIL" module.
WARNING 2014-02-17 10:58:22,895 simple_search_stub.py:1018] Could not read search indexes from c:\users\user\appdata\local\temp\appengine.test\search_indexes
INFO 2014-02-17 10:58:22,947 api_server.py:138] Starting API server at: localhost:60878
INFO 2014-02-17 10:58:22,994 dispatcher.py:171] Starting module "default" running at: localhost:8080
INFO 2014-02-17 10:58:23,032 admin_server.py:117] Starting admin server at: localhost:8000
pydev debugger: process 4452 is connecting
pydev debugger: process 4196 is connecting
ERROR 2014-02-17 09:58:35,742 wsgi.py:262]
Traceback (most recent call last):
File "C:\Program Files (x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line 239, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "C:\Program Files (x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line 298, in _LoadHandler
handler, path, err = LoadObject(self._handler)
File "C:\Program Files (x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line 84, in LoadObject
obj = import(path[0])
File "C:\Users\user\PycharmProjects\test\main.py", line 16, in
from bin.database.DBList import DBList
File "C:\Users\user\PycharmProjects\test\bin\database\DBList.py", line 17, in
from sqlalchemy import Column, Integer, String
ImportError: No module named sqlalchemy
INFO 2014-02-17 10:58:36,410 module.py:617] default: "GET / HTTP/1.1" 500 -
So how is it possible to add a third party library in gae?
This is to be expected because GAE has no idea what things your virtualenv is using. To mitigate this problem of using a third party library, all you need to do is download the source code of the library and all its dependents, and put it into a folder underneath your root project directory.
Add the folder to your PYTHONPATH, you can do this via:
import sys; sys.path.append('<your relative path to directory here>')
And then you are all set. By convention this directory that you put all your third party libraries under, is called lib.
Following Flask tutorial, running Win 7, Python 2.7.3, virtualenv, and I am stuck in Step 3: Creating The Database http://flask.pocoo.org/docs/tutorial/dbinit/#tutorial-dbinit
Such a schema can be created by piping the schema.sql file into the sqlite3 command as follows:
sqlite3 /tmp/flaskr.db < schema.sql
How to run this command, because CMD < venv > returns:
"sqlite3" is not recognized as internal or external command, operable program or batch file.
Is this step necessary?
Folder Project, 2 files schema.sql and flaskr.py.
schema.sql
drop table if exists entries;
create table entries (
id integer primary key autoincrement,
title string not null,
text string not null
);
flaskr.py
# all the imports
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, \
abort, render_template, flash
from contextlib import closing
# configuration
DATABASE = '/tmp/flaskr.db'
DEBUG = True
SECRET_KEY = 'development key'
USERNAME = 'admin'
PASSWORD = 'default'
# create our little application :)
app = Flask(__name__)
app.config.from_object(__name__)
app.config.from_envvar('FLASKR_SETTINGS', silent=True)
def connect_db():
return sqlite3.connect(app.config['DATABASE'])
def init_db():
with closing(connect_db()) as db:
with app.open_resource('schema.sql') as f:
db.cursor().executescript(f.read())
db.commit()
if __name__ == '__main__':
app.run()
< venv > python
>>> from flaskr import init_db
>>> init_db()
Trackeback <most recent call last>:
File "<stdin>", line 1, in <module>
File "flaskr.py", line 24, in init_db
with closing (connect_db()) as db:
File "flaskr.py", line 21, in connect_db
return sqlite3.connect(app.config['DATABASE'])
sqlite3.OperationalError: unable to open database.
You are confused between Windows and UNIX filesystems.
Find out where sqllite.exe file exists on the computer. lets say it is in C:\sqllite. Then you also need to determine where you will create the database file. /tmp/flaskr.db is for the UNIX filesystem. On windows, you should provide the exact path or in your current working directory. lets say it is C:\flasktutorial.
To be safe, you might want to create a blank flaskr.db file first.
Open a notepad and create the blank file at `C:\flasktutorial\flaskr.db`
Now you can run:
C:\sqllite\sqllite.exe C:\flasktutorial\flaskr.db < schema.sql
Also make sure that in your flaskr.py file, change the DATABASE to:
DATABASE = 'C:\flasktutorial\flaskr.db'
Did you activate virtualenv and installed flask?
flask should have sqlite3 by default. I got following error though:
File "flaskr.py", line 26, in connect_db
return sqlite3.connect(app.config['DATABASE'])
sqlite3.OperationalError: unable to open database file`
To fix that I had to do the following (in Windows):
Change DATABASE = '/tmp/flaskr.db' to DATABASE = '.\\tmp\\flaskr.db'
Create tmp folder in current folder (flaskr)
Create an empty flaskr.db file in tmp
After that it's working for me.
As you can observe from the error logs, the error is coming while connecting DB
sqlite3.OperationalError: unable to open database.
And since this step failed for you,
sqlite3 /tmp/flaskr.db < schema.sql
You can easily interpret that this step is necessary.
Now to solve this error, simply you have to install sqlite3, In ubuntu you can install sqlite3 as,
apt-get install sqlite3
After installation your program will work fine as expected.
I'm not sure if these tips are directly applicable to the PO, but they landed me here, so maybe it will be helpful.
Be sure to check the README file within the flaskr directory which specifies running flask --app=flaskr initdb from the command line.
If this returns AttributeError: 'Flask' object has no attribute 'cli', it may be due to click not being installed.
If the command returns flask: command not found, it may be due to having an older version of Flash installed, which is what pip install flask does.
As of today this command pip install https://github.com/mitsuhiko/flask/tarball/master, will install the most recent version.
For linux user only:
First you install Sqlite3 from here.
After installation you need to create a file called flaskr.db,location of this file is to be /myproject/venv/bin/flaskr/tmp .
Next step is run command
sqlite3 /home/ddserver/myproject/venv/bin/flaskr/tmp/flaskr.db<schema.sql
I took file address from home.
Next step is start python shell, run this code
>>> from flaskr import init_db
>>> init_db()
Thats it.
I cannot run gunicorn on heroku with simple flask app.
The application is really simple. This is app.py:
app = Flask(__name__)
#app.route("/")
def say_hello(url):
return "Hello"
if __name__ == "__main__":
port = int(os.environ.get('PORT', 8888))
app.run(host='0.0.0.0',port=port)
The app works fine through flask test server on heroku, but
when I switch to use gunicorn, it crashes with:
ImportError: No module named app.wsgiapp
My requirements.txt:
Flask==0.8
gevent==0.13.7
gunicorn==0.13.2
I've tried different versions of gunicorn from 0.13.7 to 0.14.6 with no success.
Procfile:
web: gunicorn app:app -w 4 -b 0.0.0.0:$PORT
Running this command:
heroku logs
gives this:
←[33m2012-08-09T21:08:02+00:00 app[web.1]:←[0m ImportError: No module named app.
wsgiapp ←[33m2012-08-09T21:08:02+00:00 app[web.1]:←[0m entry = __import__(self.modul
e_name, globals(),globals(), ['__name__'])
Any help please?
In my case, I got this error by having a gunicorn.py file in my top level folder. This clashed with the installed gunicorn library on Heroku.
So my run command that caused the problem was:
gunicorn -c gunicorn.py myapp:main
Raising the following error:
Traceback (most recent call last):
File "/app/.heroku/python/bin/gunicorn", line 9, in <module>
load_entry_point('gunicorn==18.0', 'console_scripts', 'gunicorn')()
File "/app/.heroku/python/lib/python2.7/site-packages/pkg_resources.py", line 378, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "/app/.heroku/python/lib/python2.7/site-packages/pkg_resources.py", line 2566, in load_entry_point
return ep.load()
File "/app/.heroku/python/lib/python2.7/site-packages/pkg_resources.py", line 2260, in load
entry = __import__(self.module_name, globals(),globals(), ['__name__'])
ImportError: No module named app.wsgiapp
Whereas after a mv gunicorn.py gunicorn_config.py it worked fine with:
gunicorn -c gunicorn_config.py myapp:main
I ran into this problem when upgrading Ubuntu to 14.04 LTS.
For some reason, gunicorn failed to pick up the correct python path to resolve the wsgi module.
I resolved this, for now, by declaring the python path explicitly to gunicorn via the --pythonpath parameter (documented here).
For example:
gunicorn --pythonpath /path/to/containing/directory "app.wsgi_app:wsgi_app"
I finally figured this one out.
It's basically just a PATH problem. If you import certain modules (like os and sys) in the wrong order depending on your setup, you will cause Gunicorn to look in the wrong package for the app.wsgiapp module. (not to be confused with the app.wsgi_app function in Flask)
The correct import order will vary depending on your setup, but the rule of thumb based on what I was able to get working was to just make sure that your sys module is imported before your os module.
Beyond that, assuming the rest of the config is normal (as above) you shouldn't have any issues.
Note: THIS IS ONLY A PROBLEM ON HEROKU with Gunicorn. It has something to do with how their PYTHONPATH and module search path is set up. I don't know why exactly, but this is only necessary for the production environment, local setups will work fine regardless of the module import order.
My guess is there is an other "app" module in the python path (both gunicorn and flask have a module called app already).
Rename it anything else than app.py and it should work.
I have a problem when i try to install a Django website, on a Mocha hosting, and their technical support is so much uninformed... (I strongly don't recomment Mocha hosting for a django hosting)
They have mod_wsgi support, and mod_python installed, but when i am uploading the site as in their tutorial
http://www.mochasupport.com/kayako/index.php?_m=knowledgebase&_a=viewarticle&kbarticleid=448&nav=0,46
but at the end i am getting an error like:
Traceback (most recent call last):
File "/usr/lib64/python2.5/site-packages/mod_python/importer.py", line 1537, in HandlerDispatch
default=default_handler, arg=req, silent=hlist.silent)
File "/usr/lib64/python2.5/site-packages/mod_python/importer.py", line 1202, in _process_target
module = import_module(module_name, path=path)
File "/usr/lib64/python2.5/site-packages/mod_python/importer.py", line 304, in import_module
return import(module_name, {}, {}, ['*'])
ImportError: No module named django.core.handlers.modpython
I know this issue has been treated here as well: Error while deploying Django on Apache
But i don't have access to the terminal, how can i solve it? Is there a way to correctly set the python path without terminal access?
Thanks!
Do you double check that you upload a django in
/home/youraccount/webapps/django
Most likely the hosting provieder has harcode (width you account)
that path in the apache configuration for the mod_python approach.
Or
Why don't you use mod_wsgi and in the wsgi script add your django, like this.
import os
import sys
sys.path.append('/home/youraccount/webapps/django') # Path to your custom django.
from django.core.handlers.wsgi import WSGIHandler
os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'
application = WSGIHandler()
Looking at that article, it seems that they don't provide Django for your use. You'll need to upload it as well.