how to create engine from flask-SQLAlchemy object? - flask

I have the following code:
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash
import pypyodbc
import pdb
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mssql+pypyodbc://SERVERNAME/DB'
db = SQLAlchemy(app)
#app.route('/')
def main():
result = db.engine.execute('SELECT * from Table')
return render_template('index.html')
This results in the following error:
ImportError: DLL load failed: The specified procedure could not be found.
I cannot find an example of this in the documentation...what is the correct way to use the SQLAlchemy object's engine?
Thanks!

Related

ImportError: cannot import name 'app' from partially initialized module 'market' (most likely due to a circular import)-Flask

#market package
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from market import routes
app = Flask(__name__)
app.config\['SQLALCHEMY_DATABASE_URI'\] = 'sqlite:///market.db'
db = SQLAlchemy(app)
----------
from market import db #(models)
----------
from market import app #(routes)
from flask import render_template
from market.models import Item
----------#run
from market import app
if __name__ == '__main__':
app.run(debug=True)
Structuring the code into packages then importing modules but then getting the above error

flask NoAppException but flask run works

I have the following structure:
app_dir/
| myapi/
| __init__.py
| myapi_app.py
where myapi_app.py is
from myapi import create_app, db
app = create_app()
and myapi/__init__.py is
import logging
import os
from logging.handlers import RotatingFileHandler
from flask import Flask, request, current_app
from flask_sqlalchemy import SQLAlchemy
from myapi.config import Config
db = SQLAlchemy()
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
db.init_app(app)
...
return app
When I set FLASK_APP=myapi_app.py and run flask run from the app_dir directory, the flask service starts. However, when I make a request, I get the following error: flask.cli.NoAppException: Could not import "myapi_app". Where am I going wrong?
Your problem is that you are setting $FLASK_APP to the file in which the app variable is stored, you should instead set it to the python object path, e.g.
FLASK_APP=myapi_app:app
However, this is not necessary, as you could also just do:
FLASK_APP=myapi
as Flask will look for a create_app function in the package on its own.

flask init_db in app_context vs not? what is the difference?

I have multiple apps and use flask_sqlalchemy with the style below:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def create_app():
app = Flask(__name__)
db.init_app(app)
return app
However, in the test, all the app linked to the same database.
after I switch to the following style. Every app can linked to its own database.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def create_app():
app = Flask(__name__)
with app.app_context():
db.init_app(app)
return app
I did not understand why? If the second case is better, why it is not in the official doc?
credit: I copied the second style from https://hackingandslacking.com/demystifying-flasks-application-context-c7bd31a53817
Each app you create has it is own context, using the below block of code:
with app.app_context():
db.init_app(app)
means that you initialize those instances to that app context only and trying to access those instances somewhere else will result in the below error.
RunTimeError: Working outside of application context.
You can read more about Flask app context here

When packaging a flask app using flask_socketio with pyinstaller, it throws an error: ValueError: Invalid async_mode specified

I have already tried this.
I have the following code:
from flask import Flask
from flask_cors import CORS
from flask_socketio import SocketIO
app = Flask(__name__)
CORS(app)
app.config['SECRET_KEY'] = 'some_secret'
socketio = SocketIO(app)
The error is thrown in the last line of the code

python flask ImportError: No module named views.login

I have a app named flaskr. When I want to import views.login` from views. it gives me error:
File "C:\Projects\flaskr\flaskr.py", line 28, in <module>
from flaskr.views.login import login
ImportError: No module named views.login
Before I put all the methods inside the flaskr.py file. I want to move each functions to different views, like login, show_entries, log_out, just like MVC has different views.
flaskr.py
from sqlite3 import dbapi2 as sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
import os
app = Flask(__name__)
app.config.from_object(__name__)
from flaskr.views.login import login
app.register_blueprint(login)
if __name__ == '__main__':
app.run(debug = True)
login.py
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
from jinja2 import TemplateNotFound
login = Blueprint('login', __name__,template_folder='../template')
#app.route('/login')
def login():
return render_template('login.html')
Create folder named app or whatever.
Create __init__.py file in app:
from sqlite3 import dbapi2 as sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
import os
app = Flask(__name__)
app.config.from_object(__name__)
from app import views
app.register_blueprint(views.login)
Move app.run method into separate start.py file in root directory
from app import app
if __name__ == '__main__':
app.run(debug = True)
Create folder views in app/. Create __init__.py in views
Now you could have structure like this:
your_project_name/
|app/
|__init__.py
|views/
|__init__.py
|login.py
start.py
Sorry, if there are have mistakes.