Flask app not running on development configuration - python

i am running a flask application, the app is running but not following the configurations i have set.This is the config file
import os
class Config(object):
"parent configuration class"
DEBUG= True
class DevelopmentConfig(Config):
"Configurations for Development"
DEBUG = True
connectionVariables="dbname='store-manager' user='postgres' password="1235" host='localhost' port='5432'"
os.environ['ENVIRONMENT']='development'
class TestingConfig(Config):
"""Configurations for Testing,"""
TESTING = True
DEBUG = True
connectionVariables="dbname='store-manager-test' user='postgres' password="1235" host='localhost' port='5432'"
os.environ['ENVIRONMENT']='testing'
app_config = {
'development': DevelopmentConfig,
'testing': TestingConfig
}
Whenever i run the app it runs on testing mode even when i have specified development, however, if i remove the testing configuration, it runs on development environment.
This is how am creating the app
from flask import Flask
from flask_restful import Api
from instance.config import app_config
from connection import DbBase
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(app_config[config_name])
return app
This is how am running it.
import os
from app import create_app
config_name = 'development'
app = create_app(config_name)
# method to run app.py
if __name__ == '__main__':
app.run()

Depending on how you're actually running it and on what platform, you need to be sure to specify the location of the config.file.
export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg
or for windows
set YOURAPPLICATION_SETTINGS=\path\to\settings.cfg
I'm not seeing it in the above description, so this may the the problem.
Flask Doc on using a config File

Related

Flask: db is not being referenced properly when importing into my database seeder script

# project\__init__.py
from flask import Flask
from flask_mysqldb import MySQL
from .config import app_config
db = MySQL()
def create_app(config_name):
app = Flask(__name__,
instance_path=os.path.join(os.path.dirname(__file__), 'instance'),
instance_relative_config=True)
app.config.from_object(app_config[config_name])
db.init_app(app)
print(db) # prints <flask_mysqldb.MySQL object at 0x000002A13710FC10>
# project/main.py
from . import db
#main.route('/foobar')
def foobar():
print(db) # prints <flask_mysqldb.MySQL object at 0x000002A13710FC10>
# project/database/seed_shipment.py
from project import create_app, db
def foo():
.
.
.
def goo()
.
.
.
if __name__ == '__main__':
config_name = os.getenv('FLASK_ENV')
app = create_app(config_name)
cursor = db.connection.cursor()
print(db) # prints <flask_mysqldb.MySQL object at 0x000002056B4EFD60>
print(db.connection) # returns None
for x in range(20):
# code which generates dummy data using foo() and goo()
cursor.execute("INSERT INTO shipment (column1, column2) VALUES (%s)", (var1, var2))
db.connection.commit()
My database connection works fine when I host the app and carry out CRUD operations using the interface in my browser. Such as login, sign up, create a shipment.
Note that I am not executing flask run from my terminal but instead python -m project.run, here is the code of this script:
# project/run.py
import os
from . import create_app
config_name = os.getenv('FLASK_ENV')
app = create_app(config_name)
if __name__ == '__main__':
app.run()
However, when I run python -m project.database.seed_shipment db seems to reference a different MySQL instance which has no connection. See the print results in the comments in my code.
My database connection works fine when I host the app and carry out CRUD operations using the interface in my browser. Such as login, sign up, create a shipment.
This indicates to me that you are correctly connecting to your db for each request.
However, when I run python -m project.database.seed_shipment db seems to reference a different MySQL instance which has no connection. See the print results in the comments in my code.
This, on the other hand, indicates to me that you are not connecting to your db when you directly execute seed_shipment - in fact, you seem to reference something different (as you write). In other words, db = MySQL() is not called.
I recommend that you try the following.
# project\__init__.py
from flask import Flask, g
from flask_mysqldb import MySQL
from .config import app_config
def create_app(config_name):
app = Flask(__name__,
instance_path=os.path.join(os.path.dirname(__file__), 'instance'),
instance_relative_config=True)
app.config.from_object(app_config[config_name])
# this here is just to register the teardown context and some variables ....
MySQL(app)
return app
def get_db():
if 'db' not in g:
g.db = MySQL().connection.cursor()
return g.db
That way, MySQL(app) is always executed when you call create_app. Now, you should be able to simply call get_db each time you want your db.

