Flask ' application not registered on db' - flask-sqlalchemy

I tried to check answers to other questions with the same error. But the situation of those seem different from mine.
I can use Role.query.all() in .\xxxapp\admin\views.py, but when I call Role.query.all() in .\xxxapp\admin\forms.py, I got this:
raise RuntimeError('application not registered on db '
RuntimeError: application not registered on db instance and no application bound to current context
My folders are like this:
.\
|-xxxapp\
| |-admin\
| | |__init__.py
| | |forms.py
| | |views.py
| |-user\
| | |__init__.py
| | |forms.py
| | |models.py
| | |views.py
| |....
| |-extensions.py
| |-app.py
|manage.py
app is created in .\xxxapp\extensions.py by a app creator function 'create_app', and db is created in .\xxxapp\extensions.py. All initiators such as db.init(app) are called in 'create_app'. While 'create_app' is called in manage.py. I don't understand why in views.py app and db know each other while in forms.py they don't.
Now here is my code in .\xxxapp\admin\views.py
from flask.ext.wtf import Form
from xxxapp.user.models import User, Role
class UserForm(Form):
roles = Role.query.all() # this doesn't work
...
and .\xxxapp\admin\models.py
from flask import (current_app, Blueprint, request, render_template, flash, url_for, redirect, session)
from flask.ext.user import current_user, login_required, roles_required
from xxxapp.extensions import db, user_manager
from xxxapp.user.models import User, Role
blueprint = Blueprint('admin', __name__, static_folder="../static")
#blueprint.route('/user/<int:user_id>', methods=['GET', 'POST'])
#login_required
#roles_required('admin')
def user(user_id):
roles = Role.query.all() #this works
Class Role is defined in .\xxxapp\user\models.py:
from xxxapp.extensions import db
.....
class Role(db.Model):
id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(50), unique=True)
description = db.Column(db.String(255))
app factory in app.py contains:
...(imported modules are omitted)
...
__all__ = ['create_app']
DEFAULT_BLUEPRINTS = (frontend,d5user,api,admin)
def create_app(config=None, app_name=None, blueprints=None):
if app_name is None:
app_name = DefaultConfig.PROJECT
if blueprints is None:
blueprints = DEFAULT_BLUEPRINTS
app = Flask(import_name=app_name, instance_path=INSTANCE_FOLDER_PATH, instance_relative_config=True)
app.config.from_object(DefaultConfig)
mail = Mail(app)
init_error_logger_with_email_handler(app)
register_extensions(app)
register_blueprints(app, blueprints)
register_errorhandlers(app)
configure_template_filters(app)
return app
def register_blueprints(app, blueprints):
for blt in blueprints:
app.register_blueprint(blt)
def register_extensions(app):
assets.init_app(app)
bcrypt.init_app(app)
cache.init_app(app)
db.init_app(app)
debug_toolbar.init_app(app)
migrate.init_app(app, db)
user_manager.init_app(app) # Init Flask-User and bind to app
return None
... more registration function are omitted.
I must have missed something, but have no clue where. Maybe it is an easy problem for experienced. Any suggestion will be appreciated.

Related

Flask not storing data to database

