How to configure MongoEngine for Heroku - python

I have postgresql as my main database and I am using mongodb for 'audit-trail' purposes.
I am using mongoengine for my django app.
In localhost, in order to connect to mongodb database I did this:
connect('dbname')
and that is it, as documentation suggested.
But this is not working in heroku.
I added MongoLab add-on to my heroku application and they gave me this connections string:
mongodb://<dbuser>:<dbpassword>#ds037622.mongolab.com:37622/heroku_app30998840
Then I tried this:
connect('heroku_app30998840', username='username', password='pwd', host='mongodb://<dbuser>:<dbpassword>#ds037622.mongolab.com:37622/heroku_app30998840')
This did not work either.
How can I fix this?
Or maybe I should use something else other than MongoEngine? some other better way?

That is what worked for me:
connect('heroku_app30998840', username='username', password='pwd', host='#ds037622.mongolab.com:37622')
i.e remove everything except host and port number in host part.

Related

python, logging to db Azure by ActiveDirectoryPassword

I connecting to database on Azure using authentication ActiveDirectoryPassword.
ss
cnxn = pyodbc.connect('DRIVER='+driver+';SERVER='+host+';UID='+user+';PWD='+password+';Authentication=ActiveDirectoryPassword')
It is working. The issue is that using this connection string I do not specify the DB. It just connecting me to master. How can I switch to DB I need. I have tried different connection strings (with database specified) but only this one works with ActiveDirectiryPassword.
You could try the below :
pyodbc.connect('DRIVER='+driver+';SERVER='+host+';DATABASE='+database+';UID='+user+';PWD='+password+';Authentication=ActiveDirectoryPassword')

Connecting Heroku Database to SQLAlchemy

so as part of a Web Programming MOOC, I have to connect to a PostgreSQL Database hosted on Heroku using Python and SQLalchemy. I have spent a lot of hours trying to do this to no avail. My main problem is that I'm not being able to connect to the Database, because every time a try to run a script to update or just check the Database I get "Is the server running on host "ec2-174-129-35-61.compute-1.amazonaws.com" (174.129.35.61) and accepting
TCP/IP connections on port 5432?" in the command prompt.
I've done a lot of research trying to figure it out and it seems that maybe the URI of my Database is not set to accept public connections. But I tried setting ssl = require and still haven't been able to solve the problem. Maybe I didn't do it right?
I have come to think that maybe I am doing something wrong with the code, or that I should try to connect through Heroku's CLI and not the command prompt but I am not sure. This is my simple test code:
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
if not os.getenv("DATABASE_URL"):
raise RuntimeError("DATABASE_URL is not set")
engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))
db.execute("INSERT INTO books VALUES (1, 1, 1, 1)")
db.commit()
I set the DATABASE_URL environment variable in the command prompt to the Database's URI but maybe I did it wrong? I also tried just using the URI in the code itself but still could not make it work.
This is my first time using Databases with Heroku so I am complete neewbie, maybe I am doing something else wrong?. I appreciate all the help that you guys can give. Thanks in advance
1) Check, did you copied all link, including postgres://
2) Maybe you had made a mistake during setting DATABASE_URL. So, try to add your URL directly to the script:
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
engine = "postgres://ennjrjkrfsb____all_code_of_key_.....___compute.amazonaws.com:5432/ddo7541ka3hio7"
db = scoped_session(sessionmaker(bind=engine))
db.execute("INSERT INTO books VALUES (1, 1, 1, 1)")
db.commit()
3) if you are using linux, try to open your database, using command psql postgres://ennjrjkrfsb____all_code_of_key_.....___compute.amazonaws.com:5432/ddo7541ka3hio7
4) Try to access to your database in any way via other internet provider (may be your provider or sys admin in your office restricted access to Heroku)
Update: Try to use free online IDE with interpreter (based on Linux), for example, https://cs50.io - from this site you can access to Heroku postgres
postgres dialect does not support any more in SQLAlchemy v1.4.x above, and it turns into postgresql, so the final connection string must be postgresql://username:password#host:port/database
Here is my working connection from SQLAlchemy to Heroku Postgresql
database_url = os.environ('DATABASE_URL')
if database_url.startswith('postgres://'):
database_url.replace('postgres://', 'postgresql://')
engine = create_engine(database_url)
# rest of your codes...
here is my reference Heroku Issue

