I've set up an Application on OpenShift like this:
I am using Flask with python on the server-side.
Note: I just need to connect Python to MySQL, Flask is irrelevant.
My Hello World program works fine:
flaskapp.py
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return "Hello World!"
if __name__ == '__main__':
app.run()
In the requirements.txt the following dependency was added: Flask==0.10.1
I'm wondering is it necessary to add the MySQL dependency, like this: MySQLdb==5.5?
I've tried importing and using MySQL in flaskapp.py like this:
from flask import Flask
import mysql # I tried MySQLdb as well
app = Flask(__name__)
#app.route('/')
def hello_world():
output = ''
db = mysql.connect(host="mysql://$OPENSHIFT_MYSQL_DB_HOST:$OPENSHIFT_MYSQL_DB_PORT/", # your host, usually localhost
user="adminIChJ87N",
passwd="mypassword",
db="python")
cur = db.cursor()
cur.execute("SELECT * FROM MyTable")
for row in cur.fetchall():
output+=row[0]
db.close()
return output
if __name__ == '__main__':
app.run()
How exactly do I use this MySQL database with Python? There seems to be no code on Openshift's website
The name of the package for MySQLdb is mysqlclient (if you want it to work with Python3, otherwise it is a fork of MySQL-python). So this is what you need to put in the dependencies. Run pip install mysqlclient to try it.
Related
I am using apscheduler in a flask application where i pull data from a site every 5 miniutes and insert data every 5 miniutes.The apsscheduler works fine till this point.But the problem occurs whenever i hit this server address http://127.0.0.1:5000 . anyhow through any api i get an assertion error:
AssertionError: A setup function was called after the first request was handled. This usually indicates a bug in the application where a module was not imported and decorators or other functionality was called too late.
To fix this make sure to import all your view modules, database models, and everything related at a central place before the application starts serving requests.
After this the save api stop working.The database doesnot work anymore.From what i get it happens due to sqlalchemy error.
this is app.py file:
from apscheduler.schedulers.background import BackgroundScheduler
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from Config.config import Config
from Service.anyService import job
app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
db.init_app(app)
scheduler = BackgroundScheduler()
scheduler.add_job(func=job, trigger="interval", seconds=300, args=[app])
scheduler.start()
if __name__ == "__main__":
from waitress import serve
serve(app, host="0.0.0.0", port=5000)
this is the file for saving data:
from flask_sqlalchemy import SQLAlchemy
def job(app):
db = SQLAlchemy(app)
connection = db.engine.connect(close_with_result=True)
# pull some data from a site and sql query to inset data
db.session.add()
db.session.commit()
I am using waitress server.the application seems to be working fine if i run python -m flask run. But if i run python3 app.py and i hit the server it stops working on saving data.what am i doing wrong here
I have been using the following python 3 script in a CDSW session which run just fine as long as the session is not killed.
I am able to click on the top-right grid and select my app
hello.py
from flask import Flask
import os
app = Flask(__name__)
#app.route('/')
def index():
return 'Web App with Python Flask!'
app.run(host=os.getenv("CDSW_IP_ADDRESS"), port=int(os.getenv('CDSW_PUBLIC_PORT')))
I would like this app to run 24/7, so instead of using a Session or scheduling a job that never ends, I would like to create a CDSW Application so that it doesn't stop.
This is the settings on my application:
Logs:
from flask import Flask
import os
app = Flask(__name__)
#app.route('/')
def index():
return 'Web App with Python Flask!'
app.run(host=os.getenv("CDSW_IP_ADDRESS"), port=int(os.getenv('CDSW_PUBLIC_PORT')))
* Serving Flask app "__main__" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: off
OSError: [Errno 98] Address already in use
I tried to change the port from CDSW_PUBLIC_PORT to CDSW_APP_PORT but it ends up the same.
As it mentions here maybe you need to change this line of code
app.run(host=os.getenv("CDSW_IP_ADDRESS"), port=int(os.getenv('CDSW_PUBLIC_PORT')))
to this
app.run(host="127.0.0.1", port=int(os.environ['CDSW_APP_PORT']))
Hope it works!
I have this code which is receiving a call from pubnub, it takes in text and I want to store that text in a mysql database
class MySubscribeCallback(SubscribeCallback):
def message(self, pubnub, message):
messageArray = message.dict
print(messageArray['message']['sender'])
cursor = db.connection.cursor(MySQLdb.cursors.DictCursor)
I keep receiving this error when trying to run my code
cursor = db.connection.cursor(MySQLdb.cursors.DictCursor)
AttributeError: 'NoneType' object has no attribute 'cursor'
Any ideas on where the problem is?
Your code must looks like that :
from flask import Flask
from flask_mysqldb import MySQL
app = Flask(__name__)
db = MySQL(app)
# Your class/method where db.connection.cursor() is called
if __name__ == '__main__':
app.run() # or app.run(debug=True)
Follow these steps below:
You will need to install mysql connector using the command below
python -m pip install mysql-connector-python
The below code is a simple connection you can use after installing the package
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
print(mydb)
# 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.
The code below works on localhost. I get the message '50' which is the number of rows I have. But it doesn't work when I push it to heroku. I get the "Application error message" and the heroku logs just say app crashed.
And yes, the heroku app has the mongolab add-on connected.
What am I doing incorrectly?
import os
from flask import Flask
from flask.ext.pymongo import PyMongo
app = Flask(__name__)
app.debug = True
app.config['MONGO_URI'] = os.environ['MONGOLAB_URI']
mongo = PyMongo(app, config_prefix='MONGO')
#app.route("/")
def hello():
num = mongo.db.test.count()
return '%s' % num
if __name__ == "__main__":
app.run()
On heroku (unless you've changed it) mongolab stores its URI at MONGOLAB_URI (per these docs).
The crash is probably PyMongo saying it can't connect to NULL, but you can check that with heroku logs on the cli.
Check that you PyMongo version is compatible with Mongo 3.0. MongoLab has switched to it recently: http://blog.mongolab.com/2015/07/mongodb-version-3-0-now-ga-on-mongolab/