Database not storing flask data models. Even though the database gets created.
Using postrges, the tables get created in bash view but not in pgAdmin. I have a simple app that needs to store data. Would appreciate help.'
Code uses SQLAlchemy. DO i need to use different library. I am using psycopg2 and sessions but havent imported sessions.
#!flask/bin/python
#!flask/bin/python
from os import linesep
from typing import Mapping, Type from flask
import Flask, jsonify
from flask import request
from slotscal import results
from flask_sqlalchemy
import SQLAlchemy
import time
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']= 'postgresql+psycopg2://postgres:test123#localhost:5432/hqw' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db=SQLAlchemy(app)
db.metadata.clear()
#add parenrts
class Contracts(db.Model):
name=db.Column(db.String(100))
address=db.Column(db.String(42), unique=True, primary_key=True)
fileName=db.Column(db.Integer)
Functions= db.relationship('Function')
Variables= db.relationship('Variable')
StateVariables=db.relationship('StateVariable')
def __init__(self,address,fileName,id,StateVariables,name):
self.address=address
self.fileName=fileName
self.id=id
self.StateVariables=StateVariables
self.name=name
class Function(db.Model):
id=db.Column(db.String(42), db.ForeignKey('contracts.address'), primary_key=True)
name=db.Column(db.String)
lines=db.Column(db.Integer)
ReachingTime=db.Column(db.DateTime)
TrackingTime=db.Column(db.DateTime)
Arguments= db.relationship('Arguments')
def __init__(self,address,ReachingTime,id,TrackingTime,name,lines):
self.address=address
self.ReachingTime=ReachingTime
self.TrackingTime=TrackingTime
self.id=id
self.lines=lines
self.name=name
class Argument(db.Model):
id=db.Column(db.String(42), db.ForeignKey('function.id'), primary_key=True)
Type=db.Column(db.String)
Value=db.Column(db.String)
Name=db.Column(db.String)
def __init__(self,Name, id,Type,Value):
self.Name=Name
self.id=id
self.Type=Type
self.Value=Value
class Variable(db.Model):
VariableName=db.Column(db.String)
id=db.Column(db.String(42),db.ForeignKey('contracts.address'),primary_key=True)
Type=db.Column(db.String)
Value=db.Column(db.String)
StateVaruiable=db.Column(db.Boolean)
Mapping=db.Column(db.Boolean)
def __init__(self,address,Value,Type,id,StateVariables,name):
self.address=address
self.Type=Type
self.Value=Value
self.id=id
self.StateVariables=StateVariables
self.name=name
class m(db.Model):
id=db.Column(db.String(42),db.ForeignKey('variable.id'), primary_key=True)
Type=db.Column(db.String)
Source=db.Column(db.String)
def __init__(self,Type,Source,id):
self.Type=Type
self.id=id
self.Source=Source
class StateVariable(db.Model):
id=StateVariableType=db.Column(db.String)
StateVariableValue=db.Column(db.String)
id=db.Column(db.String(42),db.ForeignKey('contracts.address'),primary_key=True)
def __init__(self,id,StateVariableType,StateVariableValue):
self.StateVariableType=StateVariableType
self.StateVariableValue=StateVariableValue
self.id=id
class Key(db.Model):
id=db.Column(db.String(42),db.ForeignKey('m.id'), primary_key=True)
Value=db.Column(db.String)
Type=db.Column(db.String)
def __init__(self,Value,id,Type):
self.id=id
self.Value=Value
self.Type=Type
class Analysis(db.Model):
id=db.Column(db.String(42),db.ForeignKey('contracts.address'),primary_key=True)
FullTime=db.Column(db.DateTime)
StateVariables=db.Column(db.Integer)
def __init__(self,id,FullTime):
self.id=id
self.FullTime=FullTime
#app.route('/') def index():
return "Hello, World!" #app.route('/process', methods=['POST']) def process():
#print ('h')
header=request.json
#print ('g')
code=header['code']
f=open('code.sol','w')
f.write(code)
f.close()
path='./code.sol' #filename
subcon=header['name'] #name
add=header['address'] #address
contract=Contracts(subcon,add,path)
db.session.add(contract)
db.session.commit()
lst=results(path,subcon,add)
return jsonify({'task': lst})
if __name__ == '__main__':
app.run(debug=True)**
I'm not certain what you use the db.metadata.clear() for in your context.
Most likely, you don't see data in your DB, because there's nothing in your code to create the database relations. Standard solutions would include Alembic (Flask-Migrate package) or adding
with app.app_context():
db.create_all()
to your code.
The particulars are really up to you. Flask-Migrate is quite easy:
Install: pip install flask-migrate
Add to model:
from flask-migrate import Migrate
...
app = Flask(...)
...
#db init code
...
migrate = Migrate(app, db)
Run:
initialize: flask db init
migrate: flask db migrate -m "[YOUR MESSAGE]"
upgrade: flask db upgrade
Here's a good source in addition to the official docs: https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iv-database

