flaskr tutorial; can't import flaskr (initialize database) - python

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

Related

"Fatal error in launcher:" when using pip or flask

When I try to install anything with Pip, it gives me the "Fatal error in launcher:" error. That wouldn't be too bad, since I know how to update Pip differently. However, the same error occurs when I try to run the "flask run" command.
I'm using Windows 10, Python 3.8.2 and I have previously set the FLASK_APP variable to flaskblog.py. This is its content:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
Since you haven't posted the error clearly, if Fatal error in launcher: Unable to create process using ‘”‘ is your error,
then you might want to update pip using python -m pip install --upgrade pip and try installing your package again using python -m pip install <pkg-name>. You should get it working.
if the error persists after the above mentioned steps, the try importing pip in your python console(pull up your terminal and type python then type import pip) and try pip.main([‘install’,’<pkg-name>’]) in the console.
Hope this helps.
referred from here
Edit
Alternatively, you can run your flask app by adding app.run() in your script.
Like:
if __name__ == __main__:
app.run()
and then in the terminal, run python -m flaskblog.py.
Note: if you want to run your app in debug mode, consder giving debug = True to app.run().

python run ImportError:No module named

This is my project structure. I use virtualenv in my project but when I run it ,it has an ImportError.I use Mac.
But I can run it successfully use Pycharm
So how to run it successfully by Terminal.Because I want to run it in a Ubuntu server with cron
Thanks you for your answers.Here I show my solution.I modify my handler.py I think it may be related to The Module Search Path.
So I add the project path to the PYTHONPATH.
import os
project_home = os.path.realpath(__file__)
project_home = os.path.split(project_home)[0]
import sys
sys.path.append(os.path.split(project_home)[0])
import shutil
from modules import db, json_parse, config_out
from init_log import init as initlog
initlog()
if __name__ == '__main__':
try:
columns = json_parse.json_parse()
if not columns:
sys.exit()
is_table_has_exist = db.check_tables_exist(columns=columns)
if is_table_has_exist:
db.check_columns(columns=columns)
is_ok, config_path = config_out.output(columns)
if is_ok:
file_name = os.path.split(config_path)[1]
shutil.copy(config_path, os.path.join("/app/statics_log/config", file_name))
except Exception, e:
print e
And I run with crontab by this.
cd to/my/py_file/path && /project_path/.env/bin/python /path/to/py_file
example:
13 8 1 * * cd bulu-statics/create_config/ && /home/buka/bulu-statics/.env/bin/python /home/buka/bulu-statics/create_config/handler.py >> /app/statics_log/config/create_config.log
PyCharm automatically adds project directories marked as containing sources to the PYTHONPATH environment variable, whihc is why it works from within pycharm. On the terminal use
PYTHONPATH=${PWD}/..:${PYTHONPATH} python handler.py
You can use explicit relative imports:
from .modules import db, json_parse, config_out
The proper way to do this is to turn your project into a proper Python package by adding a setup.py file and then installing it with pip install -e .
probably because PyCharm added your project folder to the PythonPath, so you can run you app inside PyCharm.
However, when you try to run it from command line, python interpreter cannot find these libs in Python python, so what you need to do is to add your python virtualenv the python python.
there are different ways to adding python path, but I would suggest you to follow:
prepare a setup.py you'll need to specify packages and install_requires.
install your app locally in development mode via pip install -e /path/to/your-package -> it'll create a egg-link in your python virtualenv, you can run your app in your local terminal from now on;
for packing and releasing, you may want to build an artifact by following https://docs.python.org/2.7/distutils/builtdist.html
you may pip install or easy_install the artifact on your other machines. you also can release your package to PyPi if you want.

Cannot run a python script using crontab

I am struggling to run the a python script as a cron job.
I am logged in as root
the permission for the python script is
-rwxr-xr-x 1 root root 2374 Mar 1 22:49 k_collab_spark.2.py
I am starting the script with
#!/usr/bin/env python
I tested the pythong script
if i do "./k_collab_spark.2.py` this work fine.
on the crontab i have set the job as
15 12 * * * /opt/lampp/htdocs/testme/SPARK/k_collab_spark.2.py >> /var/log/kspark.log
I do not see any message on the log file
Once i adde 2>&1 it gives an error Traceback (most recent call last):
File "/opt/lampp/htdocs/kabeer/SPARK/k_collab_spark.2.py", line 2, in
import requests
ImportError: No module named requests but if i execute the service manually it is successful . WHen i run it manually it works fine
Tried defining the path but still the same issue
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
import requests
ImportError: No module named requests
Any idea what i am missing.. Appreciate any help around this.
Try to run script with another first line:
#!/usr/bin/python
If it's executes successfully the problem in python interpreter, because when you have several versions of Python installed, /usr/bin/env will ensure the interpreter used - is the first one on your environment's $PATH, which i guess has no requests lib.
Can you add python explicitly before the script name?
At the end of the crontab line, add 2>&1, which redirects error messages to the log file as well. See this link for a detailed description In the shell, what does " 2>&1 " mean?
There is also a possibility that your current user and root runs different versions of python.
I used a shell script to call the python script. THe anaconda on the box was causing the trouble
export PATH=/opt/anaconda3/bin:$PATH
/opt/anaconda3/bin/python /opt/lampp/htdocs/scriptme.py >/opt/lampp/htdocs/scriptme.log 2>&1
Add the following lines of code to your script and edit the crontab :
from distutils.sysconfig import get_python_lib
print(get_python_lib())
Now check the log in crontab, you will get some path
e.g. "/usr/lib/python2.7/dist-packages"
cd(change directory) to the above path and ls(list directory) to check if package exists ; if not :
sudo pip3 install requests -t . # dot indicates current directory
or else if you have a requirements.txt file then you could try:
sudo pip3 install -r requirements.txt -t "/usr/lib/python2.7/dist-packages"
#try this from the directory where "requirements.txt" file exists
Now run your scripts.

