NameError: name 'User' is not defined (when flask shell) - python

This is my microblog.py file, environment, centos7.
from app import app,db
from app.models import User,Post
#app.shell_context_processor
def make_shell_context():
return {'db':db,'User':User,'Post':Post}
when I input flask shell, and want to add User:
Python 3.6.5 (default, Apr 10 2018, 17:08:37)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
App: app [production]
Instance: /root/code/microblog/instance
>>> User
Traceback (most recent call last):
File "<console>", line 1, in <module>
NameError: name 'User' is not defined
>>>

This is what happens if you run flask shell (or venv/bin/flask shell) without first setting FLASK_APP=microblog.py.
FLASK_APP=microblog.py flask shell
Should get you going.

You need to import User from app.models. To do this, in terminal type:
>>> from app.models import User
>>> User
Then, user should be defined. Let me know if this works for you!

Related

Flask module not found even though it's installed

I am following this python tutorial on flask, I have created the virtual environment and the code runs fine without issues. But when I open an interactive shell inside the virtual environment and type:
from app import db
I get this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Repo\flask todo app\app.py", line 1, in <module>
from flask import Flask, render_template
ModuleNotFoundError: No module named 'flask'
When I try to install flask it says it's already installed, I am not sure what I am doing wrong?
The full console output:
(venv) C:\Repo\flask todo app>python3
Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from app import db
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Repo\flask todo app\app.py", line 1, in <module>
from flask import Flask, render_template
ModuleNotFoundError: No module named 'flask'
The code in app.py:
from email.policy import default
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)
class Todo(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.String(200), nullable=False)
completed = db.Column(db.Boolean, default=False)
date_created = db.Column(db.DateTime, default=datetime.utcnow)
def __repr__(self):
return '<Task {}>'.format(self.id)
#app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
Note: I can see flask.exe under this path:
C:\Users\username\AppData\Local\Programs\Python\Python39\Scripts
But it seems like I am using python 3.10.2 version in the shell, not sure if it's relevant here.
EDIT: I see that you are running python3 in your console... and that's it! Remember that you have to select a program to open. You should run python3 <your_program_name> instead.
Still, it will be easier for you to use the flask shell instead. To use it, run the flask shell command from your project directory while inside the virtual environment.
To access your project variables using the flask shell you have to create a shell_context_processor as follows:
# Insert this between your route definitions and the run statement
#app.shell_context_processor
def make_shell_context_processor():
# The dictionary below will include any variable you want to access from the flask shell. Eventually you'll want to include here, for example, your database models
return dict(db = db )
Miguel Grinberg (the author of an excellent Flask book and several courses) has an excellent entry in his blog where he explains the shell context processor in detail Do take a look at it (go to the "Shell Context" part, after the one titled "Playing with the database") and feel free to check his other entries if you have any other doubts with Flask.
Do you ensure the installation is ok? If not, please check it and ensure it.install flask on windows

NameError: name 'create_engine' is not defined in SQLAlchemy

I am attempting to create a python script that connects to an SQLITE database and using SQLAlchemy to help with this.
I am still very early, but am trying to create a connection to a new database but keep getting this "create_engine" is not defined in SQLAlchemy error.
To try to simplify I opened a python terminal to try it... see below:
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlalchemy
>>> engine = create_engine('sqlite:///test.db')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'create_engine' is not defined
>>> print(sqlalchemy.__version__)
1.3.18
>>>
At this point I don't even know where to go looking for the problem.
I did a pip uninstall sqlalchemy then pip install sqlalchemy hoping this might help.
Thanks to Gord Thompson. Changing this line:
engine = create_engine('sqlite:///test.db')
to:
engine = db.create_engine('sqlite:///test.db')
made it work!!

How do i upload tinkergraph into python/gremlin?