django rest framework test code self.client.delete problem

from rest_framework import status, response
from rest_framework.test import APITestCase
from lots.models import Lot
class LotsTestCase(APITestCase):
def setUp(self) -> None:
self.lot = Lot.objects.create(name="1",
address="Dont Know",
phone_num="010-4451-2211",
latitude=127.12,
longitude=352.123,
basic_rate=20000,
additional_rate=2000,
partnership=False,
section_count=3,)
def test_delete(self):
response = self.client.delete(f'api/lots/{self.lot["name"]}')
# response = self.client.delete(f'/api/users/{self.users[0].pk}')
# url = reverse(f'/api/lots/{self.lot}', kwargs={'pk': self.lot.pk})
# self.client.delete(url)
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
self.assertEqual(self.lot.objects.filter(pk=self.lot.pk.count()))
I have problems with the test code above. Why doesn't it work? I know it has to do with calling dictionary values but I just can't figure it out. Thanks for your help.
Lot.objects.create(...) returns a Lot type so you access name by self.lot.name.

SoapUI API - Setting TestCase property

I'm trying to use SoapUI API in jython (modifying SoapUILibrary for Robot Framework) and somehow i am not able to find any way to set property of a Property TestStep.
Setting project, global and system properties is easy using
SoapUITestCaseRunner.setProjectProperties()
from com.eviware.soapui.tools import (SoapUITestCaseRunner)
from com.eviware.soapui.tools import (SoapUIMockServiceRunner)
from robot.api import logger
class SoapUILibrary2:
""" The main class of the library """
ROBOT_LIBRARY_SCOPE = 'TEST CASE'
ROBOT_LIBRARY_VERSION = '0.2'
def __init__(self):
self.__runner = None
self.__mockrunner = None
self._project_properties = []
def soapui_project(self, prj):
""" Initialize the runner and set the project string """
self.__runner = SoapUITestCaseRunner()
self.__runner.setProjectFile(prj)
def soapui_suite(self, s):
""" Set the suite string """
self.__runner.setTestSuite(s)
def soapui_case(self, c):
""" Set the test case string """
self.__runner.setTestCase(c)
def soapui_set_project_property(self, *properties):
""" Sets project properties for the current test run. (...)
"""
for prop in properties:
if len(prop.split('=')) == 2:
self._project_properties.append(prop)
else:
logger.warn("Skipping property: '%s'. Properties must be specified as: key=value" % prop)
try:
self.__runner.setProjectProperties(self._project_properties)
except AttributeError:
logger.warn('No project set. Cannot set project properties.')
SoapUITestCaseRunner class does not contain any way to access testSteps...
I found some examples how to solve this issue in groovy, however is it possible to set such properties using SoapUI API?
EDIT:
Adding whole code of the library. It's made to be imported in robot framework and used as its keywords.
http://tny.cz/34882261
In SOAPUI you can define properties for project, testCase and testSuite, it's also possible to generate a special type of testStep (Properties TestStep) but you can't define properties on a specific testStep (i.e on SOAP TestStep). You can see more info about here
However you can use a properties from project, testCase or testSuite in your testSteps so i.e you can define a property in a project level and then use it in your testStep. I can't give more specific info because I don't know exactly what you're trying to achieve.
EDIT:
I don't know the specific jython syntax but If you have the project file (as I see in your sample) you can access a specific testStep through com.eviware.soapui.impl.wsdl.WsdlProject, I give you a groovy script as example:
import com.eviware.soapui.impl.wsdl.WsdlProject;
import com.eviware.soapui.impl.wsdl.WsdlTestSuite;
import com.eviware.soapui.impl.wsdl.testcase.WsdlTestCase;
import com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStep
def prj = new WsdlProject(path_prj_file,null);
def tsuite = prj.getTestSuiteByName("TestSuiteName");
def tcase = tsuite.getTestCaseByName("TestCaseName");
def tstep = tcase.getTestStepByName("TestStep");
EDIT 2:
I download jython standalone version 2.5.3 and use soapui 5.0.0 and works for me:
hw.py
from com.eviware.soapui.tools import (SoapUITestCaseRunner)
from com.eviware.soapui.tools import (SoapUILoadTestRunner)
from com.eviware.soapui.tools import (SoapUIMockServiceRunner)
from com.eviware.soapui.impl.wsdl import (WsdlProject)
from com.eviware.soapui.impl.wsdl import (WsdlTestSuite)
from com.eviware.soapui.impl.wsdl.testcase import (WsdlTestCase)
from com.eviware.soapui.impl.wsdl.teststeps import (WsdlTestRequestStep)
import thread
class SoapUI2:
""" The main class of the library """
ROBOT_LIBRARY_SCOPE = 'TEST CASE'
ROBOT_LIBRARY_VERSION = '0.2'
def __init__(self):
self.__runner = None
self.__mockrunner = None
self._project_properties = []
self.__prj = WsdlProject('C:\soapui_project.xml', None)
self.__tsuite = self.__prj.getTestSuiteByName("myTestSuite")
self.__tcase = self.__tsuite.getTestCaseByName("myTestCase")
self.__tstep = self.__tcase.getTestStepByName("myTestStep")
t = self.__tstep.getPropertyValue("Value")
print "Works ok"
def soapui_project(self, prj):
""" Initialize the runner and set the project string """
self.__runner = SoapUITestCaseRunner()
self.__runner.setProjectFile(prj)
def soapui_multiproject(self, prj):
""" Initialize the runner and set the project string """
self.__runner = SoapUILoadTestRunner()
self.__runner.setProjectFile(prj)
def soapui_suite(self, s):
""" Set the suite string """
self.__runner.setTestSuite(s)
def soapui_case(self, c):
""" Set the test case string """
self.__runner.setTestCase(c)
def soapui_set_project_property(self, *properties):
""" Sets project properties for the current test run.
This assumes that you have already initialized the project via
the `SoapUI Project` keyword.
`properies` may contain multiple statements, and each must be specified as: key=value.
This is useful to data drive your existing SoapUI tests via property expansion.
For more information see: http://www.soapui.org/Scripting-Properties/property-expansion.html
Example:
| SoapUI Project | My Project |
| SoapUI Set Project Property | ServiceEndpoint=https://staging.company.com | # set a single property |
| SoapUI Set Project Property | CustomProperty=foo | AnotherProperty=bar | # or set multiple properties |
"""
for prop in properties:
if len(prop.split('=')) == 2:
self._project_properties.append(prop)
else:
logger.warn("Skipping property: '%s'. Properties must be specified as: key=value" % prop)
try:
self.__runner.setProjectProperties(self._project_properties)
except AttributeError:
logger.warn('No project set. Cannot set project properties.')
def soapui_set_multiproject_threads(self, t):
""" Sets number of threads to run in load test """
self.__runner.setThreadCount(long(t))
logger.info("Running with %s threads at once." % t)
def soapui_run(self):
""" Run the runner and report to Robot """
logger.info("Running with the following project properties set: %s" % self._project_properties)
if not self.__runner.run():
raise AssertionError('FAIL: failed to run')
if self.__runner == SoapUITestCaseRunner():
n = self.__runner.getFailedTests().size()
if n != 0:
raise AssertionError('FAIL: ' + str(n) + ' tests failed')
def soapui_start_mock_service(self, p, m):
""" Runs a mock service """
try:
self.__mockrunner = SoapUIMockServiceRunner()
self.__mockrunner.setProjectFile(p)
self.__mockrunner.setMockService(m)
self.__mockrunner.setBlock(False)
self.__mockrunner.run()
except Exception, e:
raise AssertionError('FAIL: Error running the mock service ' + m + '. Reason: ' + str(e))
def soapui_stop_mock_service(self):
""" Stops the mock service """
self.__mockrunner.stopAll()
def soapui_set_step_property(self, s, p,v):
testStep = self.__runner.testCase.getTestStepByName(s)
testStep.setPropertyValue(p,v)
if __name__ == "__main__":
SoapUI2().__init__()
cmd line execution:
java -classpath "jython-standalone-2.5.3.jar;C:\Programari\SoapUI-5.0.0\lib\*;C:\Programari\SoapUI-5.0.0\bin\*" org.python.util.jython hw.py
execution result:
2014-05-27 12:43:09,058 [main] WARN com.eviware.soapui.SoapUI - Could not find jfxrt.jar. Internal browser will be disabled.
12:43:09,589 WARN [SoapUI] Missing folder [C:\temp\ext] for external libraries
12:43:09,964 INFO [DefaultSoapUICore] initialized soapui-settings from [C:\Documents and Settings\aciffone\soapui-settings.xml]
12:43:09,995 INFO [HttpClientSupport$Helper] Initializing KeyStore
12:43:11,682 INFO [WsdlProject] Loaded project from [file:/C:/soapui_project.xml]
Works ok
Hope this helps,

