I am trying to make a database in my terminal but when I try it I always get this error when I use from first import db:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'first'
Here is my code
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///posts.db'
db = SQLAlchemy(app)
class BlogPost(db.Model):
id = db.Column(db.Integer, primary_key= True)
Title = db.Column(db.String(100), nullable= False)
Content = db.Column(db.Text, nullable= False)
Date_posted = db.Column(db.DateTime, nullable= False, default=datetime.utcnow)
def __repr__(self):
return "Blog Post" + str(self.id)
all_posts = [
{
'Title': 'Post 1',
'Content': "This is the first content"
},
{
'Title': 'Post 2',
'Content': 'This is the second content'
}
]
#app.route('/')
def index():
return render_template("index.html")
#app.route('/blog-posts')
def blog_posts():
return render_template("posts.html", posts = all_posts)
#app.route('/home')
def hello():
return "My first python website"
if __name__ == '__main__':
app.run(debug= True)
I only have python 3.8 installed.
What could be the problem? I've searched the internet and used every advice on other platforms yet no solution. Flask and flask-sqlalchemy are installed properly.
This is the youtube video I use as a guide when creating this project:
https://www.youtube.com/watch?v=3mwFC4SHY-Y
Well I am assuming you have created a python file named first. I am listing out what could have been gone wrong:
You are in the wrong directory.
You have not installed the necessary package. (unlikely)
According to the tutorial, the file name is app.py so there he performs from app import db. Just make sure you have the name of the file correct.
I am not able to think of any other probable cause, unless first is a package create by you to store the project's python files like routes.py, models.py, etc. In that case you need to have __init__.py file in the package directory and initialize app and db in __init__.py file
Related
It´s muy first time developing an API. It's very simple. here is my code:
from flask import Flask, Response
from flask import request
from flask import jsonify
import pyodbc
from sqlalchemy import create_engine,Integer
import pandas as pd
import urllib
app = Flask(__name__)
params = urllib.parse.quote_plus("DRIVER={SQL Server Native Client 11.0};"
"SERVER=xxx.xx.x.x;"
"DATABASE=xxxxx;"
"UID=xxxx;"
"PWD=xxxx")
engine = create_engine('mssql+pymssql://xxxx:xxxx#xxx.xx.x.x/xxxx')
sql_talle = "RSCV_TALLE_PARA_CADA_MARCA.sql"
fd1 = open(sql_talle, 'r')
sqlFile1 = fd1.read()
fd1.close()
DF1 = pd.read_sql_query(sqlFile1,engine)
DF1.insert(14, 'PROVEEDOR', DF1.pop('PROVEEDOR'))
periodo=DF1['YEARMONTH_DATE'].drop_duplicates()
NIKE=DF1.loc[DF1['MARCA'] == 'NIKE']
NIKE=NIKE.to_dict('records')
#app.route('/NIKE',methods = ['GET'])
def show_codigo_Agrupador():
if request.method == 'GET':
response = jsonify({'NIKE':NIKE})
response.status_code = 200
return response
if __name__ == "__main__":
app.run(debug=True)
it´s working fine!
when I run the .py on a terminal I get that it´s Running on http://127.0.0.1:5000
After that I try to do a request on another .py, simulating an external user:
import requests
import json
url = 'http://127.0.0.1:5000/NIKE'
r=requests.get(url)
response=r.text
j=response.json()
print(j)
but I get this error:
Traceback (most recent call last):
File "c:\Users\mvazquez\DABRA\FLASK_API\prueba_request_api.py", line 7, in <module>
j=response.json()
AttributeError: 'str' object has no attribute 'json'
I have these questions:
what am I doing wrong here?
my data is based on an sql query, I need to run the script every day to have refresehed data or it is refreshed when request is done? (sorry if it's stupid, I have no idea about API)
thanks in advance!
I'm new to flask, and have problem with importing db while running from python console/cmd.
I'm facing this error :
In[67]: os.getcwd()
Out[67]: 'C:\\Users\\Desktop\\Python\\Flask'
In[68]: os.listdir()
Out[68]:
['app',
'app.db',
'config.py',
'Flask.py',
'migrations',
'venv',
'__init__.py',
'__pycache__']
In[69]: from Flask.app.models import User,Post
Traceback (most recent call last):
File "C:\Users\AppData\Local\Continuum\anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3326, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-69-dca3714f084d>", line 1, in <module>
from Flask.app.models import User,Post
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.3\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
File "C:\Users\Desktop\Python\Flask\app\models.py", line 1, in <module>
from Flask.app import db
ImportError: cannot import name 'db' from 'Flask.app' (C:\Users\Desktop\Python\Flask\app\__init__.py)
The tree of my project :
Flask/
app/
__init__.py
forms.py
models.py
routes.py
__init__.py
config.py
Flask.py
Flask/init.py
app/init.py
from flask import Flask
from Flask.config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
from Flask.app import routes, models
app/models.py
from Flask.app import db
from datetime import datetime
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
password_hash = db.Column(db.String(128))
def __repr__(self):
return '<User {}>'.format(self.username)
When running flask run via command it's working fine. But I when I'm trying to run via python console or cmd I'm not able to run successfully.
Thanks
there is a problem when importing module fix this....
inside Flask remove the __init_.py here u didnt want a init file.if the Flask folder is the root folder others are sub folders inside it I guess your main file is Flask.py. So
change the
from Flask.app import db
to
from app import db
considering db is declared inside app/init.py
Ok so I am new to flask and i am trying to set up a simple task manager. And I have a problem with importing my database.
When I made my first import my db was named User and it had fields like email, username, ...
Now all I did was renaming the call of database form User to Task and changed some fields or added more.
and now when I run a command:
>>> from app.models import Task
I get an error:
Traceback (most recent call last):
File "<input>", line 1, in <module>
ImportError: cannot import name 'Task' from 'app.models' (/Users/janzaplatil/Desktop/taskmanager/app/models.py)
but if I run a >>> from app.models import User all is fine. But it makes no sense to me since there is no class User, only Task
My model python file:
from datetime import datetime
from app import db
class Task(db.Model):
id = db.Column(db.Integer, primary_key=True)
task = db.Column(db.String(64), index=True, unique=True)
description = db.Column(db.String(120), index=True, unique=True)
start = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
password_hash = db.Column(db.String(128))
def __repr__(self):
return '<Task {}>'.format(self.task)
My flask app:
from app import app, db
from app.models import Task
#app.shell_context_processor
def make_shell_context():
return {'db': db, 'Task': Task}
Ello ello,
I found similar questions on the bug i'm facing, and tried the solutions offered but it didn't work for me.
I'm trying to separate out my models in a different directory and import them into the app.py
When I try to import the db into the python terminal, i'm getting the no application found.
app.py code
from flask import Flask
from flask_restful import Resource, Api
# from flask_sqlalchemy import SQLAlchemy
from routes import test, root, user
from models.todo import db
app = Flask(__name__)
api = Api(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://username:pass123#localhost/db'
app.config['SECRET_KEY'] = 'thiskeyissecret'
# db.init_app(app)
with app.app_context():
api = Api(app)
db.init_app(app)
api.add_resource(root.HelloWorld, '/')
api.add_resource(test.Test, '/test')
api.add_resource(user.User, '/user')
if __name__ == '__main__':
app.run(debug=True)
models
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Todo(db.Model):
__tablename__ = 'Todos'
id = db.Column('id', db.Integer, primary_key=True)
data = db.Column('data', db.Unicode)
def __init__(self, id, data):
self.id = id
self.data = data
def __repr__(self):
return '<Todo %>' % self.id
my file directory looks like
Main_app
Models
Todo.py
routes
some routes
app.py
Flask-SQLAlchemy needs an active application context.
Try:
with app.app_context():
print(Todo.query.count())
From the flask documentation:
Purpose of the Context
The Flask application object has attributes, such as config, that are
useful to access within views and CLI commands. However, importing the
app instance within the modules in your project is prone to circular
import issues. When using the app factory pattern or writing reusable
blueprints or extensions there won’t be an app instance to import at
all.
Flask solves this issue with the application context. Rather than
referring to an app directly, you use the the current_app proxy, which
points to the application handling the current activity.
Flask automatically pushes an application context when handling a
request. View functions, error handlers, and other functions that run
during a request will have access to current_app.
It is ok to have db initialised in app.py
from flask import Flask
from flask_restful import Api
from flask_sqlalchemy import SQLAlchemy
from routes import test, root, user
app = Flask(__name__)
api = Api(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://username:pass123#localhost/db'
app.config['SECRET_KEY'] = 'thiskeyissecret'
db = SQLAlchemy(app)
api.add_resource(root.HelloWorld, '/')
api.add_resource(test.Test, '/test')
api.add_resource(user.User, '/user')
if __name__ == '__main__':
app.run(debug=True)
Then in your todo.py
from app import db
class Todo(db.Model):
__tablename__ = 'Todos'
id = db.Column('id', db.Integer, primary_key=True)
data = db.Column('data', db.Unicode)
def __init__(self, id, data):
self.id = id
self.data = data
def __repr__(self):
return '<Todo %>' % self.id
I get a same err
that err reason for just can operation db in viewfunc
def __init__(self, id, data):
self.id = id
self.data = data
try move that code operation to your viewfunc
In a nutshell, do something like this:
from yourapp import create_app
app = create_app()
app.app_context().push()
What am I doing?
I had been learning from a Flask tutorial (https://blog.miguelgrinberg.com/) and I'm stuck on the ORM section as it uses SQLAlchemy and I want to use Peewee (I use it in another project, and had been working nicely on it).
Noob Problematic
After configuring Peewee and define a BaseModel, and implementing it in a User model, I tried to do a query and got this error instead:
File "/home/atrevino/.local/share/virtualenvs/comparteme-qStpFUrM/lib/python3.6/site-packages/peewee.py", line 2932, in compiler
return self.database.compiler()
AttributeError: 'Flask' object has no attribute 'compiler'
Not sure if this is related to the configuration of my database, but I was able to get the MySQLDatabase object which makes me to think it's doing a connection to the DB properly.
The error above is displayed whenever I try to do something with Peewee's models, for example User.get(User.id == 1) or User.create(username='Name')
This is my test-app and environment configuration
./config.py
import os
class Config(object):
SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-know'
DATABASE = {
'name': 'comparteme',
'engine': 'peewee.MySQLDatabase',
'user': 'root',
'password': 'whatever',
'host': os.environ.get('DATABASE_URL') or 'mysql://root#localhost:3306'
}
comparteme/__init__.py
import peewee
from flask import Flask
from config import Config
app = Flask(__name__)
app.config.from_object(Config)
db = peewee.MySQLDatabase(app).database
from comparteme import routes
comparteme/models/base_model.py
import peewee
from comparteme import db
class BaseModel(peewee.Model):
class Meta:
database = db
class User(BaseModel):
username = peewee.CharField(unique=True)
I call all this from a flask route:
comparteme/routes.py
from comparteme import app
from comparteme.models.base_model import User
#app.route('/')
#app.route('/index')
def index():
User.create(username='Alan')
return 'returning any string'
To be able to test I have one test.py on my root directory that I added to FLASK_APP environment variable by using export FLASK_APP=test.py.
./test.py
from comparteme import app
After that I just do a regular flask run and open a browser with http://127.0.0.1:5000/ and get the error.
Is this the correct way to configure Peewee?
Thanks in advance !!!