wsgi not importing system environment variables in Flask

If I run flask app directly, I am getting environment variables, using wsgi I am not getting system variables,
wsgi.py
from myproject import app
if __name__ == "__main__":
app.run()
myproject.ini
[uwsgi]
module = wsgi:app
master = true
processes = 5
#protocol = httpa
protocol = http
socket = 0.0.0.0:8443
#shared-socket = 0.0.0.0:8443
buffer-size=32768
#chmod-socket = 660
#vacuum = true
#https = =0,foobar.crt,foobar.key,HIGH
die-on-term = true
enable-threads = true
vacuum = true
req-logger = file:/var/log/uwsgi/app/cart-req.log
logger = file:/var/log/uwsgi/app/cart-err.log
myproject.py
import logging, re, subprocess, json, hashlib, os, jwt, mysql.connector, datetime
from flask import Flask, request, jsonify
from flask import current_app
from flask_restful import Resource, Api
import socket, logging, sys, os, pkgutil, importlib, inspect, logging.handlers
from importlib import import_module
from logging.config import dictConfig
class GetInput(Resource):
def get(self):
output = os.environ.get("MYSYSVAR")
if output is None:
return {'message': 'System Enviroment Variable not found'}, 404
return {'user': output}, 200
cli = sys.modules['flask.cli']
cli.show_server_banner = lambda *x: None
app = Flask(__name__)
api = Api(app)
api.add_resource(GetInput, '/getinput')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8443, debug=True)
This is Linus OS (Cent OS), I set enviroment variable like below
added entry in /etc/profile
export MYSYSVAR=4
I also tried adding entry in below file
/etc/environment
MYSYSVAR=4
source /etc/environment
Not sure, it is not working If I run with web gateway that is wsgi, but it works if I run directly myproject.py
Note: system inbuilt variable like USER working
Can anyone help how to fix it.
you need to add your env file in the virtualhost like:
<VirtualHost *:443>
...
SetEnv /dir/to/app/folder/.env
...
</VirtualHost>

Mongoengine connecting to atlas No replica set members found yet

after a working production app was connected to local mongo, we've decided to move to Mongo Atlas.
This caused production errors.
Our stack is docker -> alping 3.6 -> python 2.7.13 -> Flask -> uwsgi (2.0.17) -> nginx running on aws
flask-mongoengine-0.9.3 mongoengine-0.14.3 pymongo-3.5.1
when starting the app in staging/production, The uwsgi is sending No replica set members found yet.
We don't know why.
We've tried different connection settings connect: False which is lazy connecting, meaning not on initializing, but on first query.
It caused the nginx to fail for resource temporarily unavailable error on some of our apps. We had to restart multiple times for the app to finally start serving requests.
I think the issue is with pymongo and the fact that it's not fork-safe
http://api.mongodb.com/python/current/faq.html?highlight=thread#id3
and uwsgi is using forks
I suspect it might be related to the way my app is being initalized.
might by aginst Using PyMongo with Multiprocessing
here is the app init code:
from app import FlaskApp
from flask import current_app
app = None
from flask_mongoengine import MongoEngine
import logging
application, app = init_flask_app(app_instance, module_name='my_module')
def init_flask_app(app_instance, **kwargs):
app_instance.init_instance(environment_config)
application = app_instance.get_instance()
app = application.app
return application, app
# app_instance.py
import FlaskApp
def init_instance(env):
global app
app = FlaskApp(env)
return app
def get_instance():
if globals().get('app') is None:
app = current_app.flask_app_object
else:
app = globals().get('app')
assert app is not None
return app
class FlaskApp(object):
def __init__(self, env):
.....
# Initialize the DB
self.db = Database(self.app)
....
# used in app_instance.py to get the flask app object in case it's None
self.app.flask_app_object = self
def run_server(self):
self.app.run(host=self.app.config['HOST'], port=self.app.config['PORT'], debug=self.app.config['DEBUG'])
class Database(object):
def __init__(self, app):
self.db = MongoEngine(app)
def drop_all(self, database_name):
logging.warn("Dropping database %s" % database_name)
self.db.connection.drop_database(database_name)
if __name__ == '__main__':
application.run_server()
help in debugging this will be appreciated!

