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.
Related
Been trying to implement a django app with postgresql database on heroku, with psycopg2 as the backend.
(Based on the research I've done, psycopg3 looks like it's not really built for that purpose)
My app works, without issue running inside heroku/heroku console, and connects to db fine.
But running locally (python manage.py runserver), it just can't detect the psycopg2 module. I've reinstalled the module in and out of a venv. I've tried the binary install, used -pep517 method as well.
I saw a thread here indicating newer python may not be compatible, but it didn't really provide any concrete proof as far as I could tell.
Any advise in this regard, or perhaps a better backend adapter suggestion for Django + postgres?
below are the relevant portions of settings.py in the django project directory:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': '*db info here'
...more db creds
}
}
and the error:
File "C:\*userdirectory*\djangenv\Lib\site-packages\django\db\backends\postgresql\base.py", line 24, in <module>
import psycopg2 as Database
File "C:\*userdirectory*\djangenv\Lib\site-packages\psycopg2\__init__.py", line 51, in
<module> from psycopg2._psycopg import ( # noqa
ImportError: DLL load failed while importing _psycopg: The specified module could not be
found.
So... It worked upon downgrading back to Python 3.10. Shoulda tried that earlier lol
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...
I'm trying to run a populate script which I put together from the tango_with_django tutorial (https://github.com/leifos/tango_with_django/blob/master/tango_with_django_project/populate_rango.py) however I'm getting the below traceback and it seems to be related to changes made in Django 1.7? I'd appreciate if someone could explain what I'm doing wrong here.
(test_env) C:\Users\WriteCode\test_env\epl>python populate_clubs.py
Traceback (most recent call last):
File "populate_clubs.py", line 4, in <module>
django.setup()
File "c:\Python27\lib\site-packages\django\__init__.py", line 20, in setup
configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
File "c:\Python27\lib\site-packages\django\conf\__init__.py", line 46, in __ge
tattr__
self._setup(name)
File "c:\Python27\lib\site-packages\django\conf\__init__.py", line 40, in _set
up
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, b
ut settings are not configured. You must either define the environment variable
DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
(test_env) C:\Users\WriteCode\test_env\epl>
My populate_clubs.py script
import os
import sys
import django
django.setup()
def add_club(name, nickname, manager, established, stadium, active=True):
c = clubs.objects.get_or_create(name=name, nickname=nickname, manager=manager, established=established, stadium=stadium, active=active)
return c
def populate():
add_club(name = "Aston Villa",
nickname = "Villans",
manager = "Tim Sherwood",
established = "1897",
stadium = "Villa Park"
)
# Print out what was added
for c in clubs.objects.all():
print "The following has been added to clubs:" + c
# Start execution
if __name__ == '__main__':
print "Starting club population script..."
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'epl.settings')
from teams.models import clubs
populate()
You can insert os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") before the django.setup() line.
Call to django.setup() should go after setting DJANGO_SETTINGS_MODULE environment variable. Just move it into your __main__ right after os.environ.setdefault().
If you are getting a similar error after initiating your interaction with Django by running python in a terminal, running python manage.py shell in the appropriate directory may solve your issue.
For development and debugging, you may use the standalone python package.
Install with pip
pip install standalone
Use standalone to use Django from the module.
# add the following to the top of the module.
import standalone
standalone.run('mysite.settings') # replace with your settings module.
# your code goes below the configuration
import os
import sys
# ... .. . whole module
Now you may run the module as a Python Django script.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'epl.settings')
should be above
import django
which is you should call django_settings_module before importing and calling django setup.
Hope this is helpful.
If you're running PyCharm, what worked for me was to invalidate the cache and restart the app.
File => Invalidate Caches / Restart ...
My virtualenv had been recently updated from Python 3.6 or 3.7 to 3.8.
It happened to me when I used django related import statement in a non-django module.
i.e from index.views import view that did raise an error for me.
I met the same problem when setting the environment.
(I tried to add the:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_project.settings")
into the "Starting script window",which is in the Django Console or rewrite the .wsgi file, But all of them were failed)
My final solution: (open the terminal and set the environment manually)
Here are the steps:(for mac)
open the terminal and type vim ~/.bash_profile
add below lines:
PATH=${PATH}:/Users/work/workspace/[virtual_environment]/bin
PYTHONPATH=${PATH}:/Users/work/PycharmProjects/[project_name]
DJANGO_SETTINGS_MODULE=[project_name].settings
type :wq to save and exit terminal
type source ~/.bash_profile to reload it
it will work when you run python manage.py shell this time.
Make sure to activate your venv first by scripts/activate venv then in your populate_user.py right after import os run os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'epl.settings') this should work.
I have been through the tutorial on flask (http://flask.pocoo.org/docs/tutorial/introduction/)
And now I am getting errors, can you help me please? :)
On github it says this in the readme... (https://github.com/mitsuhiko/flask/tree/master/examples/flaskr/)
fire up a python shell and run this:
from flaskr import init_db; init_db()
So I open my python shell and type it in... Only problem is that I get an import error saying it cannot find flaskr...
If I try run the flaskr.py file locally I just get this
sqlite3.OperationalError OperationalError: unable to open database file
I am really new to this and python in general so any help would be great, thank you.
Have you created the database file?
On line 19 in flaskr.py, the path to the database is given.
DATABASE = '/tmp/flaskr.db'
That file needs to exist.
I'm new to programming, and tried to work through the flask tutorial.
http://flask.pocoo.org/docs/tutorial/
I'm stuck on this part (from the readme on github) when trying to run the app:
https://github.com/mitsuhiko/flask/tree/master/examples/flaskr/
Fire up a python shell and run this:
from flaskr import init_db; init_db()
I get this error when I try to run the command in python shell:
Import error: No module named flaskr
And I get this error when I try to run app locally:
sqlite3.OperationalError
OperationalError: unable to open database file
I've been looking for solution for several hours now, but to no avail.
Any thoughts on what I could check? Thank you.
The thing that fixed it for me was changing
export FLASK_APP=flaskr
to
export FLASK_APP=flaskr.py
Taken from here
The simplest way to accomplish what you need is to fire up the Python shell in the same folder as you have flaskr:
# I'm assuming that python is available on the command line
$ cd path/to/flaskr
$ python
# Python then runs and you can import flaskr
>>> from flaskr import init_db; init_db()
>>> exit()
The trick is that when you run Python it only looks in a certain number of places for modules and packages - you can see which places by running:
>>> from sys import path
>>> for fp in path:
... print fp
from the Python interpreter. If the path to flaskr is not in that list flaskr can't be imported. By default Python adds the directory it is started in to its search path (which is why we start Python in the directory that contains flaskr.)
Once you have run init_db you should be able to run the application and see everything working.
If you're using a version of Flask < 0.11, the flask command is not available. Install the flask-cli package in that case.
pip install flask-cli
To anyone else who finds this, add init_db() to the main executer to the end of your flaksr app as follows:
if __name__ == '__main__':
init_db()
app.run()
That should solve the sqlite error and stop you from having to run init_db() manually.
When we say :
export FLASK_APP=flaskr
by no means python understands where the package "flaskr.py" exists.
One of the way to solve the issue is choosing the right path where the "flaskr.py" resides. For eg, change your current working directory to where the file exists and :
export PYTHONPATH=`pwd`
Then you can execute "flask run" anywhere you want.
PS: flask tutorial seems broken. :)
Sean Viera's answer was very good, although I'd like to add that I was encountering the same problem and want to add to the solution. Running Python from the same flaskr folder was not enough for me. It was also necessary to activate Flask before running $Python by running the ". venv/bin/activate" command, like so:
$ cd path/to/flaskr
#active
$ . venv/bin/activate
(venv)$ python
# Python then runs and you can import flaskr
>>> from flaskr import init_db;
>>> init_db()
>>> exit()
$
Hope that extra bit of info helps!
$set FLASK_APP=flaskr
$python -m flask initdb
$python -m flask run
Try this:
OS: Windows
(venv)$pip install -I --no-deps Flask
(venv)$set FLASK_APP=flaskr
(venv)$set FLASK_DEBUG=1
(venv)$flask run
Explain:
$where flask will help to locate flask.exe
if virtual-env inherits flask from system-env
(venv)$where flask
>> /system/environment/path/to/flask.exe
(root)$where flask
>> /system/environment/path/to/flask.exe
obviously it calls flask.exe which is installed for system-env
(venv)$pip install -I Flask can force to (re)install flask for virtual-env
(venv)$pip install -I Flask
(venv)$where flask
>> /virtual/environment/path/to/flask.exe
>> /system/environment/path/to/flask.exe
I have same problem, and I have fixed it by.
step1:
sudo ln -sf /usr/bin/python3.4 /usr/bin/python
easy_install_3.4 flask.
PYTHONPATH=pwd
step2: using easy_install_3.4 to install falsk.
step3:
Heading