OperationalError no such table in Flask with SQLAlchemy

run.py
if __name__ == '__main__':
config()
app.run()
main.py
import database
app = Flask(__name__)
def config():
app.config.from_object('config.DevConfig')
# Run SQLAlchemy _that uses app.config_ and add entities if in DEBUG mode
database.init_db(app)
import blueprints.auth
app.register_blueprint(blueprints.auth.auth)
database.py
db = None
def init_db(app):
global db
db = SQLAlchemy(app)
from models import User, Interest, Event
if app.config['DEBUG']:
print 'Recreating all db'
db.create_all() # I DO create everything
print 'Loading test data'
... (here I add some Users and etc. and everything works fine - tests pass)
models.py
from database import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
...
blueprints/auth.py
from models import User
auth = Blueprint('auth', __name__)
#auth.route('/')
def index():
return str(User.query.get(1).interests)
And so I get
OperationalError: (OperationalError) no such table: user u'SELECT user.id AS user_id, user.username AS user_username, user.email AS user_email, user.passhash AS user_passhash, user.vk_page AS user_vk_page \nFROM user \nWHERE user.id = ?' (1,)
What am I doing wrong?
For anyone trying to use an in memory database:
from sqlalchemy import create_engine
from sqlalchemy.pool import StaticPool
engine = create_engine(
"sqlite://",
connect_args={"check_same_thread": False},
poolclass=StaticPool
)
There were few things I had to change to make everything work.
replace DATABASE_URI with SQLALCHEMY_DATABASE_URI parametr in config
replace :memory: sqlite address with /tmp/test.db
Now it works fine.