flask socketio not starting

Trying to get a flask socketio app going.
Here's my init.py
import os
from flask import Flask, logging
from flask_socketio import SocketIO
from flask_sqlalchemy import SQLAlchemy
from config import app_config
database = SQLAlchemy()
socket_io = SocketIO()
def create_app(config_name):
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(app_config[config_name])
database.init_app(app)
socket_io.init_app(app)
from .home import home as home_blueprint
app.register_blueprint(home_blueprint)
return app
and here is my run.py
#!/usr/bin/env python3
import sys
from app import create_app, socket_io
config_name = sys.argv[1]
app = create_app(config_name)
if __name__ == "__main__":
socket_io.run(app)
When I start up the app, this is the log output in the python console:
C:\AnacondaPython\python.exe D:/workspaces/App/run.py development
* Restarting with windowsapi reloader
* Debugger is active!
* Debugger PIN: 189-233-458
And then nothing happens.
When I open the app in the browser, it just keeps loading.
How do I do this correctly?
I'll provide more code if necessary.
Thanks for any help and tips!

How to make web.py work with livereload

I'm using web.py for an app and I'd like to use livereload while being in development but I can't figure out how to make the two get along?
app.py
import web
from livereload import Server
urls = (
'/', 'index'
)
class index:
def GET(self):
return "Hello, Kitty"
if __name__ == '__main__':
app = web.application(urls, globals()).wsgifunc()
server = Server(app)
server.serve()
I'm following https://github.com/lepture/python-livereload
server = Server(app.wsgi_app)
server.serve()
in my terminal I type
livereload app.py
and I see
[I 161130 14:05:03 server:283] Serving on http://127.0.0.1:35729
[I 161130 14:05:03 handlers:60] Start watching changes
[I 161130 14:05:03 handlers:62] Start detecting changes
but in the browser when loading http://127.0.0.1:35729 I see this
import web
from livereload import Server
urls = (
'/', 'index'
)
class index:
def GET(self):
return "Hello, Pussy"
if __name__ == '__main__':
app = web.application(urls, globals()).wsgifunc()
server = Server(app)
server.serve()
I see the python script rendered as plain tex.
Update
I decided to give the whole thing a second try, and succeeded, good for me :)
from livereload import Server
import web
from nestpas.views import *
from nestpas.urls import *
import sys
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
# web.config.debug = False
web.ctx.debug = False
app = web.application(urls, globals(), autoreload=False)
webapp = app.wsgifunc()
if __name__ == '__main__':
## app.run()
server = Server(webapp)
server.watch('static/', 'templates/', 'nestpas/')
server.serve(port=8080, host='localhost')
The files I'm using are stored in static, templates and nestpas which is where the Python modules are stored. I ran into some issues having sessions stored on disk, but I managed to change that as well by using the DBStore instead
from livereload import Server
import web
from nestpas.views import *
from nestpas.urls import *
import sys
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
# web.config.debug = False
web.ctx.debug = False
app = web.application(urls, globals(), autoreload=False)
webapp = app.wsgifunc()
# Setup session storage
db = web.database(dbn='sqlite', db='dev.db')
store = web.session.DBStore(db, 'sessions')
session = web.session.Session(app, store)
if __name__ == '__main__':
## app.run()
server = Server(webapp)
server.watch('static/', 'templates/', 'nestpas/')
server.serve(port=8080, host='localhost')
The next goal is to figure out how to use Livereload only when on localhost and not have to think about it when deploying to production.

Categories

Resources