How to use mongohq or mongolab on OpenShift - python

I want to use mongoHQ in my application A part of code in views.py:
from pymongo import MongoClient
def connect_db():
client = MongoClient('mongodb://myname:mypassword#paulo.mongohq.com:10087/blog')
return client
#app.before_request
def before_request():
g.db = connect_db()
It's ok on localhost .
But it arise an HTTP 500 error on my browser when I deployed my app upon OpenShift.
(pymongo has been installed on OpenShift server.)
Anyone can help me
Thank you

There is a MongoHQ quickstart located here:
https://github.com/MongoHQ/mongohq-openshift-quickstart
While its a ruby app and not a python app it should point you in the right direction for your app config.

I had a similar problem earlier today. I solved it by adding the following line to requirements.txt:
pymongo==2.8.1

Related

Flask talisman not working and redirects to https://localhost:8000

I have been running flask-talisman on my development server and everything checks out fine. Yet, with the same code and requirements installed on my dedicated server for production (Almalinux), just adding Talisman(app) after app = Flask(__name__) results in the webpage not loading with a redirection to https://localhost:8000. The error message that I precisely get on my browser after typing in the domain is:
This site can't be reached - localhost refused to connect
I am running Nginx 1.14.1 with gunicorn 20.1.0 and supervisor. The server is connected to the internet and without using Talisman it has run smoothly so far.
List of things that I tried without any effect
temporarily stopped firewall
restarted nginx
both tried to access the website through its domain and IP address - the redirection to localhost:8000 remains
tried to run the app on other ports, e.g. 8000 for testing
stripped down the code to a mere mini tutorial that runs well on my development server but not on my production server. So I figured it can't be the app itself.
checked error logs and there is literally nothing, not in the nginx error log or python app error log. Access log shows nothing usual, the same as if everything checks out.
searched the Internet and found nothing that would point in the right direction and explain the failed redirect to localhost:8000
Here is a stripped down tutorial code that should run but doesn't run on my server:
from flask import Flask
from flask_talisman import Talisman
app = Flask(__name__)
Talisman(app)
app.secret_key = 'kungfoo'
#app.route('/', methods=['GET', 'POST'])
def index():
return "Hello stackoverflow!"
if __name__ == "__main__":
app.run(debug=True)
Well,
proxy_set_header X-Forwarded-Proto $scheme;
does the trick in the nginx.conf within the server's location / {} block. This is stated in the gunicorn docs and can be easily missed...
It is recommended to pass protocol information to Gunicorn. Many web
frameworks use this information to generate URLs. Without this
information, the application may mistakenly generate ‘http’ URLs in
‘https’ responses, leading to mixed content warnings or broken
applications.

How to setup psycopg2 with Google App Engine PostgreSQL database

I have an application that is being run on Google's App Engine and I want it to use the associated PostgreSQL database. I'm using psycopg2 to help me with my SQL queries. However I am not sure how I can set up the connection. This is what I currently have:
con = psycopg2.connect(
host=HOST_NAME, # the IP address of the SQL database
database=DATABASE_NAME, # the name of the database (I'm using the default, so this is "postgres"
user=USER_NAME, # just the user name that I created
password=PASSWORD # the password associated to that user
)
However, when I try to make a request, I get the error psycopg2.OperationalError: could not connect to server: Connection timed out when creating this connection. Is there something I am missing?
It is a little bit tricky, but here is what worked for me. I will help you to set up the Quickstart App Engine with psycopg2 and after that you will get the idea.
Use the Quickstart for Python in the App Engine Flexible Environment documentation to set up and deploy your app.
Use the Connecting from App Engine documentation to connect to your App Engine app to the Cloud SQL Postgre SQL.
I have did slightly modifications in order to make that work:
In app.yaml add:
beta_settings:
cloud_sql_instances: [INSTANCE_CONNECTION_NAME]=tcp:5432
#[INSTANCE_CONNECTION_NAME] = [PROJECT_NAME]:[INSTANCE_ZONE]:[INSTANCE_NAME]
#[INSTANCE_CONNECTION_NAME] can be found at Google Cloud Console Cloud SQL's instance page, under "Instance connection name".
In requirements.txt add:
psycopg2
psycopg2-binary
In main.py add:
#app.route('/connect')
def connect():
try:
#host='172.17.0.1' is the defult IP for the docker container that it is being created during the deployment of the App Engine
conn = psycopg2.connect("dbname='postgres' user='postgres' host='172.17.0.1' password='test'")
return "Connection was established!"
except:
return "I am unable to connect to the database"
Use the gcloud app deploy command to deploy your app.
After the deployment, use the gcloud app browse command to open the app in the browser.
When accessing the link https://[PROJECT_ID].appspot.com/connect
It should respond with Connection was established!