Django runserver under virtualenv using wrong version

I have Django 1.4.5 on my server and a working project.
I've used virtualenv to create an instance and installed Django 1.6.5 inside it (pip install Django==1.6.5).
If I simply run:
python manage.py runserver
Everything works fine and it starts a server using Django 1.6.5
But I have a file called run_devenv.py, which basically start my whole project using subprocesses. It starts server like this:
def run_devenv():
processes = [
...
('webserver', subprocess.Popen([PYTHON, 'manage.py', 'runserver', '0.0.0.0:%d' % HTTP_PORT, '--settings', os.environ['DJANGO_SETTINGS_MODULE']])),
...
]
if __name__ == '__main__':
if not os.access(settings.DEVENV_DIR, os.F_OK):
setup_devenv()
else:
run_devenv()
And for some reason it uses Django 1.4.5 instead of 1.6.5.
Looks like it uses 1.4.5 installed in the system and omits the virtualenv instance with 1.6.5.
Can someone help with this?
EDIT > Solution:
My problem was this string (I didn't show it):
PYTHON = "/usr/bin/python"
It should look like this:
PYTHON = "path_to_your_virtualenv/bin/python"
You need to call the python binary within your virtualenv instead of your system one. From your code it looks like PYTHON is a variable pointing to your python binary? If so, you should just have to change it like this:
PYTHON = "/path/to/your/virtualenv/bin/python"
I guess your script run_devenv.py is executable and has a declaration like #!/bin/python at the top. You can either alter which Python version runs the script or activate your virtualenv inside the script:
activate_this = '/path/to/env/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))
the python path is the issue
if youre using linux/osx the following command should work, assuming you've activated the virtualenv
sudo /path/to/bin/python manage.py runserver

Virtualenv issue with flask-werkzeug

I have installed virtualenv along with flask, werkzeug, jinja2 and SQLAlchemy. I was following the tutorial mentioned on the flask website and i came across the below error when executing flask code
Traceback (most recent call last):
File "hello.py", line 1, in ?
from flask import Flask
File "/root/myproject/env/lib/python2.4/site-packages/Flask-0.7dev_20110211-py2.4.egg/flask/__init__.py", line 18
from .app import Flask, Request, Response
^
What i feel is that virtualenv contains python 2.4 and in the documentation of flask it is mentioned that flask supports python 2.5. So maybe that might be the problem or it might be someother issue. Please help me out on this.
Secondly i would like to know the process of getting the latest virtualenv which has Python 2.7 or any tips on how to install it on virtualenv.
I am using CentOS
Thank You in Advance
The import .module syntax is introduced in Python 2.5 (relative import). So you have to use at least 2.5 for this thing.
dunno what you did and how old your virtualenv is .. but you make your own virtualenv by:
% python -c "import urllib, os; os.mkdir('py-env'); \
urllib.urlretrieve('http://goo.gl/D2RB', 'py-env/virtualenv.py')"
% python py-env/virtualenv.py --no-site-packages py-env
% source py-env/bin/activate
% pip install flask SQLAlchemy
that should work. virtualenv itself does not 'contain python'. do you run the correct version of python (dunno whats installed on your distro)?
There are a couple of posts below which should help:
http://cols-code-snippets.blogspot.com/2011/02/start-new-python-project-with.html
http://cols-code-snippets.blogspot.com/2011/02/my-take-on-flask-application-skeleton.html
So can we clarify what is meant when they say "virtualenv itself has no python" take a look in the corresponding bin/ or /lib directories when a env is created or what about the fact one can supply the -p flag when creating a virtualenv -p python2.7. So do as fear_matrix did, install the required python and then create a virtualenv with it "virtualenv -p python2.7". Maybe this is different on centos but I wouldn't think so.

Categories

Resources