Can`t connect MySQL database in phpMyAdmin by python

I need to use python to connect database in phpMyAdmin.
import MySQLdb
db = MySQLdb.connect(host="10.0.0.140",port=80,user="root",passwd="password")
cursor=db.cursor()
cursor.execute("SHOW DATABASES")
results=cursor.fetchall()
for result in results:
print row
and I get this error
2013,"Lost connection to MySQL server at'waiting for initial communication packet',system error:0"
I can access the database in chrome, so I don`t think it is a problem of remote access.
=======================update=======================
The real reason is that I am in a limited net segment.(maybe)
There is something wrong with SQL connection out of my code.
If changed code like this:(port is not needed)
MySQLdb.connect(host="10.0.0.140",user="root",passwd="password")
People in public net segment can connect the phpMyAdmin but I can`t.
I can not change my net segment so I can`t confirm it is the real reason.
But it is the only difference between me and others.
Check the connection, are you sure you run your mysql at port 80?
As I wrote in the comments, I doubt it runs port 80, this is the url to your phpMyAdmin and not the core mysql database server. Normally the web and database run on different machines, different IP addresses etc. Is this a hosted environment? Or do you run this in your local machine.
If it is your local machine then changing to port 3306 should work.
If it is a hosted environment by a hosting partner then you need to check the JDBC url from them. As you wrote it is XXXX hosted partner. Then check your XXX and it will provide you a XXX jdbc url for your mysql, and be sure to grant access to the user so you can logon to the mysql from your workstation remotly. The mysql url/host could be something like this NNNN-aaaa-bbbb-cccc-dddd.xxx.domain.xx
Also did you try the PyMYSQL
import pymysql
db = pymysql.connect(host='10.0.0.140',user='root',passwd='password')
cursor = db.cursor()
query = ("SHOW DATABASES")
cursor.execute(query)
for r in cursor:
print r
This is not the way you should do it. phpMyAdmin serves HTML to the user and should be used in a Web browser. You should connect directly to the MySQL host which is usually listening on port :3306. Also, you should keep in mind that, in production, MySQL servers are ordinarily not listening on public interfaces.

How to use PostgreSQL on a Pyramid App in OpenShift?

How can I use a PostgreSQL database on a Pyramid application? I'm using OpenShift as my "PaaS".
I added the PostgreSQL cartridge and it gave me a sql connection url that looked like this:
postgresql://$OPENSHIFT_POSTGRESQL_DB_HOST:$OPENSHIFT_POSTGRESQL_DB_PORT
But I don't know how and where to use it.
I solved it myself, by adding/replacing this to my "_ _init__.py" and "initializedb.py"
import os
engine = create_engine(os.environ.get('OPENSHIFT_POSTGRESQL_DB_URL'))

OpenShift mysql connection issues in python

I previously wrote my app using local development servers, and now that I have moved it onto an openshift small gear almost all works except for mysql connections.
In my code I have the line:
self.db = MySQLdb.connect(host, username, password, dbname)
When I review the openshift error log, the following error is reported:
_mysql_exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)")
I think that python is trying to connect using a UNIX socket as opposed to an INET one, but I'm not sure how to change this behavior. Any help is much appreciated.
Not specific to MySQLdb: if you use localhost as hostname, a MySQL client using the MySQL C libraries will try to connect using UNIX socket (or named pipe on Windows). There are 2 ways around this, but you'll need to grant extra permissions to make it work for both:
Use IP address 127.0.0.1
Use IP address 127.0.0.1 instead of the localhost hostname. This will make MySQL client connect using TCP/IP.
Use option files
The other way is to force the protocol using using option files. For example, in your ~/.my.cnf (or any file you want), add the following:
[python]
protocol=tcp
Now use the connection arguments to read the option file and group:
import MySQLdb
cnx = MySQLdb.connect(host='localhost', user='scott', passwd='tiger',
read_default_file='~/.my.cnf',
read_default_group='python')
The group name does not need to be python, but it is good not to use mysql or client as it might interfere with other MySQL tools (unless you want that of course).
For setting up permissions, you'll need to use the IP address of localhost, something like:
mysql> GRANT SELECT TO yourdb.* TO 'scott'#'127.0.0.1' IDENTIFIED BY ...;
(Site note: MySQL database drivers such as MySQL Connector/Python do not consider localhost to be special and connect through TCP/IP right away and you have to explicitly use the unix_socket.)
As I later discovered, while the database server runs on localhost, it runs on a very specific localhost bind address. In my case it was an address that I would never have though to try if I hadn't noticed how phpmyadmin was connecting.

Categories

Resources