Importing init_db (flask tutorial) - python

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.

Related

How do I get Phusion Passenger to recognize the correct version of Python for a web application?

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!

pylint with jenkins - complince that can't find xml file

I am trying to run pylint with jenkins with following command:
pylint -f parseable -d I0011,R0801 "mypath\highLevel" | tee.exe pylint.out
The process looks run fine, pylint.out created with a lot of information inside but during pylint report creation I get following error:
13:38:27 ERROR: Publisher hudson.plugins.violations.ViolationsPublisher aborted due to exception
13:38:27 java.io.FileNotFoundException: C:\Users\DMD\.jenkins\jobs\Diamond - Run Coverage\builds\2015-07-26_13-34-30\violations\file\A:\highLevel\Monitor\InitialBootAdapter.py.xml (The filename, directory name, or volume label syntax is incorrect)
It's creates very strange path:
C:\Users\DMD\.jenkins\jobs\Diamond - Run Coverage\builds\2015-07-26_13-34-30\violations\file\A:\highLevel\Monitor\InitialBootAdapter.py.xml
I don't really understand what happens.
Why pylint is interested in file InitialBootAdapter.py? Why it's looks for file InitialBootAdapter.py.xml? Who should create it and why? I searched for this file over all the environment and didn't find. But I did'nt find any xml for my other py files?
Maybe you have experience with pylint and can help?
Thank you.
I have experience with pylint in jenkins. And here is how I use it, hope it will help someone.
Step 1
Add a "Execute Shell" step and execute the pylint command to generate the pylint.out. Please note
/usr/local/bin/pylint -f parseable -d I0011,R0801 my-python-project-folder | tee pylint.out
Step 2
Make sure you have the Violation Report Plugin, after that , click Add post-build action-->Report Violation, put the pylint.out in the corresponding field.
And after the successful run, the pylint report looks like this:
I fixed the problem, it took time and DevOps help but it worked and is described in my own blog (it's more my online notebook than blog) in very small details.
The most important point in this post is small utility
import fileinput, sys
if __name__ == "__main__":
for line in fileinput.FileInput(sys.argv[1], inplace=True):
if ".cs" in line:
line = line.replace("\\", "/")
print line,
Here sys.argv[1] should be path to your violations.xml file.
You have to move the path as a command line argument to the utility as path to your violations.xml file is dynamic and depends on build id.

Stuck at Flask tutorial step 3

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.

Django documentation: Models; error from line 1 of code

In the Django documentation on Models, the first command that I am asked to run and python's response was:
>>> from django.db import models
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
from django.db import models
File "C:\Python26\lib\site-packages\django\db\__init__.py", line 11, in <module>
if DEFAULT_DB_ALIAS not in settings.DATABASES:
File "C:\Python26\lib\site-packages\django\utils\functional.py", line 184, in inner
self._setup()
File "C:\Python26\lib\site-packages\django\conf\__init__.py", line 40, in _setup
raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE)
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
As you can see from the stack trace, I am running a django server in python 2.6.6. Could anyone offer me a clue to start off on the right foot with this tutorial? Thanks in advance.
Are you running these commands from ./manage.py shell? You cannot run django commands from the regular python shell without specifying where your settings.py file is for the project. Django's ./manage.py shell command specifies that for you, making it easier to do django stuff on the command line.
If you don't see a file named manage.py in your current working directory, then that probably means you're not in the directory of your django application, or you haven't started one yet.
Edit: Also, that documentation is meant as an example of what to put in your application's models.py file, not something you should type in on the command line. That doesn't mean it won't work on the command line (if you use manage.py shell) but it isn't what the documentation is suggesting. Check the tutorial if you're unclear on how to start the shell and what files go where.
You're doing it wrong.
$ python manage.py shell
The answer here definitely works for the interactive prompt, which I was using, however I don't think that the intention of the first block of code was intended to actually be run! Immediately following that first code in the models documentation, you are expected to put the next codes into your models.py file created during the previous tutorial... I guess that's why they subtly labeled that section "Quick Example." What a headache!
Futhermore, that paragraph goes on to say "The above Person model would create a database table like..." suggesting that it was never intended to actually be run as-is.

Running Django custom manage.py task on Heroku - Importing Issues

I'm trying to run a custom django command as a scheduled task on Heroku. I am able to execute the custom command locally via: python manage.py send_daily_email. (note: I do NOT have any problems with the custom management command itself)
However, Heroku is giving me the following exception when trying to "Run" the task through Heroku Scheduler addon:
Traceback (most recent call last):
File "bin/send_daily_visit_email.py", line 2, in <module>
from django.conf import settings
ImportError: No module named django.conf
I placed a python script in /bin/send_daily_email.py, and it is the following:
#! /usr/bin/python
from django.conf import settings
settings.configure()
from django.core import management
management.call_command('send_daily_email') #delegates off to custom command
Within Heroku, however, I am able to run heroku run bin/python - launch the python shell - and successfully import settings from django.conf
I am pretty sure it has something to do with my PYTHON_PATH or visibility to Django's SETTINGS_MODULE, but I'm unsure how to resolve the issue. Could someone point me in the right direction? Is there an easier way to accomplish what I'm trying to do here?
Thank you so much for your tips and advice in advance! New to Heroku! :)
EDIT:
Per Nix's comment, I made some adjustments, and did discover that specifying my exact python path, I did get past the Django setup.
I now receive:
File "/app/lib/python2.7/site-packages/django/core/management/__init__.py", line 155, in call_command
raise CommandError("Unknown command: %r" % name)
django.core.management.base.CommandError: Unknown command: 'send_daily_email'
Although, I can see 'send_daily_email' when I run ``heroku run bin/python app/manage.py```.
I'll keep an update if I come across the answer.
You are probably using a different interpreter.
Check to make sure shell python is the same as the one you reference in your script /usr/bin/python . It could be that there is a different one in your path, which would explain why it works when you run python manage.py but not your shell scrip which you explicitly reference /usr/bin/python.
Typing which python will tell you what interpreter is being found on your path.
In addition, this can also be resolved by adding your home directory to your Python path. A quick and unobtrusive way to accomplish that is to add it to the PYTHONPATH environment variable (which is generally /app on the Heroku Cedar stack).
Add it via the heroku config command:
$ heroku config:add PYTHONPATH=/app
That should do it! For more details: http://tomatohater.com/2012/01/17/custom-django-management-commands-on-heroku/

Categories

Resources