How to run Flask web app without using command? [duplicate]

This question already has answers here:
Are a WSGI server and HTTP server required to serve a Flask app?
(3 answers)
Closed 4 years ago.
I'm running my flask web app on local from command line using python __init__.py command. I want to run/deploy flask web without using any command. Like spring web app.
init.py
from flask import Flask, url_for
from flask import jsonify
from werkzeug.serving import run_simple
from werkzeug.wsgi import DispatcherMiddleware
import db_config
app = Flask(__name__)
app.config['APPLICATION_ROOT'] = '/my-web-app'
def simple(env, resp):
resp(b'200 OK', [(b'Content-Type', b'text/plain')])
return [b'Hello my app User']
#app.route("/")
def hello():
return "Hello world"
#app.route('/test', methods=['GET'])
def get_tasks():
db = db_config.getconnection();
cur = db.cursor()
cur.execute("SELECT * FROM emp")
items = cur.fetchall()
print(items)
db.commit()
cur.close()
db.close()
return jsonify({'tasks': items})
app.wsgi_app = DispatcherMiddleware(simple, {'/my-web-app': app.wsgi_app})
if __name__ == "__main__":
app.run()
Is there any way to create .WAR file of flask web app and deploy it on server? And start web app when we give request.
Is there any way to create a Java .WAR file from a Flask app? Possibly, but I really wouldn't recommend it. Python is not Java.
Is there any way to deploy a Flask application on a server? Oh yes, lots of ways. The Deployment Options page in the Flask documentation lists several options, including:
Hosted options: Deploy Flask on Heroku, OpenShift, Webfaction, Google App Engine, AWS Elastic Beanstalk, Azure, PythonAnywhere
Self-hosted options: Run your own server using a standalone WSGI container (Gunicorn, uWSGI, Gevent, Twisted), using Apache's mod_wsgi, using FastCGI, or using old-school vanilla CGI.
Of the self-hosted options, I would definitely recommend nginx rather than Apache as a front-end web server, and nginx has built-in support for the uWSGI protocol, which you can then use to run your app using the uwsgi command.
But I would definitely recommend looking into one of the hosted options rather than being in the business of running your own web server, especially if you're just starting out. Google App Engine and AWS Elastic Beanstalk are both good platforms to start out with as a beginner in running a cloud web application.

"Connection in use" error in GCP app engine

I am new to GCP App engine. I am trying to make web server using flask on App engine. I tested the version of my code on localhost and it is working fine. But when I am trying to deploy it in the App Engine of GCP it is giving me this strange error "app logs".
error logs
Here is my code for the flask
app.run(threaded = True, host='127.0.0.1', port=80)
Thanks!!
You don't need to call app.run() in your main.py file -- App Engine will do that for you. Simply initialize the app variable in this file instead.

flask - Unable to connect mogodb in heroku

I have an application using Flask and MongoEngine on heroku.
My configuration looks like this:
from flask import Flask
from flask.ext.mongoengine import MongoEngine
app = Flask(__name__)
#am setting proper configuration based on database uri
if os.environ.get('MONGOLAB_URI'):
app.config.from_object(herokuConfig)
else:
app.config.from_object(localConfig)
MongoEngine(app)
This was working fine up to yesterday, but this morning I am unable to run the application.
After looking into heroku debug logs, I observed AutoReconnect: not master error, but I am able to run it locally.
I have read some documentation regarding the above error occurring due to a read_preference setting.
I am unable to solve this, and am looking forward to suggestions.

Categories