I get an Import error while importing the thermos.py module in my models.py module.
C:\Users\sys\Thermos\thermos\thermos.py
C:\Users\sys\Thermos\thermos\models.py
Here is the relevant part of the thermos.py module.
import os
from datetime import datetime
from flask import Flask, render_template, url_for, request, redirect, flash
from flask_sqlalchemy import SQLAlchemy
basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'thermos.db')
db = SQLAlchemy(app)
And, here is the relevant part of the models.py module.
from datetime import datetime
from thermos import db
Here is the image of the error I receive in CMD:
Kindly let me know what needs to be done to fix this issue.
Python can't decide if you're trying to import from the folder, or the file named thermos
You can rename
C:\Users\sys\Thermos\thermos\thermos.py
To
C:\Users\sys\Thermos\thermos\__init__.py
This makes the thermos directory a package with the db variable that can be used with an import
from . import db
Related
We are trying to connect to our instance of the CalendarStore but we don't understand the exception, that we get back when executing the code.
The Error we're having:
org.codehaus.groovy.runtime.InvokerInvocationException: net.fortuna.ical4j.connector.ObjectStoreException: net.fortuna.ical4j.connector.FailedOperationException: Principals not found
We also know that the error occurs in line 62. Please note that I have edited the strings in the variables to not expose them to the public.
import com.github.caldav4j.CalDAVCollection;
import com.github.caldav4j.CalDAVConstants;
import com.github.caldav4j.exceptions.CalDAV4JException;
import com.github.caldav4j.methods.CalDAV4JMethodFactory;
import com.github.caldav4j.methods.HttpGetMethod;
import com.github.caldav4j.model.request.CalendarQuery;
import com.github.caldav4j.util.GenerateQuery;
import net.fortuna.ical4j.connector.ObjectStoreException;
import net.fortuna.ical4j.connector.dav.CalDavCalendarCollection;
import net.fortuna.ical4j.connector.dav.CalDavCalendarStore;
import net.fortuna.ical4j.connector.dav.PathResolver;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.*;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.routing.HttpRoutePlanner;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.DefaultRoutePlanner;
import org.apache.http.impl.conn.DefaultSchemePortResolver;
import org.apache.http.protocol.HttpContext;
import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.model.Component;
import net.fortuna.ical4j.model.ComponentList;
import net.fortuna.ical4j.model.component.VEvent;
import net.fortuna.ical4j.model.Date;
import net.fortuna.ical4j.data.CalendarBuilder;
import net.fortuna.ical4j.data.ParserException;
import net.fortuna.ical4j.connector.CalendarStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClients;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.List;
String USER = "User";
String PASS = "dont matter";
g_log.info("Start");
String uri = "our uri";
String prodId = "hm";
URL url = new URL("Our url");
PathResolver pathResolver = PathResolver.CHANDLER;
CalendarStore<CalDavCalendarCollection> calendarStore = new CalDavCalendarStore(prodId, url, pathResolver);
boolean testCon = calendarStore.connect(USER.toString(), PASS.toCharArray());
g_log.info("testCon: "+ testCon);
I am writing unit test cases for my app.py file. I have created a setUp() function in my test file but the moment I execute any test case, it throws an error like
============================= test session starts ==============================
platform linux -- Python 3.6.9, pytest-6.1.1, py-1.9.0, pluggy-0.13.1 -- /home/curiousguy/PycharmProjects/leadgen/venv/bin/python
cachedir: .pytest_cache
rootdir: /home/curiousguy/PycharmProjects/leadgen/tests
plugins: cov-2.10.1
collecting ... ENV :None
test_app.py:None (test_app.py)
test_app.py:5: in <module>
from app import app
../app.py:7: in <module>
from appli import appli
../appli.py:6: in <module>
appli = create_app(db, config_name)
../app_setup.py:21: in create_app
leadgen_app.config.from_object(app_config[config_name])
E KeyError: None
collected 0 items / 1 error
==================================== ERRORS ====================================
_________________________ ERROR collecting test_app.py _________________________
test_app.py:5: in <module>
from app import app
../app.py:7: in <module>
from appli import appli
../appli.py:6: in <module>
appli = create_app(db, config_name)
../app_setup.py:21: in create_app
leadgen_app.config.from_object(app_config[config_name])
E KeyError: None
The test file is:
import unittest
from unittest.mock import patch
import pytest
# from appli import appli
from app import app
#import app
class MyApp(unittest.TestCase):
def setUp(self):
app.testing = True
self.client = app.test_client()
def tearDown(self):
pass
def test_settings_passed(self):
response = self.client.get('/settings', follow_redirects=True)
self.assertEqual(response.status_code, 200)
with pytest.raises(AssertionError) as wt:
self.assertEqual(response.status_code, 403)
Since the errors are pointing to different files I am adding those files as well.
app.py
import functools
import pickle
from flask import (redirect, render_template, request, Response, session, url_for)
from flask_login import LoginManager, login_user, current_user
from flask_admin import Admin
from ldap3 import Server, Connection, ALL, SIMPLE
from appli import appli
import datetime
from modules.controller import application
from modules.users_view import MyAdminIndexView, UsersView
from database.db_model import (Companies, Users, Leads, db)
###########################################################
# Init section #
###########################################################
app = appli
login_manager = LoginManager()
login_manager.login_view = "login"
login_manager.init_app(app)
server = Server(app.config['LDAP_SERVER'],
port=app.config['LDAP_PORT'], get_info=ALL)
server_tor = Server(app.config['LDAP_SERVER_TOR'],
port=app.config['LDAP_PORT'], get_info=ALL)
admin = Admin(app, name='LEADGEN Admin', index_view=MyAdminIndexView(), base_template='master.html')
admin.add_view(UsersView(Users, db.session))
application_inst = application("Lead Generator")
#rest of code
appli.py
import os
from app_setup import create_app
from database.db_model import db
config_name = os.getenv('FLASK_ENV')
appli = create_app(db, config_name)
if __name__ == '__main__':
appli.run()
app_Setup.py
def create_app(db,config_name):
leadgen_app = Flask(__name__, instance_relative_config=True)
# config_name = os.getenv('FLASK_ENV', 'default')
print('ENV :' + str(config_name))
# leadgen_app.config.from_object(eval(settings[config_name]))
leadgen_app.config.from_object(app_config[config_name])
leadgen_app.config.from_pyfile('config.cfg', silent=True)
# Configure logging
leadgen_app.logger.setLevel(leadgen_app.config['LOGGING_LEVEL'])
handler = logging.FileHandler(leadgen_app.config['LOGGING_LOCATION'])
handler.setLevel(leadgen_app.config['LOGGING_LEVEL'])
formatter = logging.Formatter(leadgen_app.config['LOGGING_FORMAT'])
handler.setFormatter(formatter)
leadgen_app.logger.addHandler(handler)
leadgen_app.logger.propagate = 0
# Configure sqlalchemy
leadgen_app.app_context().push()
db.init_app(leadgen_app)
# with leadgen_app.app_context():
# db.create_all()
from leads.leads_bp import leads_bp
from process.process_bp import process_bp
from CAAPI.caapi_bp import caAPI_bp
leadgen_app.register_blueprint(leads_bp)
leadgen_app.register_blueprint(process_bp)
leadgen_app.register_blueprint(caAPI_bp)
return leadgen_app
Where am I making a mistake to run my test case successfully?
The KeyError is caused by app_config[config_name].
config_name comes from config_name = os.getenv('FLASK_ENV').
getenv defaults to None when no value is set, see https://docs.python.org/3/library/os.html#os.getenv
This means you have to set the environment variable in order to make tests pass.
You could also debug your application with pdb - I gave a lightning talk how to debug a Flask application...
https://www.youtube.com/watch?v=Fxkco-gS4S8&ab_channel=PythonIreland
So I figured out an answer to this. here is what I did.
I made changes to my setUp() function in my testcase file
def setUp(self):
self.app = create_app(db)
self.client = self.app.test_client(self)
with self.app.app_context():
# create all tables
db.create_all()
and then I imported from app_setup import create_app in my testcase file. And finally I made changes in app_setup.py in function
def create_app(db, config_name='default')
And my testcases are now running.
I am trying to understand how flask and sqlalchemy works.Below is my app structure
init.py contains
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
import User
# Create a login manager object
login_manager = LoginManager()
app = Flask(__name__)
# Often people will also separate these into a separate config.py file
app.config['SECRET_KEY'] = 'mysecretkey'
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
Migrate(app, db)
model.py
from test import db
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
class User(db.Model, UserMixin):
# Create a table in the db
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(64), unique=True, index=True)
def __init__(self, email, username, password,first_name,last_name):
self.email = email
and app.py
# This is app.py, this is the main file called.
from test import app
from flask import render_template
#app.route('/')
def index():
return 'Hello World'
if __name__ == '__main__':
app.run(debug=True)
and I am using below commands to create tables
set FLASK_APP=
flask db init
flask db migrate -m
But flask migrate is not detecting table and displays below message
I am unable to figure how to resolve this issue.Could someone please highlight what I am doing wrong.Thanks
You need to import model in __init__.py
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
import User
# Create a login manager object
login_manager = LoginManager()
app = Flask(__name__)
# Often people will also separate these into a separate config.py file
app.config['SECRET_KEY'] = 'mysecretkey'
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
Migrate(app, db)
from app import model
This is because model.py depends on __init__.py
I am having a server.py file which is written in Falcon. Which looks like this.
try:
import falcon, logging
from os.path import dirname, realpath, join
from wsgiref import simple_server
from .config.config import server_config
from .middlewares.SQLAlchemySessionManager import SQLAlchemySessionManager
from .middlewares.GlobalInternalServerErrorManager import InternalServerErrorManager
from .lib.dbConnector import Session
from .routes import router
except ImportError as err:
falcon = None
raise err
serv_conf = server_config()
salescoachbot = falcon.API(middleware= [
SQLAlchemySessionManager(Session),
InternalServerErrorManager()
])
But when I am trying to import "salescoachbot" to other folder and files
like:
from ..server import salescoachbot
This gives me an error saying that the
from ..server import salescoachbot
ImportError: cannot import name 'salescoachbot'
The server.py is in the root of the project and has an init.py as well as the file which is trying to import the name.
What am I doing wrong here?
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 !!!