I am trying to use gremlin in python. I imported the following:
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
from gremlin_python.structure.graph import Graph
from gremlin_python import statics
from gremlin_python.process.graph_traversal import __
from gremlin_python.process.strategies import *
from gremlin_python.process.traversal import *
import asyncio
statics.load_statics(globals())
When i run this:
graph = TinkerGraph.open()
graph.io(graphml()).readGraph('air-routes.graphml')
i get the following error:
NameError: name 'TinkerGraph' is not defined
How do i resolve this?
There is no TinkerGraph in Python. In gremlin-python you only get a reference to a graph remotely on a server and that might be a TinkerGraph or something else. If you want to load data that way, you must issue that command as a script through a Client instance:
client = Client('ws://localhost:45940/gremlin', 'g')
client.submit("graph.io(graphml()).readGraph('air-routes.graphml');[]").all().result()
where "graph" in that script is a Graph instance that already exists on the server (and is likely empty). If you're using Gremlin Server, you might consider doing that loading separately as part of Gremlin Server startup as well and then just using gremlin-python to query that data. That would probably be best in this example as the data would just be present when the server is started.
Note that in 3.4.0, we introduce the io() step which will be part of gremlin-python directly at which point you will be able to directly do:
g.io('air-routes.xml').read()
in native python and it will just work (again, the Graph instance must be defined remotely) though the file must be readable by the server.
Here's my working example in the Python shell for submitting a script, first with the tornado error and then without:
$ env/bin/python
Python 3.4.3 (default, Nov 28 2017, 16:41:13)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from gremlin_python.driver.client import Client
>>> client = Client('ws://localhost:8182/gremlin', 'g')
>>> client.submit("g.V()").all().result()
Traceback (most recent call last):
File "/home/smallette/git/apache/incubator-tinkerpop/gremlin-python/target/python3/gremlin_python/driver/client.py", line 51, in __init__
from gremlin_python.driver.tornado.transport import (
File "/home/smallette/git/apache/incubator-tinkerpop/gremlin-python/target/python3/gremlin_python/driver/tornado/transport.py", line 19, in <module>
from tornado import ioloop, websocket
ImportError: No module named 'tornado'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/smallette/git/apache/incubator-tinkerpop/gremlin-python/target/python3/gremlin_python/driver/driver_remote_connection.py", line 45, in __init__
password=password)
File "/home/smallette/git/apache/incubator-tinkerpop/gremlin-python/target/python3/gremlin_python/driver/client.py", line 54, in __init__
raise Exception("Please install Tornado or pass"
Exception: Please install Tornado or passcustom transport factory
>>> exit
Use exit() or Ctrl-D (i.e. EOF) to exit
>>> exit()
$ env/bin/pip install tornado
Collecting tornado
Collecting backports-abc>=0.4 (from tornado)
Using cached https://files.pythonhosted.org/packages/7d/56/6f3ac1b816d0cd8994e83d0c4e55bc64567532f7dc543378bd87f81cebc7/backports_abc-0.5-py2.py3-none-any.whl
Installing collected packages: backports-abc, tornado
Successfully installed backports-abc-0.5 tornado-5.1.1
smallette#ubuntu:~/git/apache/incubator-tinkerpop/gremlin-python/target/python3$ env/bin/python
Python 3.4.3 (default, Nov 28 2017, 16:41:13)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from gremlin_python import statics
>>> client = Client('ws://localhost:8182/gremlin', 'g')
>>> client.submit("g.V()").all().result()
[v[0]]

Python3 on Ubuntu giving errors on help() command

I used help() in the python3 shell on Ubuntu 14.04
I got this output
Please help , don't know whats wrong.
Python 3.4.0 (default, Apr 11 2014, 13:05:11)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> help()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.4/_sitebuiltins.py", line 98, in __call__
import pydoc
File "/usr/lib/python3.4/pydoc.py", line 65, in <module>
import platform
File "/home/omega/platform.py", line 2, in <module>
print("System : ",platform.uname().system)
AttributeError: 'module' object has no attribute 'uname'
>>>
The problem is that platform is the name of a stdlib module, which help uses. By creating a module of your own with the same name that occurs before the stdlib in your sys.path, you're preventing Python from using the standard one.
The fact that your own platform module tries to use the stdlib module of the same name just compounds the problem. That isn't going to work; your import platform inside that module is just importing itself.
The solution is to not collide names like this. Look at the list of the standard modules, and don't create anything with the same name as any of them if you want to use features from that module, directly or indirectly.
In other words: Rename your platform.py to something else, or put it inside a package.
File "/home/omega/platform.py", line 2, in <module>
print("System : ",platform.uname().system)
This is the problem, go to platform.py and fix it, it will be ok. It says, platform has not any method called uname you probably misstyped.

qrcode for python on linux

I have an error when i used pyqrcode.
[root#localhost python2.6]# python
Python 2.6.5 (r265:79063, Sep 7 2010, 07:31:57)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import qrcode
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.6/site-packages/qrcode-0.2.1-py2.6-linux-x86_64.egg/qrcode/__init__.py", line 6, in <module>
from qrcode import _qrcode
ImportError: cannot import name _qrcode
How to resolve above error?
I am referring pyqrcode from http://pyqrcode.sourceforge.net/
Thanks,
Manu
After the installation of PIL-1.1.7 and JCC-2.14, I've tried to install pyqrcode-0.2.1 from sources as you did, and also ran into the same error :
ImportError: No module named _qrcode. But then I've noticed that _qrcode is actually a lib (_qrcode.so). So I've tried to add it on my library path :
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib/python2.7/site-packages/qrcode-0.2.1-py2.7-linux-x86_64.egg/qrcode/
And it worked ! Well actually, not quite, I ran into another error :
AttributeError: 'module' object has no attribute '_setExceptionTypes'
So I've edited the __init__.py file
# probably located under a path like this for linux
/usr/local/lib/python2.7/site-packages/qrcode-0.2.1-py2.7-linux-x86_64.egg/qrcode/
# or under a path like this for a Mac
/Library/Python/2.7/site-packages/qrcode-0.2.1-py2.7-macosx-10.7-intel.egg/qrcode/
and commented out line 21 :
# _qrcode._setExceptionTypes(JavaError, InvalidArgsError)
Then I was able to run their simple example :
#!/usr/bin/env python
# coding: utf-8
#
# pyqrcode sample encoder
import sys, qrcode
e = qrcode.Encoder()
image = e.encode('woah!', version=15, mode=e.mode.BINARY, eclevel=e.eclevel.H)
image.save('out.png')
(source : http://pyqrcode.sourceforge.net/)
Hope it helps,

Categories