Test fails in tests.py but succeeds in python shell

I'm a newbee to python and django and I can't figure out what I'm doing wrong here.
I have a Site object:
class Site (models.Model):
domain = models.CharField(max_length=30)
support_status = models.CharField(max_length=20, choices= SITE_SUPPORTED_STATUS, blank=False)
requests = models.IntegerField()
objects = SiteManager()
def __unicode__(self):
return u'%s %s' % (self.domain, self.support_status)
And a SiteManager object
class SiteManager(models.Manager):
def supported_site_counts(self):
i = self.filter(support_status__iexact="SUPPORTED").count()
return i
From the console, the method "supported_site_counts()" works just fine
>>(InteractiveConsole)
>>> from bookmark.models import Site, SiteManager
>>> Site.objects.supported_site_counts()
>>>>2012-05-18 18:09:20,027 DEBUG (0.001) SELECT COUNT(*) FROM "bookmark_site" WHERE
>>>>"bookmark_site"."support_status" LIKE SUPPORTED ESCAPE '\' ; args=(u'SUPPORTED',)
>>>>2012-05-18 18:09:20,028 DEBUG Got 1 supported site
>>>>1
But when it's called from a testcase, the count returns as 0
class SiteManagerTest(unittest.TestCase):
def test_supported_site_counts(self):
self.x = False
self.count = Site.objects.supported_site_counts()
logging.debug(self.count)
This is probably because the tests will set up a database separate from your development database to run the tests in. You will need to put testing data in to the testing database, either programmatically or using fixtures.